@classytic/arc 2.52.0 → 2.53.0

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 (222) hide show
  1. package/README.md +2 -1
  2. package/dist/{EventTransport-DeNze_-C.mjs → EventTransport-B3jTKMQH.mjs} +2 -2
  3. package/dist/{HookSystem-DTffXM1X.mjs → HookSystem-DNwxV463.mjs} +2 -2
  4. package/dist/{ResourceRegistry-tlqXSZoK.mjs → ResourceRegistry-Ck7RFodL.mjs} +2 -2
  5. package/dist/{acquire-7JKEkKnN.mjs → acquire-DkLruwhL.mjs} +1 -1
  6. package/dist/audit/index.d.mts +1 -1
  7. package/dist/audit/index.mjs +4 -4
  8. package/dist/auth/audit.mjs +1 -1
  9. package/dist/auth/index.d.mts +1 -1
  10. package/dist/auth/index.mjs +7 -7
  11. package/dist/auth/redis-session.mjs +1 -1
  12. package/dist/auth/social/index.mjs +1 -1
  13. package/dist/{authorizationDecision-DKmH4tZ-.mjs → authorizationDecision-gB5-bHDp.mjs} +5 -5
  14. package/dist/bootError-BT3z3cvX.mjs +38 -0
  15. package/dist/{boundedMap-zxGBpXX0.mjs → boundedMap-Ddw2yGb2.mjs} +1 -1
  16. package/dist/{buildHandler-ZDV6LRZ_.mjs → buildHandler-B8IDGmhD.mjs} +5 -5
  17. package/dist/cache/index.mjs +4 -4
  18. package/dist/{caching-DceUN9Xk.mjs → caching-BitJDAY0.mjs} +2 -2
  19. package/dist/{claimed-DsP5Hi_f.mjs → claimed-CM_-lFHX.mjs} +1 -1
  20. package/dist/cleanup/index.d.mts +2 -2
  21. package/dist/cleanup/index.mjs +4 -4
  22. package/dist/cli/commands/describe.d.mts +18 -1
  23. package/dist/cli/commands/describe.mjs +39 -7
  24. package/dist/cli/commands/docs.mjs +3 -3
  25. package/dist/cli/commands/doctor.d.mts +3 -1
  26. package/dist/cli/commands/doctor.mjs +135 -22
  27. package/dist/cli/commands/generate.mjs +2 -2
  28. package/dist/cli/commands/init.mjs +2 -2
  29. package/dist/cli/commands/introspect.mjs +2 -2
  30. package/dist/cli/index.mjs +3 -3
  31. package/dist/{constants-Ca2IQFy2.mjs → constants-D9EiaO5s.mjs} +1 -1
  32. package/dist/context/index.d.mts +5 -2
  33. package/dist/context/index.mjs +5 -5
  34. package/dist/core/index.d.mts +2 -2
  35. package/dist/core/index.mjs +7 -7
  36. package/dist/{core-M18RhMqi.mjs → core-B_06Fcn0.mjs} +3 -3
  37. package/dist/{createActionRouter-zXlrwWVs.mjs → createActionRouter-DtxUXOCI.mjs} +5 -5
  38. package/dist/{createAggregationRouter-CN0Da9nC.mjs → createAggregationRouter-BMiKyDoW.mjs} +7 -7
  39. package/dist/{createApp-BC67ACu4.mjs → createApp-CEdGZtkP.mjs} +207 -44
  40. package/dist/{createMcpServer-CS2KOVP6.d.mts → createMcpServer-Bk3ls5jS.d.mts} +1 -1
  41. package/dist/{defineAggregation-DqAGb5oI.mjs → defineAggregation-DUsrGcsm.mjs} +1 -1
  42. package/dist/{defineResource-DC5UqkQv.mjs → defineResource-q8TsJpOm.mjs} +92 -36
  43. package/dist/deprecation-DX625dth.mjs +27 -0
  44. package/dist/discovery/index.mjs +1 -1
  45. package/dist/docs/index.d.mts +1 -1
  46. package/dist/docs/index.mjs +3 -3
  47. package/dist/{elevation-DiXVg98q.mjs → elevation-NJ3908pJ.mjs} +5 -5
  48. package/dist/encryption/index.mjs +3 -3
  49. package/dist/{errorHandler-BUTm9P_f.mjs → errorHandler-Ke6PGvF7.mjs} +7 -4
  50. package/dist/{errors-DxpHZBlW.mjs → errors-Ukhmfmmx.mjs} +1 -1
  51. package/dist/{eventPlugin-BY38F6yK.d.mts → eventPlugin-BeJasppx.d.mts} +7 -18
  52. package/dist/{eventPlugin-ZsIQPRso.mjs → eventPlugin-DTKAgSvb.mjs} +10 -8
  53. package/dist/{eventTypes-D-pFtqT1.mjs → eventTypes-DpDQtyR6.mjs} +2 -2
  54. package/dist/events/index.d.mts +2 -2
  55. package/dist/events/index.mjs +8 -8
  56. package/dist/events/transports/redis-stream-entry.mjs +4 -4
  57. package/dist/events/transports/redis.mjs +2 -2
  58. package/dist/factory/index.d.mts +28 -5
  59. package/dist/factory/index.mjs +12 -7
  60. package/dist/{fastify-augmentation-CPReFhZ1.d.mts → fastify-augmentation-DjxuSRG4.d.mts} +4 -3
  61. package/dist/{fieldTypes-f-3TZgR3.mjs → fieldTypes-BtFpQO6I.mjs} +2 -2
  62. package/dist/{fields-kCbIDTjA.mjs → fields-B7fuROWK.mjs} +1 -1
  63. package/dist/{filter-merge-UJCgjbZR.mjs → filter-merge-BuzZ-r9z.mjs} +1 -1
  64. package/dist/{generate-CLpmzbJ_.mjs → generate-c4F39pk1.mjs} +4 -4
  65. package/dist/{headers-Bh47h0XH.mjs → headers-Ib7BDgRI.mjs} +2 -2
  66. package/dist/{health-CEpgVAl7.mjs → health-22T82HAa.mjs} +1 -1
  67. package/dist/health-skjSwNaC.d.mts +36 -0
  68. package/dist/hooks/index.d.mts +1 -1
  69. package/dist/hooks/index.mjs +2 -2
  70. package/dist/http-cache/index.mjs +4 -4
  71. package/dist/http-cache/purgers/cloudflare.mjs +2 -2
  72. package/dist/http-cache/purgers/fastly.mjs +2 -2
  73. package/dist/http-cache/testing/index.mjs +1 -1
  74. package/dist/idempotency/index.d.mts +7 -1
  75. package/dist/idempotency/index.mjs +9 -7
  76. package/dist/idempotency/redis.mjs +2 -2
  77. package/dist/{index-CMNpMBtW.d.mts → index-BzUyno-u.d.mts} +14 -5
  78. package/dist/{index-yXXCsKl7.d.mts → index-CXqYFGoH.d.mts} +13 -4
  79. package/dist/{index-CSbDhif4.d.mts → index-CaBFPmnu.d.mts} +10 -6
  80. package/dist/{index-DCH08eqQ.d.mts → index-DWn0o4U7.d.mts} +2 -2
  81. package/dist/{index-DLCcLUQT.d.mts → index-DtHACefu.d.mts} +109 -116
  82. package/dist/index.d.mts +5 -5
  83. package/dist/index.mjs +12 -12
  84. package/dist/{init-B43DXBpc.mjs → init-XY5slyuS.mjs} +3 -3
  85. package/dist/integrations/event-gateway.mjs +2 -2
  86. package/dist/integrations/index.d.mts +1 -1
  87. package/dist/integrations/index.mjs +1 -1
  88. package/dist/integrations/jobs/index.mjs +3 -3
  89. package/dist/integrations/mcp/index.d.mts +9 -4
  90. package/dist/integrations/mcp/index.mjs +2 -2
  91. package/dist/integrations/mcp/testing.d.mts +2 -2
  92. package/dist/integrations/mcp/testing.mjs +2 -2
  93. package/dist/integrations/streamline.mjs +3 -3
  94. package/dist/integrations/webhooks.d.mts +1 -1
  95. package/dist/integrations/webhooks.mjs +4 -4
  96. package/dist/integrations/websocket-pushref-redis.mjs +1 -1
  97. package/dist/integrations/websocket-redis.mjs +1 -1
  98. package/dist/integrations/websocket.mjs +2 -2
  99. package/dist/invariants-COekUeoh.mjs +120 -0
  100. package/dist/{jsonBody-CkKs6dA_.mjs → jsonBody-BNlcGUnb.mjs} +2 -2
  101. package/dist/{keys-DHrHnT0f.mjs → keys-DwvXJwUX.mjs} +1 -1
  102. package/dist/{loadResources-CFdzAWQZ.mjs → loadResources-izEeQLO_.mjs} +3 -3
  103. package/dist/{loadResourcesFromEntry-DkoSiJsI.mjs → loadResourcesFromEntry-CijqjbHE.mjs} +2 -2
  104. package/dist/logger/index.mjs +2 -2
  105. package/dist/{logger-DJwz_-Pl.mjs → logger-DdMS0XC_.mjs} +1 -1
  106. package/dist/{mcpPlugin-CA_MDFlS.mjs → mcpPlugin-D0tSZqKk.mjs} +24 -22
  107. package/dist/{memory-B9CFHbA_.mjs → memory-Ay0haw9n.mjs} +3 -3
  108. package/dist/{metrics-DSKv-T9K.mjs → metrics-Bpgf4UL6.mjs} +3 -3
  109. package/dist/middleware/index.d.mts +1 -1
  110. package/dist/middleware/index.mjs +3 -3
  111. package/dist/migrations/index.mjs +2 -2
  112. package/dist/{module-C0JCsnO7.mjs → module-BLrTmMyk.mjs} +1 -1
  113. package/dist/{multiTenant-QtDzxx_K.d.mts → multiTenant-Cf0Ye-Wu.d.mts} +1 -1
  114. package/dist/{multipartBody-Bxz-q6hI.mjs → multipartBody-L2gr96df.mjs} +1 -1
  115. package/dist/{observeSend-DfNkdGww.mjs → observeSend-B7FEdk_g.mjs} +1 -1
  116. package/dist/{openapi-Dmp7Ipsi.mjs → openapi-COrL_33P.mjs} +6 -6
  117. package/dist/outbox-admin/index.d.mts +1 -1
  118. package/dist/outbox-admin/index.mjs +6 -6
  119. package/dist/{outbox-module-vT6PaThj.mjs → outbox-module-BY2HtnjU.mjs} +7 -7
  120. package/dist/{outbox-module-DzW6zwWJ.d.mts → outbox-module-C1QWMloZ.d.mts} +5 -8
  121. package/dist/permissions/index.d.mts +2 -2
  122. package/dist/permissions/index.mjs +8 -8
  123. package/dist/{permissions-Cga6KBOX.mjs → permissions-CEyeDHtT.mjs} +36 -17
  124. package/dist/{pipe-CqPweKdL.mjs → pipe-DIAr91at.mjs} +2 -2
  125. package/dist/pipeline/index.d.mts +1 -1
  126. package/dist/pipeline/index.mjs +2 -2
  127. package/dist/{plan-CbDTFbTj.mjs → plan-BhKHIkFl.mjs} +75 -20
  128. package/dist/{plugin-8Z1khbAI.mjs → plugin-D6hrdx-j.mjs} +72 -38
  129. package/dist/plugins/index.d.mts +4 -3
  130. package/dist/plugins/index.mjs +18 -18
  131. package/dist/plugins/response-cache.mjs +4 -4
  132. package/dist/plugins/tracing-entry.mjs +177 -85
  133. package/dist/{pluralize-D4vcPLVs.mjs → pluralize-CJKgYkVc.mjs} +1 -1
  134. package/dist/presetPermission-2pcRVYRG.mjs +23 -0
  135. package/dist/presets/filesUpload.d.mts +4 -2
  136. package/dist/presets/filesUpload.mjs +11 -6
  137. package/dist/presets/index.d.mts +6 -4
  138. package/dist/presets/index.mjs +2 -2
  139. package/dist/presets/multiTenant.d.mts +1 -1
  140. package/dist/presets/multiTenant.mjs +5 -5
  141. package/dist/presets/search.d.mts +2 -2
  142. package/dist/presets/search.mjs +54 -38
  143. package/dist/{presets-D28IABZe.mjs → presets-st11ePNn.mjs} +150 -41
  144. package/dist/{projection-aHCtDQQ9.mjs → projection-B4rqiJTi.mjs} +2 -2
  145. package/dist/{purger.types-CNFmEtFu.mjs → purger.types-BcHeAhY_.mjs} +1 -1
  146. package/dist/{queryCachePlugin-CwpEjCwz.mjs → queryCachePlugin-BgSc2bga.mjs} +6 -6
  147. package/dist/rateLimitKey-DLGdeFd2.mjs +138 -0
  148. package/dist/{realtime-Dvu8ES2z.mjs → realtime-CpYpIFsm.mjs} +11 -11
  149. package/dist/registry/index.d.mts +2 -2
  150. package/dist/registry/index.mjs +3 -3
  151. package/dist/{registry-DmxbzW7-.mjs → registry-BQsdAlZ_.mjs} +2 -2
  152. package/dist/{relay-CEaCmUfG.mjs → relay-CmT3gtkP.mjs} +11 -12
  153. package/dist/{renewingLease-g2FjB3im.mjs → renewingLease-DaoP0K-e.mjs} +1 -1
  154. package/dist/{replyHelpers-CSByAX_Z.mjs → replyHelpers-SiLr1wK4.mjs} +2 -2
  155. package/dist/{requestContext-yc7MSgmq.mjs → requestContext-B-TjFpWt.mjs} +8 -3
  156. package/dist/{health-W4S2yFBL.mjs → requestId-ClcKoWLq.mjs} +154 -116
  157. package/dist/{requirement-Dm8njSoC.mjs → requirement-BygDzjDS.mjs} +1 -1
  158. package/dist/{resourceRateLimit-PQaY3HW1.mjs → resourceRateLimit-DdIYis3m.mjs} +2 -2
  159. package/dist/{rolldown-runtime-BBBkGgwA.mjs → rolldown-runtime-Cy6j0m8_.mjs} +1 -1
  160. package/dist/{routeValidator-fuG51bQA.mjs → routeValidator-Bn-x2gaJ.mjs} +1 -1
  161. package/dist/{runtimeCapabilities-B8IT7xiQ.mjs → runtimeCapabilities-DY20Pibh.mjs} +7 -2
  162. package/dist/{schedules-0-aS4jDV.mjs → schedules-CwqC0Mp0.mjs} +5 -5
  163. package/dist/{schemaConverter-Cs3SwP4R.mjs → schemaConverter-XoLKVpzG.mjs} +2 -2
  164. package/dist/{schemaIR-By8XiNeE.mjs → schemaIR-DP7mMj7c.mjs} +16 -16
  165. package/dist/schemas/index.mjs +1 -1
  166. package/dist/scim/index.mjs +2 -2
  167. package/dist/scope/index.d.mts +6 -2
  168. package/dist/scope/index.mjs +5 -5
  169. package/dist/{scope-BWNAlBj0.mjs → scope-B0vgM2Zw.mjs} +4 -4
  170. package/dist/{shutdown-Cf-27xsS.mjs → shutdown-C76Hn-Th.mjs} +1 -1
  171. package/dist/{simpleEqualityMatcher-e-dgJcUO.mjs → simpleEqualityMatcher-Qbl-11cE.mjs} +1 -1
  172. package/dist/{sse-C3bj5qWi.mjs → sse-eyb8lNuI.mjs} +7 -7
  173. package/dist/{sseStream-BYZbpFDa.mjs → sseStream-BsBesrfw.mjs} +2 -2
  174. package/dist/{store-helpers-B9HierHY.mjs → store-helpers-D1yIVa91.mjs} +1 -1
  175. package/dist/{streaming-EN8NJWxr.mjs → streaming-DKziqs1Z.mjs} +1 -1
  176. package/dist/{subscriberIdentity-DSqCh38x.mjs → subscriberIdentity-DpdSQMQq.mjs} +1 -1
  177. package/dist/{tenancy-CAqjGQcQ.mjs → tenancy-YuRYsOPr.mjs} +2 -2
  178. package/dist/{tenantPreparation-CVBWarqs.mjs → tenantPreparation-Bk8ouRB3.mjs} +17 -5
  179. package/dist/testing/cleanupStoreContract.mjs +1 -1
  180. package/dist/testing/index.d.mts +4 -4
  181. package/dist/testing/index.mjs +11 -11
  182. package/dist/testing/outboxStoreContract.mjs +2 -2
  183. package/dist/testing/requiredPorts.d.mts +1 -1
  184. package/dist/testing/requiredPorts.mjs +2 -2
  185. package/dist/testing/storageContract.mjs +1 -1
  186. package/dist/{timing-CKI_Oyub.mjs → timing-BtIDIdQz.mjs} +1 -1
  187. package/dist/{transactionContext-D0UZFoSy.mjs → transactionContext-BsQ5ortM.mjs} +1 -1
  188. package/dist/{typeGuards-CLYkmBLT.mjs → typeGuards-Cr2_zEW0.mjs} +1 -1
  189. package/dist/types/index.d.mts +2 -2
  190. package/dist/types/index.mjs +1 -1
  191. package/dist/types/storage.mjs +1 -1
  192. package/dist/{types-BeEJm-DV.d.mts → types-CQhHTZXs.d.mts} +48 -35
  193. package/dist/{types-B4E0sc6D.d.mts → types-DWFgq8EP.d.mts} +1 -1
  194. package/dist/{types-Cunc4shv.mjs → types-ZvdR7MVa.mjs} +4 -4
  195. package/dist/usage/index.mjs +4 -4
  196. package/dist/{userHelpers-cT5j1kgp.mjs → userHelpers-CwpEK36a.mjs} +1 -1
  197. package/dist/utils/index.d.mts +1 -1
  198. package/dist/utils/index.mjs +12 -12
  199. package/dist/{utils-DlNkm1dI.mjs → utils-CnrfcYMq.mjs} +6 -6
  200. package/dist/{validate-63QThRoS.mjs → validate-BTQBh-Dr.mjs} +3 -3
  201. package/dist/{versioning-f2YGmh4i.mjs → versioning-DiLykI6U.mjs} +3 -3
  202. package/dist/{workScope-DwspXz70.mjs → workScope-C3tPz_Gt.mjs} +2 -2
  203. package/package.json +34 -9
  204. package/skills/arc/SKILL.md +5 -5
  205. package/skills/arc/references/api-reference.md +1 -1
  206. package/skills/arc/references/boot.md +17 -2
  207. package/skills/arc/references/events.md +0 -1
  208. package/skills/arc/references/mcp-setup.md +3 -2
  209. package/skills/arc/references/multi-tenancy.md +1 -1
  210. package/skills/arc/references/production-api.md +19 -12
  211. package/skills/arc/references/production-audit.md +1 -1
  212. package/skills/arc/references/production-boot.md +3 -3
  213. package/skills/arc/references/production-idempotency.md +2 -2
  214. package/skills/arc/references/production-observability.md +14 -2
  215. package/skills/arc/references/production-reliability.md +1 -1
  216. package/skills/arc/references/querying.md +1 -2
  217. package/skills/arc/references/resources.md +8 -6
  218. package/skills/arc/references/testing.md +1 -1
  219. package/skills/arc-code-review/references/arc-cheatsheet.md +1 -1
  220. package/skills/arc-code-review/references/recipe-scope-permissions.md +1 -1
  221. package/skills/arc-module-publishing/references/resource-assembly.md +2 -2
  222. package/dist/rateLimitKey-D9dl3FQn.mjs +0 -40
@@ -1,132 +1,227 @@
1
- /*! @classytic/arc v2.52.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.53.0 | MIT | https://classytic.com */
2
2
  import { createRequire } from "node:module";
3
3
  import fp from "fastify-plugin";
4
4
  // src/plugins/tracing.ts
5
5
  /**
6
6
  * OpenTelemetry Distributed Tracing Plugin
7
7
  *
8
- * Traces HTTP requests, repository operations, and MongoDB queries
9
- * across the entire application lifecycle.
8
+ * Traces HTTP requests and the spans your code adds (`createSpan`, `traced`).
9
+ * Explicit opt-in: nothing is traced until a host registers this plugin.
10
10
  *
11
11
  * @example
12
- * import { tracingPlugin } from '@classytic/arc/plugins';
12
+ * import { tracingPlugin } from '@classytic/arc/plugins/tracing';
13
13
  *
14
14
  * await fastify.register(tracingPlugin, {
15
15
  * serviceName: 'my-api',
16
16
  * exporterUrl: 'http://localhost:4318/v1/traces', // OTLP endpoint
17
17
  * });
18
18
  *
19
- * ## Type strategy
19
+ * ## What it needs (OpenTelemetry JS SDK 3.x line)
20
20
  *
21
- * `@opentelemetry/api` is the stable surface — its types are type-only
22
- * imported here so hook handlers, `createSpan`, and `traced` don't hand
23
- * out `any` for Tracer / Span. Only the runtime-loaded module BODIES
24
- * (`trace.getTracer`, `context.with`, etc.) go through the optional-require
25
- * path; everything downstream keeps its shape through the plugin.
21
+ * CORE — without any of these the plugin is a no-op with one warning:
22
+ * `@opentelemetry/api`, `@opentelemetry/sdk-trace` (`TracerProvider`),
23
+ * `@opentelemetry/resources`, `@opentelemetry/semantic-conventions`.
26
24
  *
27
- * The SDK-side factories (`NodeTracerProvider`, `BatchSpanProcessor`,
28
- * `OTLPTraceExporter`) aren't in @classytic/arc's devDeps and aren't
29
- * type-importable without adding install weight, so those retain
30
- * minimal constructor-style `unknown`-valued boxes. If a future refactor
31
- * moves SDK types into devDependencies we can tighten further.
25
+ * OPTIONAL — each loads on its own; a missing one is named once and tracing continues:
26
+ * - `@opentelemetry/exporter-trace-otlp-http` — where spans go (warning: not exported).
27
+ * - `@opentelemetry/context-async-hooks` — keeps the request span active across
28
+ * `await`, so instrumentations parent their spans to it (warning).
29
+ * - `@opentelemetry/core` — W3C `traceparent` / baggage propagation (warning).
30
+ * - instrumentations: `@opentelemetry/auto-instrumentations-node`, else
31
+ * `@opentelemetry/instrumentation-http` / `@opentelemetry/instrumentation-mongodb`
32
+ * singly (debug line).
33
+ *
34
+ * A global provider, context manager or propagator the host already registered (for
35
+ * example with `NodeSDK`) is kept: arc then uses it instead of its own.
36
+ *
37
+ * ## Span shape (stable OpenTelemetry HTTP semantic conventions)
38
+ *
39
+ * Name: `{METHOD} {route template}` (`GET /products/:id`), or `{METHOD}` alone when no
40
+ * route matched; never the raw URL, whose ids and query strings make names unbounded.
41
+ * The query string is not recorded (it can carry tokens).
32
42
  */
33
43
  const require = createRequire(import.meta.url);
34
- let trace;
35
- let context;
36
- let SpanStatusCode;
37
- let NodeTracerProvider;
38
- let BatchSpanProcessor;
39
- let OTLPTraceExporter;
40
- let getNodeAutoInstrumentations;
41
- let isAvailable = false;
42
- try {
43
- const api = require("@opentelemetry/api");
44
- trace = api.trace;
45
- context = api.context;
46
- SpanStatusCode = api.SpanStatusCode;
47
- const sdkNode = require("@opentelemetry/sdk-node");
48
- NodeTracerProvider = sdkNode.NodeTracerProvider;
49
- BatchSpanProcessor = sdkNode.BatchSpanProcessor;
50
- OTLPTraceExporter = require("@opentelemetry/exporter-trace-otlp-http").OTLPTraceExporter;
51
- require("@opentelemetry/instrumentation-http");
52
- require("@opentelemetry/instrumentation-mongodb");
53
- getNodeAutoInstrumentations = require("@opentelemetry/auto-instrumentations-node").getNodeAutoInstrumentations;
54
- isAvailable = true;
55
- } catch (_e) {}
44
+ const PKG = {
45
+ api: "@opentelemetry/api",
46
+ sdk: "@opentelemetry/sdk-trace",
47
+ resources: "@opentelemetry/resources",
48
+ semconv: "@opentelemetry/semantic-conventions",
49
+ exporter: "@opentelemetry/exporter-trace-otlp-http",
50
+ contextManager: "@opentelemetry/context-async-hooks",
51
+ core: "@opentelemetry/core",
52
+ auto: "@opentelemetry/auto-instrumentations-node"
53
+ };
54
+ const CORE_PACKAGES = [
55
+ PKG.api,
56
+ PKG.sdk,
57
+ PKG.resources,
58
+ PKG.semconv
59
+ ];
60
+ const SINGLE_INSTRUMENTATIONS = [{
61
+ pkg: "@opentelemetry/instrumentation-http",
62
+ exportName: "HttpInstrumentation"
63
+ }, {
64
+ pkg: "@opentelemetry/instrumentation-mongodb",
65
+ exportName: "MongoDBInstrumentation"
66
+ }];
67
+ /** Load each OpenTelemetry package on its own, so one absence never hides the rest. */
68
+ function loadOtel() {
69
+ const missing = [];
70
+ const load = (pkg, has) => {
71
+ try {
72
+ const mod = require(pkg);
73
+ if (has(mod)) return mod;
74
+ } catch {}
75
+ missing.push(pkg);
76
+ };
77
+ const bindings = {
78
+ api: load(PKG.api, (m) => typeof m.trace === "object"),
79
+ sdk: load(PKG.sdk, (m) => typeof m.TracerProvider === "function"),
80
+ resources: load(PKG.resources, (m) => typeof m.resourceFromAttributes === "function"),
81
+ semconv: load(PKG.semconv, (m) => typeof m.ATTR_HTTP_REQUEST_METHOD === "string"),
82
+ exporter: load(PKG.exporter, (m) => typeof m.OTLPTraceExporter === "function"),
83
+ contextManager: load(PKG.contextManager, (m) => typeof m.AsyncLocalStorageContextManager === "function"),
84
+ core: load(PKG.core, (m) => typeof m.W3CTraceContextPropagator === "function"),
85
+ instrumentations: [],
86
+ missing
87
+ };
88
+ const auto = load(PKG.auto, (m) => typeof m.getNodeAutoInstrumentations === "function");
89
+ if (auto) bindings.getNodeAutoInstrumentations = auto.getNodeAutoInstrumentations;
90
+ else for (const { pkg, exportName } of SINGLE_INSTRUMENTATIONS) {
91
+ const ctor = load(pkg, (m) => typeof m[exportName] === "function")?.[exportName];
92
+ if (ctor) bindings.instrumentations.push({
93
+ pkg,
94
+ ctor
95
+ });
96
+ }
97
+ return bindings;
98
+ }
99
+ const otel = loadOtel();
100
+ const isAvailable = Boolean(otel.api && otel.sdk && otel.resources && otel.semconv);
101
+ const trace = otel.api?.trace;
102
+ const context = otel.api?.context;
103
+ const SpanStatusCode = otel.api?.SpanStatusCode;
104
+ const semconv = otel.semconv;
56
105
  /**
57
- * Create a tracer provider
106
+ * Build the SDK `TracerProvider` and register it globally, together with an async
107
+ * context manager and W3C propagators when those packages are present. Anything the
108
+ * host registered first stays; arc's copy is then shut down unused. Returns the
109
+ * provider arc owns (to flush on close), or `undefined` when the host's is in use.
58
110
  */
59
- function createTracerProvider(options) {
60
- if (!isAvailable || !NodeTracerProvider || !BatchSpanProcessor || !OTLPTraceExporter) return null;
111
+ function setupGlobals(api, options, log) {
112
+ const { sdk, resources, semconv: sc } = otel;
113
+ if (!sdk || !resources || !sc) return void 0;
61
114
  const { serviceName = "@classytic/arc", serviceVersion, exporterUrl = "http://localhost:4318/v1/traces" } = options;
62
- const resolvedVersion = serviceVersion ?? "2.52.0";
63
- const exporter = new OTLPTraceExporter({ url: exporterUrl });
64
- const provider = new NodeTracerProvider({ resource: { attributes: {
65
- "service.name": serviceName,
66
- "service.version": resolvedVersion
67
- } } });
68
- provider.addSpanProcessor(new BatchSpanProcessor(exporter));
69
- provider.register();
115
+ const resolvedVersion = serviceVersion ?? "2.53.0";
116
+ const spanProcessors = [];
117
+ if (otel.exporter) spanProcessors.push(new sdk.BatchSpanProcessor({ exporter: new otel.exporter.OTLPTraceExporter({ url: exporterUrl }) }));
118
+ else log.warn(`[arc] tracing: ${PKG.exporter} not installed — spans are created but not exported. Install it to send spans to ${exporterUrl}.`);
119
+ const provider = new sdk.TracerProvider({
120
+ resource: resources.resourceFromAttributes({
121
+ [sc.ATTR_SERVICE_NAME]: serviceName,
122
+ [sc.ATTR_SERVICE_VERSION]: resolvedVersion
123
+ }),
124
+ spanProcessors
125
+ });
126
+ if (otel.contextManager) {
127
+ const manager = new otel.contextManager.AsyncLocalStorageContextManager();
128
+ if (!api.context.setGlobalContextManager(manager.enable())) manager.disable();
129
+ } else log.warn(`[arc] tracing: ${PKG.contextManager} not installed — the request span is not active across await, so instrumented calls start their own traces.`);
130
+ if (otel.core) {
131
+ const { CompositePropagator, W3CTraceContextPropagator, W3CBaggagePropagator } = otel.core;
132
+ api.propagation.setGlobalPropagator(new CompositePropagator({ propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()] }));
133
+ } else log.warn(`[arc] tracing: ${PKG.core} not installed — incoming traceparent headers are not joined.`);
134
+ if (!api.trace.setGlobalTracerProvider(provider)) {
135
+ log.info("[arc] tracing: a global tracer provider is already registered — using it");
136
+ provider.shutdown();
137
+ return;
138
+ }
70
139
  return provider;
71
140
  }
141
+ /** Enable the instrumentations that are installed; name each one that is not. */
142
+ function enableInstrumentations(log) {
143
+ if (otel.getNodeAutoInstrumentations) {
144
+ const instrumentations = otel.getNodeAutoInstrumentations({
145
+ "@opentelemetry/instrumentation-http": { enabled: true },
146
+ "@opentelemetry/instrumentation-mongodb": { enabled: true }
147
+ });
148
+ for (const instrumentation of instrumentations) instrumentation.enable();
149
+ log.debug("OpenTelemetry auto-instrumentation enabled");
150
+ return;
151
+ }
152
+ for (const pkg of otel.missing) if (pkg === PKG.auto || SINGLE_INSTRUMENTATIONS.some((i) => i.pkg === pkg)) log.debug(`[arc] tracing: ${pkg} not installed — skipped; tracing continues without it`);
153
+ for (const { pkg, ctor } of otel.instrumentations) try {
154
+ new ctor().enable();
155
+ log.debug(`[arc] tracing: ${pkg} enabled`);
156
+ } catch (err) {
157
+ log.warn({ err }, `[arc] tracing: ${pkg} failed to start — skipped`);
158
+ }
159
+ }
160
+ /** `{METHOD} {route template}`, or `{METHOD}` when no route matched — never the raw URL. */
161
+ function spanName(request) {
162
+ const route = request.routeOptions?.url;
163
+ return route ? `${request.method} ${route}` : request.method;
164
+ }
165
+ /** Path without the query string — the query can carry tokens, so it is never recorded. */
166
+ function urlPath(url) {
167
+ const q = url.indexOf("?");
168
+ return q === -1 ? url : url.slice(0, q);
169
+ }
72
170
  /**
73
171
  * OpenTelemetry Distributed Tracing Plugin
74
172
  */
75
173
  async function tracingPlugin(fastify, options = {}) {
76
174
  const { serviceName = "@classytic/arc", autoInstrumentation = true, sampleRate = 1 } = options;
77
- if (!isAvailable || !trace || !context || !SpanStatusCode) {
78
- fastify.log.warn("OpenTelemetry not installed. Tracing disabled.");
79
- fastify.log.warn("Install: npm install @opentelemetry/api @opentelemetry/sdk-node");
175
+ const api = otel.api;
176
+ const sc = otel.semconv;
177
+ if (!isAvailable || !api || !sc) {
178
+ const core = otel.missing.filter((p) => CORE_PACKAGES.includes(p));
179
+ fastify.log.warn(`OpenTelemetry not installed (${core.join(", ")}). Tracing disabled.`);
180
+ fastify.log.warn(`Install: npm install ${CORE_PACKAGES.join(" ")}`);
80
181
  return;
81
182
  }
82
- const otelTrace = trace;
83
- const otelContext = context;
84
- const otelStatus = SpanStatusCode;
85
- if (!createTracerProvider(options)) return;
86
- if (autoInstrumentation && getNodeAutoInstrumentations) {
87
- const instrumentations = getNodeAutoInstrumentations({
88
- "@opentelemetry/instrumentation-http": { enabled: true },
89
- "@opentelemetry/instrumentation-mongodb": { enabled: true }
90
- });
91
- for (const instrumentation of instrumentations) instrumentation.enable();
92
- fastify.log.debug("OpenTelemetry auto-instrumentation enabled");
93
- }
94
- const tracer = otelTrace.getTracer(serviceName);
183
+ const provider = setupGlobals(api, options, fastify.log);
184
+ if (provider) fastify.addHook("onClose", async () => provider.shutdown());
185
+ if (autoInstrumentation) enableInstrumentations(fastify.log);
186
+ const tracer = api.trace.getTracer(serviceName);
187
+ const { SpanStatusCode: status, SpanKind } = api;
95
188
  fastify.decorateRequest("tracer", void 0);
96
189
  fastify.addHook("onRequest", (request, _reply, done) => {
97
190
  if (Math.random() > sampleRate) {
98
191
  done();
99
192
  return;
100
193
  }
101
- const span = tracer.startSpan(`HTTP ${request.method} ${request.url}`, {
102
- kind: 1,
194
+ const parent = api.propagation.extract(api.context.active(), request.headers);
195
+ const route = request.routeOptions?.url;
196
+ const span = tracer.startSpan(spanName(request), {
197
+ kind: SpanKind.SERVER,
103
198
  attributes: {
104
- "http.method": request.method,
105
- "http.url": request.url,
106
- "http.target": request.routeOptions?.url ?? request.url,
107
- "http.host": request.hostname,
108
- "http.scheme": request.protocol,
109
- "http.user_agent": request.headers["user-agent"]
199
+ [sc.ATTR_HTTP_REQUEST_METHOD]: request.method,
200
+ ...route ? { [sc.ATTR_HTTP_ROUTE]: route } : {},
201
+ [sc.ATTR_URL_PATH]: urlPath(request.url),
202
+ [sc.ATTR_URL_SCHEME]: request.protocol,
203
+ [sc.ATTR_SERVER_ADDRESS]: request.hostname,
204
+ [sc.ATTR_USER_AGENT_ORIGINAL]: request.headers["user-agent"]
110
205
  }
111
- });
206
+ }, parent);
112
207
  request.tracer = {
113
208
  tracer,
114
209
  currentSpan: span
115
210
  };
116
- otelContext.with(otelTrace.setSpan(otelContext.active(), span), done);
211
+ api.context.with(api.trace.setSpan(parent, span), done);
117
212
  });
118
213
  fastify.addHook("onResponse", async (request, reply) => {
119
214
  if (!request.tracer?.currentSpan) return;
120
215
  const span = request.tracer.currentSpan;
121
216
  span.setAttributes({
122
- "http.status_code": reply.statusCode,
123
- "http.response_content_length": reply.getHeader("content-length")
217
+ [sc.ATTR_HTTP_RESPONSE_STATUS_CODE]: reply.statusCode,
218
+ ...reply.statusCode >= 500 ? { [sc.ATTR_ERROR_TYPE]: String(reply.statusCode) } : {}
124
219
  });
125
- const status = reply.statusCode >= 500 ? {
126
- code: otelStatus.ERROR,
220
+ const spanStatus = reply.statusCode >= 500 ? {
221
+ code: status.ERROR,
127
222
  message: `HTTP ${reply.statusCode}`
128
- } : { code: otelStatus.OK };
129
- span.setStatus(status);
223
+ } : { code: status.OK };
224
+ span.setStatus(spanStatus);
130
225
  span.end();
131
226
  });
132
227
  fastify.addHook("onError", async (request, _reply, error) => {
@@ -134,7 +229,7 @@ async function tracingPlugin(fastify, options = {}) {
134
229
  const span = request.tracer.currentSpan;
135
230
  span.recordException(error);
136
231
  span.setStatus({
137
- code: otelStatus.ERROR,
232
+ code: status.ERROR,
138
233
  message: error.message
139
234
  });
140
235
  });
@@ -196,10 +291,7 @@ function traced(spanName) {
196
291
  const request = args.find((arg) => !!(arg && typeof arg === "object" && "tracer" in arg && arg.tracer));
197
292
  if (!request?.tracer) return originalMethod.apply(this, args);
198
293
  return createSpan(request, spanName ?? `${target.constructor.name}.${propertyKey}`, async (span) => {
199
- if (span) {
200
- span.setAttribute("db.operation", propertyKey);
201
- span.setAttribute("db.system", "mongodb");
202
- }
294
+ if (span && semconv) span.setAttribute(semconv.ATTR_DB_OPERATION_NAME, propertyKey);
203
295
  return originalMethod.apply(this, args);
204
296
  });
205
297
  };
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.52.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.53.0 | MIT | https://classytic.com */
2
2
  // src/utils/pluralize.ts
3
3
  /**
4
4
  * Lightweight English pluralization for the Arc CLI.
@@ -0,0 +1,23 @@
1
+ /*! @classytic/arc v2.53.0 | MIT | https://classytic.com */
2
+ import { R as denyAll } from "./permissions-CEyeDHtT.mjs";
3
+ // src/presets/presetPermission.ts
4
+ /**
5
+ * A preset route's permission: the preset's own option, else the resource permission it
6
+ * maps to. With neither, the route carries an UNRESOLVED marker, never a silent
7
+ * `allowPublic()`: `defineResource` fails boot under `strictPermissions`
8
+ * (`preset-route-public-by-omission`) and otherwise mounts the route public with an info
9
+ * diagnostic, the same ladder as an ungated CRUD read. Outside `defineResource` (a direct
10
+ * `applyPresets` caller) the marker denies.
11
+ */
12
+ const UNRESOLVED = Symbol.for("arc.presetPermissionUnresolved");
13
+ function presetPermission(check, unresolved) {
14
+ if (check) return check;
15
+ const marker = denyAll(`Preset '${unresolved.preset}' route has no permission (permissions.${unresolved.inherits} is not set)`);
16
+ Object.defineProperty(marker, UNRESOLVED, { value: unresolved });
17
+ return marker;
18
+ }
19
+ function unresolvedPresetPermission(check) {
20
+ if (typeof check !== "function") return void 0;
21
+ return Reflect.get(check, UNRESOLVED);
22
+ }
23
+ export { unresolvedPresetPermission as n, presetPermission as t };
@@ -1,7 +1,7 @@
1
1
 
2
2
  import { i as RequestScope } from "../types-DnkIALZ8.mjs";
3
3
  import { l as PermissionCheck } from "../base-HXNgPQww.mjs";
4
- import { W as PresetResult } from "../index-DLCcLUQT.mjs";
4
+ import { G as PresetResult } from "../index-DtHACefu.mjs";
5
5
  import { a as StorageReadResult, i as StorageReadRange, n as StorageContext, o as StorageUploadInput, r as StorageFile, t as Storage } from "../storage-odC5MNKN.mjs";
6
6
  export interface FilesUploadPresetRoutes {
7
7
  upload?: boolean;
@@ -46,7 +46,9 @@ export interface FilesUploadPresetOptions {
46
46
  sanitizeFilename?: FilenamePolicy;
47
47
  /**
48
48
  * Per-route permissions.
49
- * Defaults: upload → `requireAuth()`, read → `allowPublic()`, delete → `requireAuth()`.
49
+ * Defaults: upload → `permissions.create`, else `requireAuth()`; delete → `permissions.delete`,
50
+ * else `requireAuth()`; read → `permissions.get`, else NONE: boot fails under strict
51
+ * permissions (`allowPublic()` here makes downloads public on purpose).
50
52
  */
51
53
  permissions?: FilesUploadPresetPermissions;
52
54
  /** Opt out of individual routes. Default: all three enabled. */
@@ -1,8 +1,9 @@
1
- /*! @classytic/arc v2.52.0 | MIT | https://classytic.com */
2
- import { t as multipartBody } from "../multipartBody-Bxz-q6hI.mjs";
3
- import { B as requireAuth, F as allowPublic } from "../permissions-Cga6KBOX.mjs";
4
- import { c as getOrgId, g as getUserId } from "../types-Cunc4shv.mjs";
5
- import { i as NotFoundError, u as ValidationError } from "../errors-DxpHZBlW.mjs";
1
+ /*! @classytic/arc v2.53.0 | MIT | https://classytic.com */
2
+ import { t as multipartBody } from "../multipartBody-L2gr96df.mjs";
3
+ import { B as requireAuth } from "../permissions-CEyeDHtT.mjs";
4
+ import { c as getOrgId, g as getUserId } from "../types-ZvdR7MVa.mjs";
5
+ import { i as NotFoundError, u as ValidationError } from "../errors-Ukhmfmmx.mjs";
6
+ import { t as presetPermission } from "../presetPermission-2pcRVYRG.mjs";
6
7
  // src/presets/filesUpload.ts
7
8
  const DEFAULT_FIELD_NAME = "file";
8
9
  const DEFAULT_MAX_FILE_SIZE = 10485760;
@@ -231,7 +232,11 @@ function filesUploadPreset(options) {
231
232
  operation: "filesUpload.read",
232
233
  summary: "Download a file",
233
234
  description: "Streams the stored bytes. Supports single-range `Range: bytes=start-end`.",
234
- permissions: options.permissions?.read ?? permissions.get ?? allowPublic(),
235
+ permissions: presetPermission(options.permissions?.read ?? permissions.get, {
236
+ preset: "filesUpload",
237
+ inherits: "get",
238
+ option: "filesUploadPreset({ permissions: { read } })"
239
+ }),
235
240
  rawHandler: makeReadHandler(deps),
236
241
  mcp: false
237
242
  });
@@ -1,8 +1,8 @@
1
1
 
2
2
  import { t as AnyRecord } from "../base-HXNgPQww.mjs";
3
- import { L as ResourceConfig, Un as IControllerResponse, W as PresetResult, Wn as IRequestContext, i as PaginationResult } from "../index-DLCcLUQT.mjs";
3
+ import { G as PresetResult, Gn as IRequestContext, H as PresetController, L as ResourceConfig, Wn as IControllerResponse, i as PaginationResult } from "../index-DtHACefu.mjs";
4
4
  import { FilesUploadPresetOptions, FilesUploadPresetPermissions, FilesUploadPresetRoutes, filesUploadPreset } from "./filesUpload.mjs";
5
- import { n as multiTenantPreset, r as TenantFieldSpec, t as MultiTenantOptions } from "../multiTenant-QtDzxx_K.mjs";
5
+ import { n as multiTenantPreset, r as TenantFieldSpec, t as MultiTenantOptions } from "../multiTenant-Cf0Ye-Wu.mjs";
6
6
  import { SearchHandler, SearchPresetOptions, SearchRouteConfig, searchPreset } from "./search.mjs";
7
7
  interface AuditedPresetOptions {
8
8
  /** Field name for creator (default: 'createdBy') */
@@ -276,7 +276,9 @@ export type PresetInput = string | PresetResult | {
276
276
  };
277
277
  /**
278
278
  * Apply presets to resource config.
279
- * Validates preset combinations for conflicts before merging.
279
+ * Validates preset combinations for conflicts before merging. `controller` is
280
+ * what function-form `routes(permissions, controller)` receives; `defineResource`
281
+ * passes a handle bound to the resolved controller.
280
282
  */
281
- export declare function applyPresets<TDoc = AnyRecord>(config: ResourceConfig<TDoc>, presets?: PresetInput[]): ResourceConfig<TDoc>;
283
+ export declare function applyPresets<TDoc = AnyRecord>(config: ResourceConfig<TDoc>, presets?: PresetInput[], controller?: PresetController): ResourceConfig<TDoc>;
282
284
  export { type AuditedPresetOptions, type BulkOperation, type BulkPresetOptions, type FilesUploadPresetOptions, type FilesUploadPresetPermissions, type FilesUploadPresetRoutes, type IAuditedPreset, type IMultiTenantPreset, type IOwnedByUserPreset, type IPresetController, type ISlugLookupController, type ISoftDeleteController, type ITreeController, type MultiTenantOptions, type OwnedByUserOptions, type SearchHandler, type SearchPresetOptions, type SearchRouteConfig, type SlugLookupOptions, type TenantFieldSpec, type TreeOptions, filesUploadPreset, multiTenantPreset, searchPreset };
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.52.0 | MIT | https://classytic.com */
2
- import { a as treePreset, c as ownedByUserPreset, i as registerPreset, l as bulkPreset, n as getAvailablePresets, o as softDeletePreset, r as getPreset, s as slugLookupPreset, t as applyPresets, u as auditedPreset } from "../presets-D28IABZe.mjs";
1
+ /*! @classytic/arc v2.53.0 | MIT | https://classytic.com */
2
+ import { a as treePreset, c as ownedByUserPreset, i as registerPreset, l as bulkPreset, n as getAvailablePresets, o as softDeletePreset, r as getPreset, s as slugLookupPreset, t as applyPresets, u as auditedPreset } from "../presets-st11ePNn.mjs";
3
3
  import { filesUploadPreset } from "./filesUpload.mjs";
4
4
  import { multiTenantPreset } from "./multiTenant.mjs";
5
5
  import { searchPreset } from "./search.mjs";
@@ -1,3 +1,3 @@
1
1
 
2
- import { n as multiTenantPreset, r as TenantFieldSpec, t as MultiTenantOptions } from "../multiTenant-QtDzxx_K.mjs";
2
+ import { n as multiTenantPreset, r as TenantFieldSpec, t as MultiTenantOptions } from "../multiTenant-Cf0Ye-Wu.mjs";
3
3
  export { MultiTenantOptions, type TenantFieldSpec, multiTenantPreset };
@@ -1,8 +1,8 @@
1
- /*! @classytic/arc v2.52.0 | MIT | https://classytic.com */
2
- import "../constants-Ca2IQFy2.mjs";
3
- import { i as tagTenantPreparation, t as applyTenantPreparation } from "../tenantPreparation-CVBWarqs.mjs";
4
- import { u as getRequestScope } from "../types-Cunc4shv.mjs";
5
- import { t as ArcError } from "../errors-DxpHZBlW.mjs";
1
+ /*! @classytic/arc v2.53.0 | MIT | https://classytic.com */
2
+ import "../constants-D9EiaO5s.mjs";
3
+ import { a as tagTenantPreparation, t as applyTenantPreparation } from "../tenantPreparation-Bk8ouRB3.mjs";
4
+ import { u as getRequestScope } from "../types-ZvdR7MVa.mjs";
5
+ import { t as ArcError } from "../errors-Ukhmfmmx.mjs";
6
6
  // src/presets/multiTenant.ts
7
7
  function createTenantMiddleware(specs, mode) {
8
8
  const preparation = {
@@ -1,6 +1,6 @@
1
1
 
2
2
  import { l as PermissionCheck } from "../base-HXNgPQww.mjs";
3
- import { Ot as RouteDefinition, W as PresetResult, kt as RouteMcpConfig, zn as ControllerHandler } from "../index-DLCcLUQT.mjs";
3
+ import { At as RouteMcpConfig, Bn as ControllerHandler, G as PresetResult, kt as RouteDefinition } from "../index-DtHACefu.mjs";
4
4
  /**
5
5
  * Search Preset — backend-agnostic search / vector / embed routes
6
6
  *
@@ -68,7 +68,7 @@ export interface SearchRouteConfig {
68
68
  path?: string;
69
69
  /** HTTP method. Default: `POST`. */
70
70
  method?: "GET" | "POST";
71
- /** Permission check. Defaults: search/similar fall back to `permissions.list ?? allowPublic()`; embed → `requireAuth()`. */
71
+ /** Permission check. Defaults: search/similar inherit `permissions.list` (unset: boot error under strict permissions); embed → `requireAuth()`. */
72
72
  permissions?: PermissionCheck;
73
73
  /** Fastify/AJV route schema (body/querystring/params/headers/response). */
74
74
  schema?: RouteDefinition["schema"];
@@ -1,22 +1,34 @@
1
- /*! @classytic/arc v2.52.0 | MIT | https://classytic.com */
2
- import { B as requireAuth, F as allowPublic } from "../permissions-Cga6KBOX.mjs";
1
+ /*! @classytic/arc v2.53.0 | MIT | https://classytic.com */
2
+ import { t as conjoinPolicyFilters } from "../filter-merge-BuzZ-r9z.mjs";
3
+ import { B as requireAuth } from "../permissions-CEyeDHtT.mjs";
4
+ import { t as presetPermission } from "../presetPermission-2pcRVYRG.mjs";
3
5
  // src/presets/search.ts
4
6
  const BUILTINS = [
5
7
  {
6
8
  key: "search",
7
9
  defaultPath: "/search",
8
10
  defaultOperation: "search",
11
+ tenantSlot: "list",
9
12
  defaultSummary: "Search",
10
13
  defaultDescription: "Full-text / engine-backed search. Delegates to the configured backend.",
11
- permissionFallback: (p) => p.list ?? allowPublic()
14
+ permissionFallback: (p) => presetPermission(p.list, {
15
+ preset: "search",
16
+ inherits: "list",
17
+ option: "searchPreset({ search: { permissions } })"
18
+ })
12
19
  },
13
20
  {
14
21
  key: "similar",
15
22
  defaultPath: "/search-similar",
16
23
  defaultOperation: "searchSimilar",
24
+ tenantSlot: "list",
17
25
  defaultSummary: "Semantic search",
18
26
  defaultDescription: "Vector / similarity search. Delegates to the configured backend.",
19
- permissionFallback: (p) => p.list ?? allowPublic()
27
+ permissionFallback: (p) => presetPermission(p.list, {
28
+ preset: "search",
29
+ inherits: "list",
30
+ option: "searchPreset({ similar: { permissions } })"
31
+ })
20
32
  },
21
33
  {
22
34
  key: "embed",
@@ -50,47 +62,45 @@ function normaliseSection(value) {
50
62
  if (value === true) return {};
51
63
  return value;
52
64
  }
53
- /**
54
- * Build an auto-synthesised handler that proxies the request body to
55
- * `repo[method]` using each kit's native calling convention. Returns
56
- * `undefined` when the method isn't present so the caller can fall back to
57
- * an explicit `cfg.handler` or skip the route.
58
- *
59
- * Conventions (verified against mongokit 3.6):
60
- *
61
- * - **`search`** (mongokit `elasticSearchPlugin`):
62
- * `search(query, { limit?, from?, mongoOptions? })` — positional. `query`
63
- * is the engine-native DSL (e.g. ES `match` clause). Arc passes
64
- * `(body.query, body)` so the rest of the body flows into options.
65
- *
66
- * - **`searchSimilar`** (mongokit `vectorPlugin`):
67
- * `searchSimilar(params: VectorSearchParams)` — **single object**. `params`
68
- * carries `query` (vector, text, or multimodal), `limit`, `filter`,
69
- * `numCandidates`, `exact`, `field`, `minScore`, etc. Arc passes `body`
70
- * directly so the shapes align. Passing positional args here would
71
- * silently break (first arg becomes the whole `params`, second arg
72
- * is ignored).
73
- *
74
- * - **`embed`** (mongokit `vectorPlugin`):
75
- * `embed(input: string | EmbeddingInput)` — single arg. Arc passes
76
- * `body.input ?? body`, so callers may wrap as `{ input: "…" }` or send
77
- * the `EmbeddingInput` shape directly.
78
- */
79
- function autoHandlerFor(repo, method) {
65
+ function postFilter(result, allows) {
66
+ if (Array.isArray(result)) return result.filter(allows);
67
+ if (result !== null && typeof result === "object" && Array.isArray(result.data)) {
68
+ const page = result;
69
+ const data = page.data.filter(allows);
70
+ const removed = page.data.length - data.length;
71
+ return {
72
+ ...page,
73
+ data,
74
+ ...typeof page.total === "number" ? { total: Math.max(0, page.total - removed) } : {}
75
+ };
76
+ }
77
+ return result;
78
+ }
79
+ function autoHandlerFor(repo, method, scopeOf) {
80
80
  if (!repo) return void 0;
81
81
  const fn = repo[method];
82
82
  if (typeof fn !== "function") return void 0;
83
83
  if (method === "embed") return async (req) => {
84
84
  const body = req.body ?? {};
85
- return fn(body.input ?? body);
85
+ return fn.call(repo, body.input ?? body);
86
86
  };
87
+ const scope = scopeOf();
87
88
  if (method === "searchSimilar") return async (req) => {
88
- const body = req.body ?? {};
89
- return fn(body);
89
+ const { filter: callerFilter, ...body } = req.body ?? {};
90
+ const { filter, options } = await scope(req);
91
+ return fn.call(repo, {
92
+ ...body,
93
+ filter: conjoinPolicyFilters(callerFilter, filter),
94
+ ...options
95
+ });
90
96
  };
91
97
  return async (req) => {
92
98
  const body = req.body ?? {};
93
- return fn(body.query, body);
99
+ const { options, allows } = await scope(req);
100
+ return postFilter(await fn.call(repo, body.query, {
101
+ ...body,
102
+ ...options
103
+ }), allows);
94
104
  };
95
105
  }
96
106
  /**
@@ -120,12 +130,17 @@ function searchPreset(options = {}) {
120
130
  };
121
131
  return {
122
132
  name: "search",
123
- routes: (permissions) => {
133
+ routes: (permissions, controller) => {
124
134
  const mounted = [];
135
+ let listScope;
136
+ const scopeOf = () => {
137
+ listScope ??= controller.listScope;
138
+ return listScope;
139
+ };
125
140
  for (const spec of BUILTINS) {
126
141
  const cfg = sections[spec.key];
127
142
  if (!cfg) continue;
128
- const handler = cfg.handler ?? autoHandlerFor(options.repository, repoMethodFor[spec.key]);
143
+ const handler = cfg.handler ?? autoHandlerFor(options.repository, repoMethodFor[spec.key], scopeOf);
129
144
  if (!handler) continue;
130
145
  const route = {
131
146
  method: cfg.method ?? "POST",
@@ -137,7 +152,8 @@ function searchPreset(options = {}) {
137
152
  permissions: cfg.permissions ?? spec.permissionFallback(permissions),
138
153
  schema: cfg.schema,
139
154
  mcp: cfg.mcp,
140
- handler: wrapEnvelope(handler)
155
+ handler: wrapEnvelope(handler),
156
+ ...spec.tenantSlot ? { _tenantSlot: spec.tenantSlot } : {}
141
157
  };
142
158
  mounted.push(route);
143
159
  }