@classytic/arc 2.45.2 → 2.46.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.
- package/README.md +1 -1
- package/dist/{EventTransport-CiicKz2Z.d.mts → EventTransport-CYEoCJGe.d.mts} +0 -2
- package/dist/{EventTransport-DHb1tpu-.mjs → EventTransport-DNgD9NP4.mjs} +3 -4
- package/dist/{HookSystem-C1u0EUnt.mjs → HookSystem-DRbPzEcP.mjs} +3 -4
- package/dist/{QueryCache--5uAuYPW.d.mts → QueryCache-DdvrGG8Q.d.mts} +1 -3
- package/dist/{ResourceRegistry-D2jXWVN_.mjs → ResourceRegistry-Douk51fa.mjs} +15 -4
- package/dist/{acquire-DTkA8Lme.mjs → acquire-RbtvDg9s.mjs} +2 -3
- package/dist/{actionPermissions-DRVk6m7x.mjs → actionPermissions-De0AJ7hm.mjs} +37 -42
- package/dist/audit/index.d.mts +2 -10
- package/dist/audit/index.mjs +8 -12
- package/dist/auth/audit.d.mts +0 -2
- package/dist/auth/audit.mjs +2 -3
- package/dist/auth/index.d.mts +9 -17
- package/dist/auth/index.mjs +26 -29
- package/dist/auth/redis-session.d.mts +2 -4
- package/dist/auth/redis-session.mjs +2 -3
- package/dist/{authorizationDecision-D48fUJv1.mjs → authorizationDecision-DeZMrHcm.mjs} +5 -6
- package/dist/{base-CZyixEQR.d.mts → base-HXNgPQww.d.mts} +1 -7
- package/dist/{boundedMap-DkKiPifd.mjs → boundedMap-2WBh3gM9.mjs} +2 -3
- package/dist/{buildHandler-BiZ4VATS.mjs → buildHandler-DxVOOBpw.mjs} +5 -6
- package/dist/cache/index.d.mts +4 -10
- package/dist/cache/index.mjs +5 -6
- package/dist/{caching-Cj0as-P1.mjs → caching-BYRwYrUo.mjs} +3 -4
- package/dist/{claimed-ChI13rUR.mjs → claimed-DYlELdnm.mjs} +2 -3
- package/dist/cleanup/index.d.mts +4 -18
- package/dist/cleanup/index.mjs +12 -20
- package/dist/cli/commands/describe.d.mts +1 -3
- package/dist/cli/commands/describe.mjs +4 -5
- package/dist/cli/commands/docs.d.mts +1 -3
- package/dist/cli/commands/docs.mjs +4 -5
- package/dist/cli/commands/doctor.d.mts +1 -3
- package/dist/cli/commands/doctor.mjs +2 -3
- package/dist/cli/commands/generate.d.mts +1 -1
- package/dist/cli/commands/generate.mjs +2 -2
- package/dist/cli/commands/init.d.mts +1 -1
- package/dist/cli/commands/init.mjs +2 -2
- package/dist/cli/commands/introspect.d.mts +1 -3
- package/dist/cli/commands/introspect.mjs +3 -4
- package/dist/cli/index.d.mts +2 -2
- package/dist/cli/index.mjs +3 -3
- package/dist/{constants-D_aiew34.mjs → constants-CHZMUwBW.mjs} +2 -3
- package/dist/context/index.d.mts +0 -8
- package/dist/context/index.mjs +6 -7
- package/dist/core/index.d.mts +3 -3
- package/dist/core/index.mjs +8 -8
- package/dist/{core-QIZ2560Y.mjs → core-D9rS2BxO.mjs} +9 -12
- package/dist/{createActionRouter-CvH84dyx.mjs → createActionRouter-0qkCRzTL.mjs} +7 -8
- package/dist/{createAggregationRouter-DGyK2Hp6.mjs → createAggregationRouter-CUf5Esd9.mjs} +9 -10
- package/dist/{createApp-CKjZpmq9.mjs → createApp-DZIXfDKD.mjs} +49 -62
- package/dist/{createMcpServer-DSztofa9.d.mts → createMcpServer-DeVpqQF-.d.mts} +1 -3
- package/dist/{defineAggregation-BLza7Ca4.mjs → defineAggregation-bmKQ4NmC.mjs} +2 -3
- package/dist/{defineResource-CEo0gDCb.mjs → defineResource-CGmdmGwh.mjs} +78 -29
- package/dist/discovery/index.d.mts +1 -3
- package/dist/discovery/index.mjs +2 -3
- package/dist/docs/index.d.mts +8 -8
- package/dist/docs/index.mjs +4 -5
- package/dist/{elevation-BJTsSnke.mjs → elevation-CzhqAyVN.mjs} +9 -10
- package/dist/{elevation-BW2J3tNj.d.mts → elevation-DPD0hcU-.d.mts} +0 -2
- package/dist/encryption/index.d.mts +1 -7
- package/dist/encryption/index.mjs +8 -13
- package/dist/{errorHandler--4rSMMvq.d.mts → errorHandler-B9r88jZV.d.mts} +8 -3
- package/dist/{errorHandler-2p4SL5zm.mjs → errorHandler-dFyGOEoB.mjs} +16 -6
- package/dist/{errors-grZkIA8N.mjs → errors-BY8vzlP4.mjs} +2 -3
- package/dist/{errors-JYc9vwqE.d.mts → errors-DTo0me1o.d.mts} +0 -2
- package/dist/{eventPlugin-BtmA4-3P.d.mts → eventPlugin-BY38F6yK.d.mts} +1 -7
- package/dist/{eventPlugin-ItcYBGUs.mjs → eventPlugin-eMhAPtQA.mjs} +10 -12
- package/dist/{eventTypes-Ck6fD3ne.mjs → eventTypes-Do2KYeJx.mjs} +5 -8
- package/dist/events/index.d.mts +4 -16
- package/dist/events/index.mjs +8 -9
- package/dist/events/transports/redis-stream-entry.d.mts +1 -1
- package/dist/events/transports/redis-stream-entry.mjs +5 -6
- package/dist/events/transports/redis.d.mts +2 -4
- package/dist/events/transports/redis.mjs +3 -4
- package/dist/{externalPaths-CmGOxOtD.d.mts → externalPaths-BOqdq5wr.d.mts} +0 -2
- package/dist/factory/index.d.mts +4 -14
- package/dist/factory/index.mjs +12 -18
- package/dist/{fastify-augmentation-DRlCIWE9.d.mts → fastify-augmentation-Dtn0IIRn.d.mts} +4 -10
- package/dist/{fields-BBSpf8pS.d.mts → fields-JTkrtO-r.d.mts} +0 -2
- package/dist/{fields-BRX0Krcj.mjs → fields-LnbCcvsw.mjs} +2 -3
- package/dist/{filter-merge-CDc7YMwX.mjs → filter-merge-BAWi019Q.mjs} +2 -3
- package/dist/{generate-DCGuEbqI.d.mts → generate-C-g_KOkV.d.mts} +0 -4
- package/dist/{generate-hvg7V2g1.mjs → generate-oXoDnpJf.mjs} +7 -12
- package/dist/{headers-Cqkg4LzI.mjs → headers-DBd3Qheo.mjs} +3 -4
- package/dist/{health-PVt0VjOx.mjs → health-BlJu9GXS.mjs} +2 -3
- package/dist/{health-DyeP3mTW.mjs → health-Dp-3EC9o.mjs} +4 -7
- package/dist/hooks/index.d.mts +1 -1
- package/dist/hooks/index.mjs +2 -2
- package/dist/idempotency/index.d.mts +3 -9
- package/dist/idempotency/index.mjs +10 -13
- package/dist/idempotency/redis.d.mts +1 -1
- package/dist/idempotency/redis.mjs +3 -4
- package/dist/{index-Bxriq3so.d.mts → index-B5i9-vuP.d.mts} +4 -26
- package/dist/{index-Chgz3d0i.d.mts → index-BAXDo5eE.d.mts} +1 -7
- package/dist/{index-Beg3aNnK.d.mts → index-BTxzJ_MN.d.mts} +67 -25
- package/dist/{index-CUJvoyw3.d.mts → index-Bqfo8hLz.d.mts} +2 -24
- package/dist/{index-uhkUA5-U.d.mts → index-CUdaoCYt.d.mts} +13 -23
- package/dist/{index-WH7xgvxS.d.mts → index-DyJFTJLA.d.mts} +31 -92
- package/dist/index.d.mts +7 -9
- package/dist/index.mjs +12 -13
- package/dist/{init-jC3rMPzb.mjs → init-BOaNkLYb.mjs} +18 -35
- package/dist/{init-Cscs4lab.d.mts → init-CV2_Fw3H.d.mts} +0 -4
- package/dist/integrations/event-gateway.d.mts +3 -5
- package/dist/integrations/event-gateway.mjs +3 -4
- package/dist/integrations/index.d.mts +3 -3
- package/dist/integrations/index.mjs +1 -1
- package/dist/integrations/jobs/index.d.mts +1 -1
- package/dist/integrations/jobs/index.mjs +7 -11
- package/dist/integrations/mcp/index.d.mts +7 -39
- package/dist/integrations/mcp/index.mjs +8 -14
- package/dist/integrations/mcp/testing.d.mts +3 -5
- package/dist/integrations/mcp/testing.mjs +3 -4
- package/dist/integrations/streamline.d.mts +1 -3
- package/dist/integrations/streamline.mjs +4 -5
- package/dist/integrations/webhooks.d.mts +2 -4
- package/dist/integrations/webhooks.mjs +4 -5
- package/dist/integrations/websocket-pushref-redis.d.mts +2 -4
- package/dist/integrations/websocket-pushref-redis.mjs +2 -3
- package/dist/integrations/websocket-redis.d.mts +2 -4
- package/dist/integrations/websocket-redis.mjs +2 -3
- package/dist/integrations/websocket.d.mts +2 -2
- package/dist/integrations/websocket.mjs +13 -24
- package/dist/{interface-JJzwH4Ro.d.mts → interface-BmExzQRD.d.mts} +0 -2
- package/dist/{interface-BOk3YnTz.d.mts → interface-WR1U0K7t.d.mts} +0 -2
- package/dist/{jsonBody-ptwyzZQ-.mjs → jsonBody-DpRpKR_K.mjs} +3 -4
- package/dist/{keys-C1vFuSbv.mjs → keys-FBz6Ull-.mjs} +2 -3
- package/dist/{loadResources-CHPDyIPn.mjs → loadResources-Bx1sKPnF.mjs} +4 -5
- package/dist/{loadResourcesFromEntry-BkHHTu_B.mjs → loadResourcesFromEntry-b_jcqbxh.mjs} +3 -4
- package/dist/logger/index.d.mts +1 -3
- package/dist/logger/index.mjs +2 -2
- package/dist/{logger-C5bvCiAK.mjs → logger-CbFcIEBZ.mjs} +3 -5
- package/dist/{mcpPlugin-C9qohJCF.mjs → mcpPlugin-yix548XX.mjs} +41 -60
- package/dist/{memory-CxiTwT0j.mjs → memory-Bgw5dn8N.mjs} +4 -5
- package/dist/{metrics-Ckp2zRy-.mjs → metrics-CZDQWVjS.mjs} +4 -5
- package/dist/middleware/index.d.mts +1 -5
- package/dist/middleware/index.mjs +4 -5
- package/dist/migrations/index.d.mts +0 -2
- package/dist/migrations/index.mjs +3 -4
- package/dist/{module-CfnKuIuH.mjs → module-Dsc_nKL5.mjs} +2 -3
- package/dist/{multiTenant-CAtYlW6H.d.mts → multiTenant-XCxAUlru.d.mts} +1 -5
- package/dist/{multipartBody-BFasGtP9.mjs → multipartBody-B85ek8Kj.mjs} +2 -3
- package/dist/observeSend-BK-JN1jK.mjs +20 -0
- package/dist/{openapi-DAPxjYHX.mjs → openapi-Co7hl073.mjs} +18 -28
- package/dist/outbox-admin/index.d.mts +2 -4
- package/dist/outbox-admin/index.mjs +6 -7
- package/dist/{outbox-module-gZCHoE4H.d.mts → outbox-module-XvUThpqn.d.mts} +2 -8
- package/dist/{outbox-module-B4FAkx3A.mjs → outbox-module-mg9kDYkd.mjs} +13 -17
- package/dist/permissions/index.d.mts +4 -4
- package/dist/permissions/index.mjs +7 -7
- package/dist/{permissions-B14c3OMp.mjs → permissions-A1oKtpiC.mjs} +19 -29
- package/dist/{pipe-CQv7PsAK.mjs → pipe-Czpw9U2n.mjs} +3 -4
- package/dist/pipeline/index.d.mts +1 -9
- package/dist/pipeline/index.mjs +5 -8
- package/dist/{plan-CpnTykjb.mjs → plan-KVseuBCL.mjs} +5 -9
- package/dist/{plugin-DXTjVg_Q.mjs → plugin-DTWt_8C3.mjs} +130 -62
- package/dist/plugins/index.d.mts +8 -16
- package/dist/plugins/index.mjs +22 -26
- package/dist/plugins/response-cache.d.mts +2 -4
- package/dist/plugins/response-cache.mjs +10 -10
- package/dist/plugins/tracing-entry.d.mts +1 -1
- package/dist/plugins/tracing-entry.mjs +3 -4
- package/dist/{pluralize-C3VJKRGp.mjs → pluralize-msB9X3yw.mjs} +2 -3
- package/dist/presets/filesUpload.d.mts +4 -6
- package/dist/presets/filesUpload.mjs +6 -7
- package/dist/presets/index.d.mts +3 -19
- package/dist/presets/index.mjs +2 -2
- package/dist/presets/multiTenant.d.mts +1 -1
- package/dist/presets/multiTenant.mjs +7 -7
- package/dist/presets/search.d.mts +3 -5
- package/dist/presets/search.mjs +3 -4
- package/dist/{presets-CquqYJPy.mjs → presets-qKCehiJM.mjs} +11 -18
- package/dist/{projection-CgfSLOSM.mjs → projection-ClBqtsIw.mjs} +3 -4
- package/dist/{pushref-registry-UxCkoA4C.d.mts → pushref-registry-d86QUaSq.d.mts} +0 -6
- package/dist/{queryCachePlugin-D0HUISHJ.mjs → queryCachePlugin-3gJj5Rbz.mjs} +8 -10
- package/dist/{queryCachePlugin-C2lZjTxk.d.mts → queryCachePlugin-DYQUyeJ9.d.mts} +2 -4
- package/dist/{rateLimitKey-AvkBOMkl.mjs → rateLimitKey-Kro---xl.mjs} +2 -3
- package/dist/{realtime-CbWtVbqK.mjs → realtime-Ber8uJN2.mjs} +17 -19
- package/dist/{redis-BDgv9Glw.d.mts → redis-RpDMemdm.d.mts} +2 -4
- package/dist/{redis-stream-BMk-bpQS.d.mts → redis-stream-CS1N9dwM.d.mts} +1 -3
- package/dist/{redisShapes-CQksY67q.d.mts → redisShapes-CqBXTn_s.d.mts} +0 -2
- package/dist/registry/index.d.mts +2 -12
- package/dist/registry/index.mjs +3 -3
- package/dist/{registry-BVwpAuFI.mjs → registry-BA-_vFYk.mjs} +7 -12
- package/dist/{renewingLease-CykpeNcQ.mjs → renewingLease-CMY8YOcc.mjs} +2 -3
- package/dist/{replyHelpers-DA51IZio.mjs → replyHelpers-DK9P_XSz.mjs} +3 -4
- package/dist/{requestContext-DIWHKDtQ.mjs → requestContext-GYO_0gEw.mjs} +2 -3
- package/dist/{requirement-CbiLdQ1n.d.mts → requirement-CTRQjjQx.d.mts} +0 -2
- package/dist/{requirement-Cp_fsMDL.mjs → requirement-DeNjZIH3.mjs} +2 -3
- package/dist/{resourceRateLimit-Wf6d6FL9.d.mts → resourceRateLimit-DCWglD7V.d.mts} +1 -3
- package/dist/{resourceRateLimit-BFuluodF.mjs → resourceRateLimit-tHLbrtWc.mjs} +3 -4
- package/dist/{rolldown-runtime-D_lMdYOd.mjs → rolldown-runtime-Kv1fZdLg.mjs} +2 -3
- package/dist/{routeValidator-DuLonYwr.mjs → routeValidator-C_H5NanI.mjs} +2 -3
- package/dist/{runtimeCapabilities-CydRfm0i.mjs → runtimeCapabilities-DWqbxkyw.mjs} +2 -3
- package/dist/{schedules-B693KXxa.mjs → schedules-eO_RzhCU.mjs} +132 -9
- package/dist/{schemaConverter-DNvZWTV6.mjs → schemaConverter-DBJrPZN4.mjs} +3 -4
- package/dist/{schemaIR-REV2y7Wd.mjs → schemaIR-CEScKT2v.mjs} +3 -4
- package/dist/schemas/index.d.mts +0 -2
- package/dist/schemas/index.mjs +2 -3
- package/dist/scim/index.d.mts +0 -12
- package/dist/scim/index.mjs +10 -18
- package/dist/scope/index.d.mts +2 -6
- package/dist/scope/index.mjs +5 -5
- package/dist/{scope-Bevxy_ST.mjs → scope-B-Sm9m_E.mjs} +5 -6
- package/dist/{sessionManager-qimlKV0P.d.mts → sessionManager-CdvDF04x.d.mts} +2 -4
- package/dist/{shutdown-CfrqPR7A.mjs → shutdown-DzLFbe27.mjs} +2 -3
- package/dist/{simpleEqualityMatcher-BJwfuRKP.mjs → simpleEqualityMatcher-DOJhwQ8g.mjs} +2 -3
- package/dist/{sse-CuNNWr2z.mjs → sse-2972pVwV.mjs} +8 -9
- package/dist/{sseStream-C_2ujAVY.mjs → sseStream-AWLEeNV-.mjs} +3 -4
- package/dist/{storage-Cx9Sz3Ou.d.mts → storage-odC5MNKN.d.mts} +0 -2
- package/dist/{store-helpers-C8uBGCbb.mjs → store-helpers-VzjgVTkM.mjs} +2 -3
- package/dist/{streaming-Bdq_M4d5.mjs → streaming-DvraWW6x.mjs} +2 -3
- package/dist/{subscriberIdentity-B-KpZkdl.mjs → subscriberIdentity-Bya56jsg.mjs} +2 -3
- package/dist/{tenancy-C5PCvm1h.mjs → tenancy-DSa_0hhw.mjs} +3 -4
- package/dist/{tenantPreparation-dYvWrgNa.mjs → tenantPreparation-BrpkQre3.mjs} +5 -6
- package/dist/testing/cleanupStoreContract.d.mts +2 -4
- package/dist/testing/cleanupStoreContract.mjs +2 -3
- package/dist/testing/index.d.mts +6 -32
- package/dist/testing/index.mjs +24 -37
- package/dist/testing/outboxStoreContract.d.mts +1 -3
- package/dist/testing/outboxStoreContract.mjs +3 -4
- package/dist/testing/requiredPorts.d.mts +2 -4
- package/dist/testing/requiredPorts.mjs +3 -4
- package/dist/testing/storageContract.d.mts +2 -4
- package/dist/testing/storageContract.mjs +2 -3
- package/dist/{timing-DCqsezX8.mjs → timing-6rQTuCwg.mjs} +3 -5
- package/dist/{tracing-Dro5eH6j.d.mts → tracing-JSFiBl5r.d.mts} +0 -2
- package/dist/{transactionContext-DrcNyjpv.mjs → transactionContext-DaxYUEgH.mjs} +2 -3
- package/dist/{typeGuards-CEl10KPy.mjs → typeGuards-UKnX8wPX.mjs} +2 -3
- package/dist/types/index.d.mts +4 -4
- package/dist/types/index.mjs +1 -1
- package/dist/types/storage.d.mts +1 -1
- package/dist/types/storage.mjs +1 -1
- package/dist/{types-ByHn9rEO.d.mts → types-0Dqlbgn8.d.mts} +0 -2
- package/dist/{types-D3Ixsh00.d.mts → types-BYEb_dLW.d.mts} +2 -4
- package/dist/{types-BJ-2XqVF.d.mts → types-BeEJm-DV.d.mts} +114 -14
- package/dist/{types-DVLddu2q.d.mts → types-C0YJAiL0.d.mts} +0 -2
- package/dist/{types-D9NWjpYc.mjs → types-CuGjhn83.mjs} +5 -6
- package/dist/{types-Ddl9OjmE.d.mts → types-DnkIALZ8.d.mts} +0 -4
- package/dist/usage/index.d.mts +2 -10
- package/dist/usage/index.mjs +8 -12
- package/dist/{userHelpers-BHig1kHq.mjs → userHelpers-oX5_mOVs.mjs} +2 -3
- package/dist/utils/index.d.mts +5 -39
- package/dist/utils/index.mjs +12 -12
- package/dist/{utils-BG5P7_Vb.mjs → utils-CjjGOT4E.mjs} +20 -30
- package/dist/{validate-D_mdOCir.mjs → validate-4RlTKOJb.mjs} +5 -7
- package/dist/{versioning-DBGHjPh7.mjs → versioning-Dk2-19La.mjs} +4 -5
- package/dist/{versioning-Bqm_57Qt.d.mts → versioning-S18y2-0C.d.mts} +1 -15
- package/dist/{websocket-Cs4awVyD.d.mts → websocket-BGuc-WVZ.d.mts} +1 -15
- package/dist/{workScope-DPPfM4m6.mjs → workScope-DoBsoVo4.mjs} +3 -4
- package/llms.txt +37 -30
- package/package.json +9 -8
- package/skills/arc/SKILL.md +65 -844
- package/skills/arc/references/agent-auth.md +82 -193
- package/skills/arc/references/api-reference.md +41 -245
- package/skills/arc/references/auth-api-keys.md +99 -0
- package/skills/arc/references/auth-better-auth-overlay.md +87 -0
- package/skills/arc/references/auth-better-auth.md +78 -0
- package/skills/arc/references/auth-permissions.md +100 -0
- package/skills/arc/references/auth-strategies.md +122 -0
- package/skills/arc/references/boot.md +80 -0
- package/skills/arc/references/enterprise-auth.md +65 -81
- package/skills/arc/references/events-outbox.md +90 -0
- package/skills/arc/references/events.md +75 -440
- package/skills/arc/references/integrations-jobs.md +74 -0
- package/skills/arc/references/integrations-realtime.md +84 -0
- package/skills/arc/references/integrations-webhooks.md +71 -0
- package/skills/arc/references/integrations-workflows.md +47 -0
- package/skills/arc/references/mcp-auth.md +83 -0
- package/skills/arc/references/mcp-custom-tools.md +125 -0
- package/skills/arc/references/mcp-setup.md +115 -0
- package/skills/arc/references/mcp-testing.md +63 -0
- package/skills/arc/references/multi-tenancy.md +56 -230
- package/skills/arc/references/permissions-scope.md +81 -0
- package/skills/arc/references/production-api.md +119 -0
- package/skills/arc/references/production-audit.md +101 -0
- package/skills/arc/references/production-boot.md +91 -0
- package/skills/arc/references/production-caching.md +63 -0
- package/skills/arc/references/production-distributed.md +75 -0
- package/skills/arc/references/production-idempotency.md +83 -0
- package/skills/arc/references/production-observability.md +83 -0
- package/skills/arc/references/production-realtime.md +70 -0
- package/skills/arc/references/production-reliability.md +100 -0
- package/skills/arc/references/production-shutdown.md +43 -0
- package/skills/arc/references/querying.md +76 -0
- package/skills/arc/references/resources.md +97 -0
- package/skills/arc/references/schedules.md +79 -0
- package/skills/arc/references/scim.md +61 -208
- package/skills/arc/references/tenancy-scope-install.md +82 -0
- package/skills/arc/references/testing.md +101 -144
- package/skills/arc/references/usage-cleanup-capabilities.md +45 -0
- package/skills/arc/references/validation.md +91 -0
- package/skills/arc/references/writes-hooks-errors.md +80 -0
- package/skills/arc-code-review/SKILL.md +67 -114
- package/skills/arc-code-review/references/arc-cheatsheet.md +68 -167
- package/skills/arc-code-review/references/mongokit-repositories.md +104 -0
- package/skills/arc-code-review/references/recipe-events-cache-jobs.md +112 -0
- package/skills/arc-code-review/references/recipe-resource.md +100 -0
- package/skills/arc-code-review/references/recipe-schemas-fields.md +93 -0
- package/skills/arc-code-review/references/recipe-scope-permissions.md +82 -0
- package/skills/arc-code-review/references/scaffolding.md +61 -198
- package/skills/arc-code-review/references/severity.md +49 -102
- package/skills/arc-code-review/references/smells-auth-scope.md +80 -0
- package/skills/arc-code-review/references/smells-data-events.md +66 -0
- package/skills/arc-code-review/references/smells-imports-style.md +59 -0
- package/skills/arc-code-review/references/smells-platform.md +89 -0
- package/skills/arc-code-review/references/smells-routes-schemas.md +66 -0
- package/skills/arc-module-publishing/SKILL.md +82 -208
- package/skills/arc-module-publishing/references/action-presets-and-plugins.md +87 -0
- package/skills/arc-module-publishing/references/build-and-types.md +73 -0
- package/skills/arc-module-publishing/references/module-lifecycle.md +101 -0
- package/skills/arc-module-publishing/references/package-manifest.md +34 -122
- package/skills/arc-module-publishing/references/publishing-workflow.md +44 -140
- package/skills/arc-module-publishing/references/resource-assembly.md +102 -0
- package/skills/arc-module-publishing/references/testing-packages.md +82 -0
- package/skills/arc/references/auth.md +0 -729
- package/skills/arc/references/integrations.md +0 -452
- package/skills/arc/references/mcp.md +0 -691
- package/skills/arc/references/production.md +0 -835
- package/skills/arc-code-review/references/anti-patterns.md +0 -1008
- package/skills/arc-code-review/references/migration-recipes.md +0 -649
- package/skills/arc-code-review/references/mongokit-migration.md +0 -360
- package/skills/arc-module-publishing/references/authoring-modules.md +0 -327
package/skills/arc/SKILL.md
CHANGED
|
@@ -1,878 +1,99 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: arc
|
|
3
|
-
description:
|
|
4
|
-
@classytic/arc — Resource-oriented backend framework for Fastify.
|
|
5
|
-
Use when building REST APIs with Fastify, resource CRUD, defineResource, createApp,
|
|
6
|
-
permissions, presets, database adapters, hooks, events, QueryCache, authentication,
|
|
7
|
-
multi-tenant SaaS, OpenAPI, job queues, WebSocket, MCP tools, or production deployment.
|
|
8
|
-
Triggers: arc, fastify resource, defineResource, createApp, BaseController, arc preset,
|
|
9
|
-
arc auth, arc events, arc jobs, arc websocket, arc mcp, arc plugin, arc testing, arc cli,
|
|
10
|
-
arc permissions, arc hooks, arc factory, arc cache.
|
|
3
|
+
description: "@classytic/arc: resource-oriented Fastify backend framework. Use for defineResource CRUD, createApp, permissions, presets, route/action validation (zod v4), scheduled and daily jobs, events/outbox, auth (JWT, Better Auth), multi-tenancy, OpenAPI, MCP tools, testing. Triggers: arc, defineResource, createApp, routeInput, scheduledJobs, arc preset, arc permissions."
|
|
11
4
|
license: MIT
|
|
12
5
|
metadata:
|
|
13
6
|
author: Classytic
|
|
14
|
-
|
|
15
|
-
- fastify
|
|
16
|
-
- rest-api
|
|
17
|
-
- resource-framework
|
|
18
|
-
- crud
|
|
19
|
-
- permissions
|
|
20
|
-
- multi-tenant
|
|
21
|
-
- presets
|
|
22
|
-
- typescript
|
|
23
|
-
- cache
|
|
24
|
-
- events
|
|
25
|
-
- openapi
|
|
7
|
+
minVersion: "2.46.0"
|
|
26
8
|
---
|
|
27
9
|
|
|
28
10
|
# @classytic/arc
|
|
29
11
|
|
|
30
|
-
|
|
12
|
+
One `defineResource()` = REST + validation + permissions + events + cache + OpenAPI + MCP. Fastify >=5.12, Node >=22, ESM. DB through kits (`@classytic/mongokit`, `sqlitekit`, `prismakit`) over `@classytic/repo-core`.
|
|
31
13
|
|
|
32
|
-
|
|
14
|
+
## Do not hand-roll
|
|
33
15
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
16
|
+
| Need | Use |
|
|
17
|
+
|---|---|
|
|
18
|
+
| CRUD, OpenAPI, MCP tools | `defineResource({ name, adapter, permissions })` |
|
|
19
|
+
| Role, ownership, row policy | `@classytic/arc/permissions`: `requireRoles`, `requireOwnership`, `allowPublic({ policy })`, `anyOf` |
|
|
20
|
+
| Tenant or user id in a handler | `@classytic/arc/scope`: `requireOrgId`, `getUserId` (never read scope fields) |
|
|
21
|
+
| Route body/query/params schema | `routeInput({ body })` from `@classytic/arc/core` |
|
|
22
|
+
| CRUD write schema | `crudInput({ create, update })` |
|
|
23
|
+
| Action body schema | `actions.x.schema` is the schema itself; `defineAction({ schema, parse: true })`; `noPayloadSchema` |
|
|
24
|
+
| Filter, sort, page | resource `queryParser` allow-list, keyset `after` |
|
|
25
|
+
| Soft delete, slug, tree, bulk, files | `presets: [...]` |
|
|
26
|
+
| Recurring job | module `scheduledJobs` + `lock` or `singleReplica` |
|
|
27
|
+
| Once per local day | `scheduledJobs` with `daily: { hour, minute, zone, ledger }` |
|
|
28
|
+
| Durable queue | `@classytic/arc/integrations/jobs` |
|
|
29
|
+
| Headless worker | `createWorker(sameOptions)` from `@classytic/arc/factory` |
|
|
30
|
+
| Counters, quotas | `@classytic/arc/usage`: `usagePlugin`, `requireQuota`; `rateLimit.plan` |
|
|
31
|
+
| Events, outbox, webhooks | `@classytic/arc/events`: `createOutboxModule` |
|
|
32
|
+
| 404 for unknown routes | built in: `arc.not_found` ErrorContract |
|
|
33
|
+
| Tests | `createTestApp`, `expectArc` from `@classytic/arc/testing` |
|
|
34
|
+
|
|
35
|
+
## Golden path
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
import { defineResource } from '@classytic/arc';
|
|
51
39
|
import { createApp, loadResources } from '@classytic/arc/factory';
|
|
52
|
-
|
|
53
|
-
const app = await createApp({
|
|
54
|
-
preset: 'production', // production | development | testing | edge
|
|
55
|
-
runtime: 'memory', // memory | distributed
|
|
56
|
-
resourcePrefix: '/api/v1',
|
|
57
|
-
auth: { type: 'jwt', jwt: { secret: process.env.JWT_SECRET } },
|
|
58
|
-
cors: { origin: process.env.ALLOWED_ORIGINS!.split(','), credentials: true },
|
|
59
|
-
resources: await loadResources(import.meta.url), // auto-discovers *.resource.ts
|
|
60
|
-
arcPlugins: { events: true, queryCache: false, sse: false, caching: true },
|
|
61
|
-
stores: { // required when runtime: 'distributed'
|
|
62
|
-
events: new RedisEventTransport({ client: redis }),
|
|
63
|
-
queryCache: new RedisCacheStore({ client: redis }),
|
|
64
|
-
},
|
|
65
|
-
});
|
|
66
|
-
|
|
67
|
-
await app.listen({ port: 8040, host: '0.0.0.0' });
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
**Boot order (fixed):** `beforeBoot` → modules resolve → `plugins` → `bootstrap[]` → `resources` → `afterResources` → `onReady`.
|
|
71
|
-
|
|
72
|
-
**`role` — one image, N deployments (2.33).** `createApp({ role })` declares what a process is FOR, so the same codebase ships as api / worker / relay / scheduler without per-deployment builds:
|
|
73
|
-
|
|
74
|
-
```typescript
|
|
75
|
-
createApp({ role: process.env.ARC_ROLE as 'api' | 'worker' | 'relay' | 'scheduler' | 'all' })
|
|
76
|
-
```
|
|
77
|
-
|
|
78
|
-
`api` and `worker` mount NO module schedule arms; `relay` mounts only `kind: 'relay'` arms (the outbox relay, durable webhook delivery); `scheduler` mounts all of them. Declaring `relay`/`scheduler` together with `resources`/`resourceDir` is BOOT-FATAL — a relay process must not serve routes. Default `all` is the pre-2.33 behaviour, unchanged. `createWorker()` forwards `role`; without one it still runs everything non-HTTP.
|
|
79
|
-
|
|
80
|
-
`beforeBoot()` (2.21) runs before Fastify exists and before module thunks / resource files import — connect the DB there instead of dynamic-import ordering hacks. Return a disposer (`() => mongoose.disconnect()`) and arc runs it on close and on a failed boot. A bridge declared as `{ kind: 'bridge', name, dependsOn, load }` is never imported when inactive.
|
|
81
|
-
|
|
82
|
-
For async-booted engines, pass `resources` as a factory so it runs after `bootstrap[]`:
|
|
83
|
-
|
|
84
|
-
```typescript
|
|
85
|
-
resources: async (fastify) => {
|
|
86
|
-
const engine = await ensureCatalogEngine();
|
|
87
|
-
return [buildProductResource(engine)];
|
|
88
|
-
}
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
`loadResources(import.meta.url)` resolves `src/` in dev and `dist/` in prod. Use `loadResources(import.meta.url, { context: { engine } })` to thread engine handles into `(ctx) => defineResource(...)` default exports. `{ filter: (absPath) => boolean }` (2.21) gates files BEFORE they're imported — feature-flag manifests become one callback.
|
|
92
|
-
|
|
93
|
-
## defineResource()
|
|
94
|
-
|
|
95
|
-
```typescript
|
|
96
|
-
import { defineResource, allowPublic, requireRoles, requireAuth } from '@classytic/arc';
|
|
40
|
+
import { allowPublic, requireRoles } from '@classytic/arc/permissions';
|
|
97
41
|
import { createMongooseAdapter } from '@classytic/mongokit/adapter';
|
|
98
42
|
|
|
99
43
|
export default defineResource({
|
|
100
44
|
name: 'product',
|
|
101
|
-
// mongokit >=3.21 defaults schemaGenerator to buildCrudSchemasFromModel;
|
|
102
|
-
// pass `schemaGenerator: false` to opt out.
|
|
103
45
|
adapter: createMongooseAdapter({ model: ProductModel, repository: productRepo }),
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
list: allowPublic(),
|
|
109
|
-
get: allowPublic(),
|
|
110
|
-
create: requireRoles(['admin']),
|
|
111
|
-
update: requireRoles(['admin']),
|
|
112
|
-
delete: requireRoles(['admin']),
|
|
113
|
-
},
|
|
114
|
-
|
|
115
|
-
schemaOptions: {
|
|
116
|
-
fieldRules: {
|
|
117
|
-
name: { minLength: 2, maxLength: 200 },
|
|
118
|
-
sku: { pattern: '^[A-Z]{3}-\\d{3}$' },
|
|
119
|
-
status: { enum: ['draft', 'active', 'archived'] },
|
|
120
|
-
deletedAt: { systemManaged: true }, // framework stamps; strip from body
|
|
121
|
-
priceMode: { nullable: true }, // accept null
|
|
122
|
-
organizationId: { systemManaged: true, preserveForElevated: true },
|
|
123
|
-
},
|
|
124
|
-
query: {
|
|
125
|
-
allowedPopulate: ['category', 'createdBy'],
|
|
126
|
-
filterableFields: { status: { type: 'string' } },
|
|
127
|
-
},
|
|
128
|
-
},
|
|
129
|
-
|
|
130
|
-
cache: { staleTime: 30, gcTime: 300, tags: ['catalog'] },
|
|
131
|
-
|
|
132
|
-
routes: [
|
|
133
|
-
{ method: 'GET', path: '/featured', handler: 'getFeatured', permissions: allowPublic() },
|
|
134
|
-
{ method: 'POST', path: '/webhook', rawHandler: webhookFn, permissions: requireAuth() },
|
|
135
|
-
],
|
|
136
|
-
actions: {
|
|
137
|
-
approve: { handler: approveOrder, permissions: requireRoles(['admin']) },
|
|
138
|
-
},
|
|
139
|
-
});
|
|
140
|
-
```
|
|
141
|
-
|
|
142
|
-
**Auto-generated:** `GET /`, `GET /:id`, `POST /`, `PATCH /:id`, `DELETE /:id`. Presets add their own routes (see table below).
|
|
143
|
-
|
|
144
|
-
### Custom routes: `handler` vs `rawHandler`
|
|
145
|
-
|
|
146
|
-
A route declares its execution model by WHICH FIELD it fills — there is no `raw` flag (removed in 2.31).
|
|
147
|
-
|
|
148
|
-
| Field | Signature | Behaviour |
|
|
149
|
-
|---|---|---|
|
|
150
|
-
| `handler` | `(ctx: IRequestContext)` or a controller-method name | Arc pipeline: envelope shaping, field-write permissions, MCP tool by default |
|
|
151
|
-
| `rawHandler` | `(request, reply)` or a controller-method name | Fastify-native: owns the response, no pipeline, no MCP unless `mcpHandler` is set |
|
|
152
|
-
| `controllerMethod` | `(c: MyController) => c.method` | Typed ref for the pipeline — TS catches typos |
|
|
153
|
-
|
|
154
|
-
Declaring both `handler` and `rawHandler` throws at boot. `streamResponse: true` requires `rawHandler` (the handler is invoked with `(request, reply)` and owns the socket).
|
|
155
|
-
|
|
156
|
-
Inline `rawHandler` parameters infer — no `req: FastifyRequest` annotation — and typed generics (`FastifyRequest<{ Body: CreateBody }>`) assign without a cast.
|
|
157
|
-
|
|
158
|
-
**Resource shorthands:**
|
|
159
|
-
|
|
160
|
-
```typescript
|
|
161
|
-
// "fetch-all" reference data — read-only crud (list+get), defaultLimit/maxLimit=1000,
|
|
162
|
-
// cache { staleTime: 300, gcTime: 600 }. Explicit narrow flags still win.
|
|
163
|
-
defineResource({ name: 'currency', adapter, referenceData: true });
|
|
164
|
-
|
|
165
|
-
// Service resource — no adapter, no auto-CRUD, no validation, no registry entry.
|
|
166
|
-
// Equivalent to disableDefaultRoutes + skipValidation + skipRegistry.
|
|
167
|
-
defineResource({ name: 'health', customRoutesOnly: true, routes: [...] });
|
|
168
|
-
|
|
169
|
-
// Resource-level pagination knobs (no custom queryParser needed):
|
|
170
|
-
defineResource({ name: 'pipeline', adapter, defaultLimit: 200, maxLimit: 500 });
|
|
171
|
-
```
|
|
172
|
-
|
|
173
|
-
A `?limit=` above the cap is **clamped to it**, not rejected (2.33 — see Query parsing). The effective cap rides in the OpenAPI parameter description.
|
|
174
|
-
|
|
175
|
-
## fieldRules
|
|
176
|
-
|
|
177
|
-
| Flag | Effect |
|
|
178
|
-
|---|---|
|
|
179
|
-
| `systemManaged` | Strip from body, drop from `required[]`. Framework stamps the value. |
|
|
180
|
-
| `preserveForElevated` | Elevated admins keep the field on ingest (cross-tenant writes). |
|
|
181
|
-
| `immutable` / `immutableAfterCreate` | Omit from update body. |
|
|
182
|
-
| `optional` | Strip from `required[]` without touching `properties`. |
|
|
183
|
-
| `nullable` | Widen JSON-Schema `type` to include null. |
|
|
184
|
-
| `hidden` | Block from response projection + OpenAPI. |
|
|
185
|
-
| `minLength` · `maxLength` · `min` · `max` · `pattern` · `enum` · `description` | Map to AJV + OpenAPI. |
|
|
186
|
-
|
|
187
|
-
Mongoose model constraints take precedence; `fieldRules` supplements what the model doesn't declare.
|
|
188
|
-
|
|
189
|
-
## Presets
|
|
190
|
-
|
|
191
|
-
| Preset | Routes added | Config |
|
|
192
|
-
|---|---|---|
|
|
193
|
-
| `softDelete` | `GET /deleted`, `POST /:id/restore` | `{ deletedField }` |
|
|
194
|
-
| `slugLookup` | `GET /slug/:slug` | `{ slugField }` |
|
|
195
|
-
| `tree` | `GET /tree`, `GET /:parent/children` | `{ parentField }` |
|
|
196
|
-
| `ownedByUser` | (middleware only) | `{ ownerField }` |
|
|
197
|
-
| `multiTenant` | (middleware only) | `{ tenantField }` or `{ tenantFields: [...] }` |
|
|
198
|
-
| `audited` | (middleware only) | — |
|
|
199
|
-
| `bulk` | `POST/PATCH/DELETE /bulk` | `{ operations?, maxCreateItems? }` |
|
|
200
|
-
| `filesUpload` | `POST /upload`, `GET /:id`, `DELETE /:id` | `{ storage, sanitizeFilename?, allowedMimeTypes?, maxFileSize? }` |
|
|
201
|
-
| `search` | `POST /search`, `/search-similar`, `/embed` | `{ repository?, search?, similar?, embed? }` |
|
|
202
|
-
|
|
203
|
-
```typescript
|
|
204
|
-
presets: ['softDelete', { name: 'multiTenant', tenantField: 'organizationId' }]
|
|
205
|
-
```
|
|
206
|
-
|
|
207
|
-
**`tenantField: false`** disables the silent org filter — use it for lookup tables, platform settings, cross-org reports.
|
|
208
|
-
|
|
209
|
-
**`idField`** picks the lookup column for `:id` (default `_id`). URL segment is always `:id`. A 404 on `PATCH /agents/foo` when `GET` works is usually a permission `filters` clause excluding the row — not an `idField` bug.
|
|
210
|
-
|
|
211
|
-
## Permissions
|
|
212
|
-
|
|
213
|
-
A `PermissionCheck` returns `boolean | AuthorizationDecision` — build one with `allow({ policy?, scope? })` / `deny(reason?)`. `policy` is ANDed into the repo query (row-level ABAC); `scope` stamps attributes downstream. The pre-2.30 `{ granted, filters }` shape THROWS — never emit it.
|
|
214
|
-
|
|
215
|
-
**Public but row-filtered** — use `allowPublic({ policy })`, not a hand-written `allow({ policy })`: a hand-written check lacks the `_isPublic` flag, so anonymous callers get 401.
|
|
216
|
-
|
|
217
|
-
```typescript
|
|
218
|
-
list: allowPublic({ policy: { status: 'published' } }), // strangers: published only
|
|
219
|
-
list: allowPublic({ policy: (ctx) => isElevated(scopeOf(ctx)) ? {} : { status: 'published' } }), // {} = unrestricted
|
|
220
|
-
```
|
|
221
|
-
|
|
222
|
-
```typescript
|
|
223
|
-
import {
|
|
224
|
-
allowPublic, requireAuth, requireRoles, requireOwnership,
|
|
225
|
-
requireOrgMembership, requireOrgRole, requireTeamMembership,
|
|
226
|
-
requireServiceScope, requireScopeContext, requireOrgInScope,
|
|
227
|
-
allOf, anyOf, when, denyAll,
|
|
228
|
-
createDynamicPermissionMatrix,
|
|
229
|
-
} from '@classytic/arc/permissions';
|
|
230
|
-
|
|
231
|
-
permissions: {
|
|
232
|
-
list: allowPublic(),
|
|
233
|
-
create: requireRoles(['admin', 'editor']),
|
|
234
|
-
update: anyOf(requireOwnership('userId'), requireRoles(['admin'])),
|
|
235
|
-
delete: allOf(requireAuth(), requireRoles(['admin'])),
|
|
236
|
-
bulkImport: anyOf(requireOrgRole('admin'), requireServiceScope('jobs:bulk-write')),
|
|
237
|
-
}
|
|
238
|
-
```
|
|
239
|
-
|
|
240
|
-
**Custom check:**
|
|
241
|
-
|
|
242
|
-
```typescript
|
|
243
|
-
import { allow, deny, type PermissionCheck } from '@classytic/arc/permissions';
|
|
244
|
-
|
|
245
|
-
const requirePro = (): PermissionCheck => async (ctx) => {
|
|
246
|
-
if (!ctx.user) return deny('Auth required');
|
|
247
|
-
return ctx.user.plan === 'pro' ? allow() : deny('Pro plan required');
|
|
248
|
-
};
|
|
249
|
-
```
|
|
250
|
-
|
|
251
|
-
**Field-level:**
|
|
252
|
-
|
|
253
|
-
```typescript
|
|
254
|
-
import { fields } from '@classytic/arc/permissions';
|
|
255
|
-
fields: {
|
|
256
|
-
password: fields.hidden(),
|
|
257
|
-
salary: fields.visibleTo(['admin', 'hr']),
|
|
258
|
-
role: fields.writableBy(['admin']),
|
|
259
|
-
email: fields.redactFor(['viewer'], '***'),
|
|
260
|
-
}
|
|
261
|
-
```
|
|
262
|
-
|
|
263
|
-
**Dynamic ACL (DB-backed):**
|
|
264
|
-
|
|
265
|
-
```typescript
|
|
266
|
-
const acl = createDynamicPermissionMatrix({
|
|
267
|
-
resolveRolePermissions: (ctx) => aclService.getRoleMatrix(ctx.user.orgId),
|
|
268
|
-
cacheStore: new RedisCacheStore({ client: redis, prefix: 'acl:' }),
|
|
269
|
-
});
|
|
270
|
-
permissions: { list: acl.canAction('product', 'read') }
|
|
271
|
-
```
|
|
272
|
-
|
|
273
|
-
`requireRoles()` checks BOTH platform roles (`user.role`) and org roles (`scope.orgRoles`). For mixed human + machine routes, combine with `requireServiceScope(...)` via `anyOf(...)`.
|
|
274
|
-
|
|
275
|
-
## RequestScope
|
|
276
|
-
|
|
277
|
-
Five kinds, populated by your auth function. **Always read via accessors from `@classytic/arc/scope`** — never direct property access.
|
|
278
|
-
|
|
279
|
-
```typescript
|
|
280
|
-
type RequestScope =
|
|
281
|
-
| { kind: 'public' }
|
|
282
|
-
| { kind: 'authenticated'; userId?; userRoles? }
|
|
283
|
-
| { kind: 'member'; userId?; userRoles; organizationId; orgRoles; teamId?; context?; ancestorOrgIds? }
|
|
284
|
-
| { kind: 'service'; clientId; organizationId; scopes?; context?; ancestorOrgIds?; mandate?; dpopJkt? }
|
|
285
|
-
| { kind: 'elevated'; userId?; organizationId?; elevatedBy; context?; ancestorOrgIds? };
|
|
286
|
-
|
|
287
|
-
import {
|
|
288
|
-
isMember, isService, isElevated, hasOrgAccess,
|
|
289
|
-
getOrgId, getUserId, getUserRoles, getOrgRoles, getServiceScopes,
|
|
290
|
-
getScopeContext, getAncestorOrgIds, isOrgInScope,
|
|
291
|
-
requireOrgId, requireUserId, // throwing accessors for handler boundaries
|
|
292
|
-
} from '@classytic/arc/scope';
|
|
293
|
-
```
|
|
294
|
-
|
|
295
|
-
| Helper | `member` | `service` | `elevated` |
|
|
296
|
-
|---|---|---|---|
|
|
297
|
-
| `requireOrgMembership()` | ✅ | ✅ | ✅ |
|
|
298
|
-
| `requireOrgRole(roles)` | role match | ❌ | bypass |
|
|
299
|
-
| `requireServiceScope(scopes)` | ❌ | scope match | bypass |
|
|
300
|
-
| `requireTeamMembership()` | `teamId` set | n/a | bypass |
|
|
301
|
-
| `requireOrgInScope(target)` | target in chain | target in chain | bypass |
|
|
302
|
-
|
|
303
|
-
Populate `scope.context` / `scope.ancestorOrgIds` in your auth function for branch/region scoping and parent-child org chains. Then `multiTenantPreset({ tenantFields: [...] })` auto-filters by every dimension. → [references/multi-tenancy.md](references/multi-tenancy.md)
|
|
304
|
-
|
|
305
|
-
## Authentication
|
|
306
|
-
|
|
307
|
-
Discriminated union on `type`:
|
|
308
|
-
|
|
309
|
-
```typescript
|
|
310
|
-
auth: { type: 'jwt', jwt: { secret, expiresIn: '15m' } } // arc JWT
|
|
311
|
-
auth: { type: 'betterAuth', betterAuth: createBetterAuthAdapter({ auth }) } // Better Auth
|
|
312
|
-
auth: { type: 'custom', plugin: myAuthPlugin } // any Fastify plugin
|
|
313
|
-
auth: { type: 'authenticator', authenticate: async (req, reply) => { … } } // ad-hoc fn
|
|
314
|
-
auth: false // internal services
|
|
315
|
-
```
|
|
316
|
-
|
|
317
|
-
Decorates `app.authenticate` / `app.optionalAuthenticate` / `app.authorize`.
|
|
318
|
-
|
|
319
|
-
**Better Auth** is arc's recommended path for SaaS with orgs. Kit overlays read whatever BA plugins you enabled (`organization`, `twoFactor`, `admin`, `bearer`, `apiKey` from `@better-auth/api-key`). Bulk-stub populate models with `registerBetterAuthStubs(mongoose, { plugins, extraCollections })`; per-resource overlay with `createBetterAuthOverlay({ auth, mongoose, collection })`. Sqlitekit is symmetric. Full recipes (multi-plugin matrix, API-key flow, write path) → [references/auth.md](references/auth.md).
|
|
320
|
-
|
|
321
|
-
## Authoritative gotchas
|
|
322
|
-
|
|
323
|
-
- **Field-write reject (default).** Requests carrying non-writable fields → 403 with denied list. Opt into silent strip: `defineResource({ onFieldWriteDenied: 'strip' })`.
|
|
324
|
-
- **Immutable writes are STRIPPED, not refused (default).** `PATCH {"type":"rent"}` on an `immutable` field returns 200 with the value unchanged. Opt into 403: `defineResource({ onImmutableWrite: 'reject' })`, or `ARC_STRICT_IMMUTABLE_WRITES=true`. Separate from `onFieldWriteDenied` because a full-object PATCH echoing an immutable field back UNCHANGED is legitimate, and the sanitizer has no stored document to tell that from a real change — turn it on if you send partial patches.
|
|
325
|
-
- **Log redaction is REPLACED, not merged.** Setting `logger.redact` makes yours the whole policy; arc's defaults stop applying. Superset them: `import { DEFAULT_LOGGER_REDACT_PATHS } from '@classytic/arc/factory'` and spread it into your list, rather than hand-copying (a copy drifts — one host's had lost `*.passwordHash`).
|
|
326
|
-
- **Error disclosure derives from `preset`, falling back to the environment.** `includeStack` and `exposeInternalMessages` are both derived, and host keys MERGE over them — stating one no longer resets the other. Direct `errorHandlerPlugin` registration skips the preset derivation entirely.
|
|
327
|
-
- **multiTenant injects org on UPDATE.** Body `organizationId` is overwritten with caller's scope (closes tenant-hop).
|
|
328
|
-
- **`request.user`** is `Record<string, unknown> | undefined`. Guard with `if (req.user)` on public routes.
|
|
329
|
-
- **Arc reads singular `user.role`** (string, comma-separated, or array). Don't put a plural `roles` field on the model.
|
|
330
|
-
- **`verifySignature(body, …)`** throws on parsed body — pass `req.rawBody`.
|
|
331
|
-
- **MCP tools fail-closed.** A resource action without per-action perm + no `actionPermissions` + no `permissions.update` fallback → throws at tool generation. Declare `allowPublic()` to opt into unauthenticated.
|
|
332
|
-
- **Better Auth roles.** BA stores `member.role = "admin,recruiter"` (comma-separated). Arc splits into `scope.orgRoles = ['admin', 'recruiter']`; `?role=admin` won't match — use `role[like]=admin`.
|
|
333
|
-
- **Read-only repositories refuse write ROUTES at boot (2.33).** Kits' Better Auth overlays are sealed by default (`capabilities.readOnly`) — BA owns hashing, session revocation, org cascades. Mounting `create`/`update`/`delete` over one is boot-fatal: disable those routes, or pass the kit's `unsafeWritable: true` for administrative repair only. Normal identity mutations go through `auth.api`.
|
|
334
|
-
- **Arc closes only stores/transports it BUILT (2.33).** One you hand to `idempotencyPlugin` / `eventPlugin` / `queryCachePlugin` stays yours to close — arc used to close every one, which wiped a co-resident app's live idempotency records.
|
|
335
|
-
- **Idempotency self-checks its store at boot (2.33).** A probe write must read back under its own key and NOT under another; registration throws otherwise. Catches a filter-stripping repository (a pathless Mongoose schema under `strictQuery: true` strips filters to `{}`), which otherwise replays cached responses across keys AND users. `selfCheck: false` to disable; the adapter's per-read identity checks remain.
|
|
336
|
-
|
|
337
|
-
## routeGuards + defineGuard
|
|
338
|
-
|
|
339
|
-
Apply guards to **every** route on a resource (CRUD + custom + preset):
|
|
340
|
-
|
|
341
|
-
```typescript
|
|
342
|
-
import { defineGuard } from '@classytic/arc/utils';
|
|
343
|
-
|
|
344
|
-
const tenantGuard = defineGuard({
|
|
345
|
-
name: 'tenant',
|
|
346
|
-
resolve: (req) => {
|
|
347
|
-
const orgId = req.headers['x-org-id'] as string;
|
|
348
|
-
if (!orgId) throw new Error('Missing x-org-id');
|
|
349
|
-
return { orgId, actorId: req.user?.id ?? 'system' };
|
|
350
|
-
},
|
|
351
|
-
});
|
|
352
|
-
|
|
353
|
-
defineResource({
|
|
354
|
-
name: 'procurement',
|
|
355
|
-
routeGuards: [tenantGuard.preHandler],
|
|
356
|
-
routes: [{
|
|
357
|
-
method: 'GET', path: '/summary', permissions: requireAuth(),
|
|
358
|
-
rawHandler: async (req, reply) => {
|
|
359
|
-
const { orgId } = tenantGuard.from(req);
|
|
360
|
-
reply.send({ orgId });
|
|
361
|
-
},
|
|
362
|
-
}],
|
|
363
|
-
});
|
|
364
|
-
```
|
|
365
|
-
|
|
366
|
-
**Order:** auth → permissions → cache/idempotency → `routeGuards` → per-route `preHandler`.
|
|
367
|
-
|
|
368
|
-
## Query parsing
|
|
369
|
-
|
|
370
|
-
```
|
|
371
|
-
GET /products?page=2&limit=20&sort=-createdAt&select=name,price
|
|
372
|
-
GET /products?price[gte]=100&status[in]=active,featured&search=keyword
|
|
373
|
-
GET /products?after=<cursor_id>&limit=20 # keyset
|
|
374
|
-
GET /products?populate[category][select]=name,slug
|
|
375
|
-
GET /products?filter[status]=active&filter[price][gte]=100 # bracket envelope (2.16)
|
|
376
|
-
```
|
|
377
|
-
|
|
378
|
-
Operators: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`, `like`, `regex`, `exists`.
|
|
379
|
-
|
|
380
|
-
**Whitelisted parser (MCP filter auto-derive):**
|
|
381
|
-
|
|
382
|
-
```typescript
|
|
383
|
-
import { QueryParser } from '@classytic/mongokit';
|
|
384
|
-
|
|
385
|
-
defineResource({
|
|
386
|
-
queryParser: new QueryParser({
|
|
387
|
-
allowedFilterFields: ['status', 'category', 'orgId'],
|
|
388
|
-
allowedSortFields: ['createdAt', 'price'],
|
|
389
|
-
allowedOperators: ['eq', 'gte', 'lte', 'in'],
|
|
390
|
-
}),
|
|
391
|
-
schemaOptions: { query: { allowedPopulate: ['category'], allowedLookups: ['categories'] } },
|
|
392
|
-
});
|
|
393
|
-
```
|
|
394
|
-
|
|
395
|
-
**An unknown filter key is DROPPED by default, and dropping WIDENS.** `?filters[status]=pending`
|
|
396
|
-
against a parser that does not whitelist `status` returns 200 with every row unfiltered — the
|
|
397
|
-
caller asked to narrow and got a broader set. Refuse instead:
|
|
398
|
-
|
|
399
|
-
```typescript
|
|
400
|
-
new QueryParser({ allowedFilterFields: [...], strictFilterFields: true }) // 400 ValidationError
|
|
401
|
-
```
|
|
402
|
-
|
|
403
|
-
Off by default (an unconditional throw would reject requests that work today). Fleet-wide via
|
|
404
|
-
`ARC_STRICT_QUERY_PARAMS=true`; an explicit `false` beats the env. Only the FILTER whitelist —
|
|
405
|
-
a dropped sort or operator degrades ordering, it does not widen the row set.
|
|
406
|
-
|
|
407
|
-
**`?limit` above the cap CLAMPS, it does not 400** (2.33). The parser and `QueryResolver` both
|
|
408
|
-
clamp, and the querystring schema no longer emits `maximum` — it used to reject first, making the
|
|
409
|
-
documented clamp unreachable and turning a benign over-ask into a 400 that callers render as an
|
|
410
|
-
empty list. The cap is in the parameter description instead, so OpenAPI still shows it.
|
|
411
|
-
|
|
412
|
-
**One cap, one owner.** Page size is capped by the parser, the repository's pagination engine and
|
|
413
|
-
arc — lowest wins silently. Arc defers to the parser's `maxLimit` when the host states none, and
|
|
414
|
-
WARNS at boot when the parser allows more than the repository (`pagination-cap-mismatch`).
|
|
415
|
-
Configure both to the same number.
|
|
416
|
-
|
|
417
|
-
## Aggregations
|
|
418
|
-
|
|
419
|
-
`GET /:prefix/aggregations/:name` per entry. Portable `$match → $group → $project → $sort → $limit` against `repo.aggregate(req, options)` — same shape across kits.
|
|
420
|
-
|
|
421
|
-
```typescript
|
|
422
|
-
import { defineResource, defineAggregation } from '@classytic/arc';
|
|
423
|
-
|
|
424
|
-
defineResource({
|
|
425
|
-
name: 'transaction',
|
|
426
|
-
adapter,
|
|
427
|
-
presets: [multiTenantPreset({ tenantField: 'organizationId' })],
|
|
428
|
-
permissions: { list: canViewRevenue() },
|
|
429
|
-
aggregations: {
|
|
430
|
-
byPaymentMethod: defineAggregation({
|
|
431
|
-
groupBy: 'method',
|
|
432
|
-
measures: { total: 'sum:amount', count: 'count' },
|
|
433
|
-
sort: { total: -1 },
|
|
434
|
-
cache: { staleTime: 60, swr: true, tags: ['revenue'] },
|
|
435
|
-
permissions: canViewRevenue(),
|
|
436
|
-
}),
|
|
437
|
-
byDay: defineAggregation({
|
|
438
|
-
dateBuckets: { day: { field: 'createdAt', interval: 'day' } },
|
|
439
|
-
groupBy: 'flow',
|
|
440
|
-
measures: { total: 'sum:amount', count: 'count' },
|
|
441
|
-
requireDateRange: { field: 'createdAt', maxRangeDays: 365 },
|
|
442
|
-
permissions: canViewRevenue(),
|
|
443
|
-
}),
|
|
444
|
-
},
|
|
445
|
-
});
|
|
446
|
-
```
|
|
447
|
-
|
|
448
|
-
Safety guards on the declaration: `requireFilters`, `requireDateRange { field, maxRangeDays }`, `maxGroups`. Caller query-string filters compose with `groupBy` / measures. SWR + `tags` invalidation tie aggregations to CRUD writes. Every aggregation auto-exports as an MCP tool.
|
|
449
|
-
|
|
450
|
-
Tenant scope flows through `options` (second arg), NOT into `aggReq.filter`. The kit's multi-tenant plugin handles type coercion (string → ObjectId, UUID/text, etc.). **Aggregation-only resources** (`disableDefaultRoutes: true` + no controller) work — arc falls back to the adapter's repo. If aggregations exist without a repo AND without `materialized`, `defineResource()` throws at boot.
|
|
451
|
-
|
|
452
|
-
### `materialized` hook — escape hatch + footgun
|
|
453
|
-
|
|
454
|
-
When a kit can't express your aggregation in the portable IR (`$graphLookup`, window functions, custom SQL), declare a `materialized` hook to own dispatch yourself:
|
|
455
|
-
|
|
456
|
-
```typescript
|
|
457
|
-
defineAggregation({
|
|
458
|
-
measures: { count: 'count' },
|
|
459
|
-
permissions: canViewRevenue(),
|
|
460
|
-
materialized: async (ctx) => {
|
|
461
|
-
// ctx = { filter, orgId, userId, requestId, query }
|
|
462
|
-
// ⚠️ ctx.filter contains ONLY the declaration filter + caller query string.
|
|
463
|
-
// Tenant scope is in ctx.orgId, NOT in ctx.filter. Soft-delete is NOT merged.
|
|
464
|
-
// Bypassing repo.aggregate() means bypassing the kit's hook pipeline.
|
|
465
|
-
|
|
466
|
-
// ✅ Right (mongokit) — route through repo.aggregatePipeline so the kit's
|
|
467
|
-
// multi-tenant + soft-delete + audit hooks all run:
|
|
468
|
-
const rows = await orderRepo.aggregatePipeline(
|
|
469
|
-
[{ $group: { _id: '$flow', total: { $sum: '$amount' } } }],
|
|
470
|
-
{ organizationId: ctx.orgId, userId: ctx.userId, requestId: ctx.requestId },
|
|
471
|
-
);
|
|
472
|
-
return { rows };
|
|
473
|
-
|
|
474
|
-
// ❌ Wrong — Model.aggregate(...) bypasses kit plugins; tenant + soft-delete
|
|
475
|
-
// leak across orgs. Never call the driver directly in a materialized hook.
|
|
476
|
-
},
|
|
477
|
-
});
|
|
478
|
-
```
|
|
479
|
-
|
|
480
|
-
For sqlitekit / custom adapters without an `aggregatePipeline` equivalent, **you** must inject tenant + soft-delete clauses into the SQL before executing — `ctx.filter` is not sufficient. Prefer the portable `repo.aggregate(req, options)` path whenever the IR can express your shape.
|
|
481
|
-
|
|
482
|
-
## QueryCache
|
|
483
|
-
|
|
484
|
-
TanStack-Query-style server cache with SWR + auto-invalidation on mutations:
|
|
485
|
-
|
|
486
|
-
```typescript
|
|
487
|
-
const app = await createApp({ arcPlugins: { queryCache: true } });
|
|
488
|
-
|
|
489
|
-
defineResource({
|
|
490
|
-
cache: {
|
|
491
|
-
staleTime: 30, gcTime: 300, tags: ['catalog'],
|
|
492
|
-
invalidateOn: { 'category.*': ['catalog'] }, // event pattern → tag targets
|
|
493
|
-
list: { staleTime: 60 },
|
|
494
|
-
byId: { staleTime: 10 },
|
|
495
|
-
},
|
|
496
|
-
});
|
|
497
|
-
```
|
|
498
|
-
|
|
499
|
-
POST/PATCH/DELETE bumps resource version. Response header: `x-cache: HIT | STALE | MISS`. `runtime: 'distributed'` requires `stores.queryCache: RedisCacheStore`.
|
|
500
|
-
|
|
501
|
-
## Transactional writes (2.33)
|
|
502
|
-
|
|
503
|
-
`transactional: true` runs the PERSISTENCE step inside `withTransaction`. Write verbs receive the tx-bound repository plus `ctx.uow` — the join point for work outside the repository:
|
|
504
|
-
|
|
505
|
-
```typescript
|
|
506
|
-
defineResource({
|
|
507
|
-
name: 'order',
|
|
508
|
-
adapter,
|
|
509
|
-
transactional: true,
|
|
510
|
-
writes: {
|
|
511
|
-
create: async (data, ctx) => {
|
|
512
|
-
const order = await ctx.repository.create(data); // tx-bound
|
|
513
|
-
await outbox.store(event, { session: ctx.uow?.session }); // SAME transaction
|
|
514
|
-
return order;
|
|
515
|
-
},
|
|
516
|
-
},
|
|
517
|
-
});
|
|
518
|
-
```
|
|
519
|
-
|
|
520
|
-
- Hooks stay OUTSIDE the retry — before/after run once; only persistence re-runs.
|
|
521
|
-
- Transient conflicts re-run with jittered backoff; `VersionConflictError` surfaces (409), never retried.
|
|
522
|
-
- **Retry authority is the KIT's.** mongokit declares `transactionRetry: 'managed'` (its driver already retries internally) and is called exactly once; sqlitekit declares `'caller'` and gets the envelope's loop. Arc never stacks a second policy.
|
|
523
|
-
- **BOOT-FATAL** without `withTransaction`, and at REGISTRATION when the repository reports `capabilities.transactions !== true` (standalone Mongo, D1, unconfirmed topology). The capability is checked at registration, not at `defineResource()`, because that usually runs at module import — before `beforeBoot()` connects.
|
|
524
|
-
- `ctx.uow.session` is empty on connection-bound backends (SQLite); the tx-bound repo is the join point there.
|
|
525
|
-
|
|
526
|
-
## Events
|
|
527
|
-
|
|
528
|
-
CRUD events auto-emit: `{resource}.created` / `{resource}.updated` / `{resource}.deleted`. Manual publish:
|
|
529
|
-
|
|
530
|
-
```typescript
|
|
531
|
-
await app.events.publish('order.created', { orderId: '123' });
|
|
532
|
-
await app.events.subscribe('order.*', async (event) => { … });
|
|
533
|
-
```
|
|
534
|
-
|
|
535
|
-
Transports: Memory · Redis Pub/Sub (fire-and-forget) · Redis Streams (durable, consumer groups, DLQ). Event types live in `@classytic/primitives/events` (`createEvent`, `createChildEvent`, `matchEventPattern`, …); arc re-exports the runtime `MemoryEventTransport` only.
|
|
536
|
-
|
|
537
|
-
**Outbox** (at-least-once via transactional outbox) — prefer the MODULE, so the store is a slot other modules depend on rather than a value threaded by hand:
|
|
538
|
-
|
|
539
|
-
```typescript
|
|
540
|
-
createApp({ modules: [createOutboxModule({ store: repositoryAsOutboxStore(outboxRepo) })] });
|
|
541
|
-
// Dev: createOutboxModule({ store: new MemoryOutboxStore() })
|
|
542
|
-
```
|
|
543
|
-
|
|
544
|
-
The relay arm is `kind: 'relay'`, so `role: 'relay'` deployments drain it. It resolves the RAW transport, never the `fastify.events` facade (the facade fails open, which would acknowledge rows whose publish failed) — no transport is boot-fatal. **Fencing (2.33):** stores that support `claimPendingFenced` mint a token in the claim CAS; a relay that lost its lease mid-batch cannot ack or re-schedule a row a successor already owns. Feature-detected end to end.
|
|
545
|
-
|
|
546
|
-
**Durable webhooks (2.33)** — delivery survives crash and deploy, using the outbox machinery rather than a second queue:
|
|
547
|
-
|
|
548
|
-
```typescript
|
|
549
|
-
const store = repositoryAsOutboxStore(deliveryRepo);
|
|
550
|
-
createApp({
|
|
551
|
-
modules: [createDurableWebhookModule({ store })], // relay does the signed POST
|
|
552
|
-
plugins: async (f) => f.register(webhookPlugin, { durable: { store } }), // enqueue, don't POST
|
|
553
|
-
});
|
|
554
|
-
```
|
|
555
|
-
|
|
556
|
-
One row per (event × subscription), deterministic id so an at-least-once upstream enqueues each delivery exactly once. Transient failures (network/timeout/429/5xx) retry with backoff; 4xx dead-letters on the FIRST attempt. `durable` + `retry` together is a registration error.
|
|
557
|
-
|
|
558
|
-
Full event recipes (retry, DLQ, dual-publish warnings, idempotency keys) → [references/events.md](references/events.md).
|
|
559
|
-
|
|
560
|
-
## Hooks
|
|
561
|
-
|
|
562
|
-
Inline on resource. `ResourceHookContext` = `{ data, user?, meta? }`; `meta` has `id` and `existing` for update/delete.
|
|
563
|
-
|
|
564
|
-
```typescript
|
|
565
|
-
hooks: {
|
|
566
|
-
beforeCreate: async (ctx) => { ctx.data.slug = slugify(ctx.data.name); },
|
|
567
|
-
afterCreate: async (ctx) => { analytics.track('created', { id: ctx.data._id }); },
|
|
568
|
-
beforeUpdate: async (ctx) => { /* ctx.meta.existing has the pre-image */ },
|
|
569
|
-
beforeDelete: async (ctx) => { if (ctx.data.isProtected) throw new Error('locked'); },
|
|
570
|
-
}
|
|
571
|
-
```
|
|
572
|
-
|
|
573
|
-
App-level (cross-resource): `createHookSystem()` + `beforeCreate(hooks, 'product', fn)` from `@classytic/arc/hooks`.
|
|
574
|
-
|
|
575
|
-
## Errors
|
|
576
|
-
|
|
577
|
-
```typescript
|
|
578
|
-
import { ArcError, NotFoundError, ValidationError, createDomainError } from '@classytic/arc';
|
|
579
|
-
|
|
580
|
-
throw new NotFoundError('Product'); // 404
|
|
581
|
-
throw createDomainError('SELF_REFERRAL', 'Cannot self-refer', 422, { field });
|
|
582
|
-
```
|
|
583
|
-
|
|
584
|
-
Wire envelope: `{ code, message, status, meta?, correlationId? }`. HTTP status is the discriminator — no `success` field. Custom mappers:
|
|
585
|
-
|
|
586
|
-
```typescript
|
|
587
|
-
errorHandler: {
|
|
588
|
-
errorMappers: [{
|
|
589
|
-
type: AccountingError,
|
|
590
|
-
toResponse: (err) => ({ status: err.status, code: err.code, message: err.message }),
|
|
591
|
-
}],
|
|
592
|
-
}
|
|
593
|
-
```
|
|
594
|
-
|
|
595
|
-
Modules ship their own via `defineModule({ errorMappers })` (2.21) — merged into the app handler at boot; host-level mappers keep priority.
|
|
596
|
-
|
|
597
|
-
## Testing
|
|
598
|
-
|
|
599
|
-
```typescript
|
|
600
|
-
import { createTestApp, expectArc } from '@classytic/arc/testing';
|
|
601
|
-
|
|
602
|
-
const ctx = await createTestApp({
|
|
603
|
-
resources: [productResource],
|
|
604
|
-
authMode: 'jwt', // 'jwt' | 'better-auth' | 'none'
|
|
605
|
-
connectMongoose: true, // in-memory Mongo
|
|
606
|
-
});
|
|
607
|
-
ctx.auth.register('admin', { user: { id: '1', role: 'admin' }, orgId: 'org-1' });
|
|
608
|
-
|
|
609
|
-
const res = await ctx.app.inject({
|
|
610
|
-
method: 'POST', url: '/products',
|
|
611
|
-
headers: ctx.auth.as('admin').headers,
|
|
612
|
-
payload: { name: 'Widget' },
|
|
613
|
-
});
|
|
614
|
-
expectArc(res).ok().hidesField('password');
|
|
615
|
-
await ctx.close();
|
|
616
|
-
```
|
|
617
|
-
|
|
618
|
-
Three entry points: `createTestApp` (custom), `createHttpTestHarness` (~16 auto-generated CRUD/perm/validation tests per resource), `runStorageContract` (adapter conformance). → [references/testing.md](references/testing.md)
|
|
619
|
-
|
|
620
|
-
## CLI
|
|
621
|
-
|
|
622
|
-
```bash
|
|
623
|
-
arc init my-api --mongokit --better-auth --ts # scaffold
|
|
624
|
-
arc generate resource product # alias: arc g r product
|
|
625
|
-
arc generate resource product --mcp # + MCP tools file
|
|
626
|
-
arc generate mcp analytics # standalone MCP file
|
|
627
|
-
arc docs ./openapi.json --entry ./dist/index.js # emit OpenAPI
|
|
628
|
-
arc introspect --entry ./dist/index.js
|
|
629
|
-
arc describe ./dist/resources.js --json # JSON metadata
|
|
630
|
-
arc doctor # diagnose env
|
|
631
|
-
```
|
|
632
|
-
|
|
633
|
-
Set `"mcp": true` in `.arcrc` to always generate `.mcp.ts` alongside resources.
|
|
634
|
-
|
|
635
|
-
## MCP (AI agent tools)
|
|
636
|
-
|
|
637
|
-
Resources auto-generate Model Context Protocol tools — same permissions, same field rules. Stateless by default.
|
|
638
|
-
|
|
639
|
-
```typescript
|
|
640
|
-
import { mcpPlugin } from '@classytic/arc/mcp';
|
|
641
|
-
|
|
642
|
-
await app.register(mcpPlugin, {
|
|
643
|
-
resources: [productResource, orderResource],
|
|
644
|
-
auth: false, // or: getAuth() | custom function
|
|
645
|
-
exclude: ['credential'],
|
|
646
|
-
overrides: { product: { operations: ['list', 'get'] } },
|
|
647
|
-
});
|
|
648
|
-
```
|
|
649
|
-
|
|
650
|
-
**Per-resource opt-out:** `defineResource({ mcp: false })` — exclude a resource from MCP tool generation entirely. Useful for internal-admin or write-heavy resources where you don't want LLMs poking.
|
|
651
|
-
|
|
652
|
-
**Auth modes** — `false` | `getAuth()` (Better Auth OAuth 2.1) | `createMcpAuthFromBetterAuthApiKey(getAuth(), { orgFromMetadata: true })` (BA API-key plugin — handles `referenceId`/`userId` fallback + `metadata.organizationId` extraction) | custom function returning `{ userId, organizationId, roles }` (human) or `{ clientId, organizationId, scopes }` (service). `PermissionResult.filters` flow into MCP tools exactly like REST.
|
|
653
|
-
|
|
654
|
-
**Tool-name collisions** — preset vs user (e.g. `softDelete` route vs `actions.restore`) auto-namespace to `softdelete_restore_<resource>`; every other collision shape throws `ArcError('arc.mcp.tool_name_collision')` naming both sources.
|
|
655
|
-
|
|
656
|
-
**Custom tools** — co-locate with resources (`order.mcp.ts`), wire via `extraTools`. **AI SDK bridge** — expose AI SDK `tool()` defs via `buildMcpToolsFromBridges([...])`.
|
|
657
|
-
|
|
658
|
-
Connect Claude CLI: `claude mcp add --transport http my-api http://localhost:3000/mcp`. Full recipes → [references/mcp.md](references/mcp.md).
|
|
659
|
-
|
|
660
|
-
### AI SDK streaming → Fastify
|
|
661
|
-
|
|
662
|
-
`streamResponse: true` routes that return a Web `ReadableStream` (Vercel AI SDK's `result.toUIMessageStream()`, `fetch().body`) auto-pipe through `pipeUIMessageStreamToReply()` — no `JsonToSseTransformStream` boilerplate.
|
|
663
|
-
|
|
664
|
-
```typescript
|
|
665
|
-
import { streamText } from 'ai';
|
|
666
|
-
|
|
667
|
-
defineResource({
|
|
668
|
-
name: 'chat',
|
|
669
|
-
customRoutesOnly: true,
|
|
670
|
-
routes: [{
|
|
671
|
-
method: 'POST', path: '/', streamResponse: true,
|
|
672
|
-
permissions: requireAuth(),
|
|
673
|
-
rawHandler: async (req) => {
|
|
674
|
-
const result = streamText({ model, messages: req.body.messages });
|
|
675
|
-
return result.toUIMessageStream(); // arc pipes it for you
|
|
676
|
-
},
|
|
677
|
-
}],
|
|
678
|
-
});
|
|
679
|
-
```
|
|
680
|
-
|
|
681
|
-
For manual control: `import { pipeUIMessageStreamToReply, UI_MESSAGE_STREAM_HEADERS } from '@classytic/arc/utils'`. Client disconnect cancels the source stream (no zombie LLM spend).
|
|
682
|
-
|
|
683
|
-
## Tenant cleanup (GDPR / SOX / HIPAA)
|
|
684
|
-
|
|
685
|
-
Per-resource strategy + one auth-lifecycle wire-up:
|
|
686
|
-
|
|
687
|
-
```typescript
|
|
688
|
-
defineResource({
|
|
689
|
-
name: 'invoice',
|
|
690
|
-
tenantField: 'organizationId',
|
|
691
|
-
onTenantDelete: {
|
|
692
|
-
strategy: { type: 'anonymize', fields: { customerName: '[REDACTED]', email: null } },
|
|
693
|
-
priority: 50, batchSize: 1000,
|
|
694
|
-
},
|
|
46
|
+
presets: ['softDelete', { name: 'multiTenant', tenantField: 'organizationId' }],
|
|
47
|
+
permissions: { list: allowPublic(), get: allowPublic(), create: requireRoles(['admin']),
|
|
48
|
+
update: requireRoles(['admin']), delete: requireRoles(['admin']) },
|
|
49
|
+
schemaOptions: { fieldRules: { organizationId: { systemManaged: true } } },
|
|
695
50
|
});
|
|
696
|
-
defineResource({ name: 'event', onTenantDelete: { strategy: { type: 'hard' } } });
|
|
697
|
-
defineResource({ name: 'ledger', onTenantDelete: { strategy: { type: 'skip', reason: 'SOX retention' } } });
|
|
698
|
-
|
|
699
|
-
import { cascadeDeleteForOrganization, assertNoTenantData } from '@classytic/arc/registry';
|
|
700
|
-
|
|
701
|
-
betterAuth.org.afterDelete = async ({ organizationId }) => {
|
|
702
|
-
const report = await cascadeDeleteForOrganization(fastify.arc.registry, {
|
|
703
|
-
organizationId, concurrency: 4, logger: fastify.log,
|
|
704
|
-
});
|
|
705
|
-
if (report.failures.length > 0) await alerting.fire({ report });
|
|
706
|
-
};
|
|
707
|
-
```
|
|
708
|
-
|
|
709
|
-
Strategies: `hard` · `soft` · `anonymize` (`fields` static or `(doc) => value`) · `skip` (`reason` mandatory). Resources without `onTenantDelete` are never touched. **Index `tenantField`** on every cascading resource or chunked SELECTs run O(n²). Compliance smoke: `assertNoTenantData(registry, { organizationId })`.
|
|
710
|
-
|
|
711
|
-
## Enterprise auth (opt-in)
|
|
712
|
-
|
|
713
|
-
| Capability | Surface | Reference |
|
|
714
|
-
|---|---|---|
|
|
715
|
-
| SCIM 2.0 provisioning (Okta / Azure AD / Google) | `@classytic/arc/scim` — `scimPlugin({ users, groups, bearer })` | [references/scim.md](references/scim.md) |
|
|
716
|
-
| Agent mandates + DPoP (AP2 / x402 / MCP authz) | `@classytic/arc/permissions` — `requireAgentScope`, `requireMandate`, `requireDPoP` | [references/agent-auth.md](references/agent-auth.md) |
|
|
717
|
-
| Auth-event audit bridge | `@classytic/arc/auth/audit` — `wireBetterAuthAudit({ events })` | [references/enterprise-auth.md](references/enterprise-auth.md) |
|
|
718
|
-
|
|
719
|
-
Out of scope: SAML (use BA SAML plugin), session storage (BA `secondaryStorage`), DPoP crypto (one `jose.dpop.verify()` in your `authenticate`), device trust (Castle / Stytch).
|
|
720
|
-
|
|
721
|
-
## Audit per-resource
|
|
722
|
-
|
|
723
|
-
```typescript
|
|
724
|
-
await fastify.register(auditPlugin, { autoAudit: { perResource: true } });
|
|
725
|
-
|
|
726
|
-
defineResource({ name: 'order', audit: true });
|
|
727
|
-
defineResource({ name: 'invoice', history: true }); // 2.22: injects GET /:id/history from audit rows; implies audit: true (gate: update→get→requireAuth; override via { permissions, limit })
|
|
728
|
-
defineResource({ name: 'payment', audit: { operations: ['delete'] } });
|
|
729
|
-
defineResource({ name: 'product' }); // not audited
|
|
730
|
-
|
|
731
|
-
// Manual (MCP tools / read auditing)
|
|
732
|
-
await app.audit.custom('order', req.params.id, 'refund', { reason }, { user });
|
|
733
|
-
```
|
|
734
|
-
|
|
735
|
-
## Usage counters + plan limits (2.22)
|
|
736
|
-
|
|
737
|
-
`@classytic/arc/usage` — `usagePlugin` decorates `fastify.usage` with per-actor, per-UTC-month counters (`record`/`summary`/`period`/`actorOf`; actor chain org → user → client → ip). Auto-tracks `api.requests` (default on) + `api.egress.bytes` (opt-in); recording is fail-safe (a throwing `UsageStore` never fails a request). Stores: `MemoryUsageStore` (default, single-process) and `RedisUsageStore` (2.41 — `HINCRBY`, the right shape for a hot per-request counter) both from `@classytic/arc/usage`; or a kit's (`@classytic/mongokit/usage`) when counters belong beside domain data. `RedisUsageStore` keeps counters forever by default — `retentionSeconds` is opt-in, because expiring billing history on an unchosen schedule is silent (`summary()` returns `{}` for an expired bucket and a never-written one alike). Pair with `createApp({ rateLimit: { plan: { resolve, limits: { free: { max: 60 }, enterprise: false }, default: 'free' } } })` for per-plan ceilings — `false` = unlimited, unknown/throwing resolvers fall back to `default` then global `max`, and buckets follow the tenant key chain by default. Caveat: the limiter runs before route auth, so `resolve` sees the raw request.
|
|
738
51
|
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
```typescript
|
|
744
|
-
import { declareRuntimeCapability } from '@classytic/arc/utils';
|
|
745
|
-
|
|
746
|
-
declareRuntimeCapability(fastify, {
|
|
747
|
-
subsystem: 'billing.sequence-cache',
|
|
748
|
-
durability: 'memory', // 'memory' | 'shared'
|
|
749
|
-
detail: 'invoice numbering cached per process',
|
|
750
|
-
// accepted: true, // ONLY when per-process is intended by design
|
|
751
|
-
// // (logged, never fatal). Must be stated by the
|
|
752
|
-
// // declarant — the audit never infers it.
|
|
52
|
+
const app = await createApp({
|
|
53
|
+
preset: 'production', beforeBoot: connectDb,
|
|
54
|
+
auth: { type: 'jwt', jwt: { secret: process.env.JWT_SECRET } },
|
|
55
|
+
resources: await loadResources(import.meta.url),
|
|
753
56
|
});
|
|
754
57
|
```
|
|
755
58
|
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
**Since 2.41 every memory-backed default arc ships declares itself**: `auth.sessions`, `usage.store`, `audit.store`, `cache.query`, `permissions.dynamic-cache` (pass `fastify:` to the matrix — it has no handle of its own), `websocket.adapter`, `websocket.pushref-store`, `webhooks.store`. `http.response-cache` declares `accepted` (per-replica by design). So a distributed app that booted before 2.41 can now fail on a default it was silently running replica-local — the error names each one, and `references/production.md` has the store-by-store fix table.
|
|
759
|
-
|
|
760
|
-
## Adapters
|
|
761
|
-
|
|
762
|
-
Cross-framework adapter contract lives in `@classytic/repo-core/adapter`. Every kit-specific adapter ships from its kit's `/adapter` subpath; arc itself has zero kit-bound adapters.
|
|
59
|
+
Validated route, parsed once:
|
|
763
60
|
|
|
764
61
|
```typescript
|
|
765
|
-
import {
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
import type { DataAdapter, RepositoryLike, AdapterRepositoryInput }
|
|
770
|
-
from '@classytic/repo-core/adapter';
|
|
771
|
-
// MinimalRepo<TDoc> — 5-method floor (getAll, getById, create, update, delete)
|
|
772
|
-
// StandardRepo<TDoc> — MinimalRepo + optional batch ops, CAS, soft-delete, aggregate, …
|
|
773
|
-
// Arc feature-detects optional methods at call sites; missing methods → 501.
|
|
62
|
+
import { parsed, routeInput } from '@classytic/arc/core';
|
|
63
|
+
const body = z.object({ title: z.string().trim().min(2), tags: z.array(z.string()).default([]) });
|
|
64
|
+
routes: [{ method: 'POST', path: '/notes', permissions: requireAuth(), ...routeInput({ body }),
|
|
65
|
+
rawHandler: async (req, reply) => reply.send(await notes.create(parsed(body, req.body))) }]
|
|
774
66
|
```
|
|
775
67
|
|
|
776
|
-
|
|
68
|
+
Daily job: `scheduledJobs: [{ name: 'sweep', every: 600_000, daily: { hour: 2, zone: 'Asia/Dhaka', ledger }, handler: async (f, ctx) => sweep(ctx?.day) }]`.
|
|
777
69
|
|
|
778
|
-
|
|
70
|
+
Test: `const ctx = await createTestApp({ resources: [productResource] }); expectArc(await ctx.app.inject({ method: 'GET', url: '/products' })).ok();`
|
|
779
71
|
|
|
780
|
-
|
|
72
|
+
## Gotchas
|
|
781
73
|
|
|
782
|
-
|
|
783
|
-
|
|
74
|
+
- `{ body: X }` as an action schema validates nothing (no `type`); pass the schema. `strictSchemas: true` makes it fatal.
|
|
75
|
+
- `.default()` stays optional on the wire (zod input direction); `.refine()` needs `routeInput` or `parse: true`.
|
|
76
|
+
- `request.user` is undefined on public routes: guard it.
|
|
77
|
+
- Public + row filter needs `allowPublic({ policy })`, not `allow({ policy })`.
|
|
78
|
+
- A non-writable field in a body is 403; an `immutable` field is silently stripped.
|
|
79
|
+
- An unknown filter key is dropped (widens results): `strictFilterFields: true`.
|
|
80
|
+
- `distributed` runtime needs shared stores and a schedule `lock` or `singleReplica`.
|
|
81
|
+
- Own `setNotFoundHandler` needs `errorHandler: { notFound: false }`.
|
|
82
|
+
- Refusing hook: `return reply.send(...)` or throw, never a bare send.
|
|
784
83
|
|
|
785
|
-
|
|
786
|
-
constructor(opts: { tenantField?: string | false; idField?: string } = {}) {
|
|
787
|
-
super(productRepo, { resourceName: 'product', ...opts });
|
|
788
|
-
}
|
|
789
|
-
async getFeatured(req: IRequestContext): Promise<IControllerResponse<Product[]>> {
|
|
790
|
-
return { data: await this.repository.getAll({ filters: { isFeatured: true } }) };
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
defineResource({ name: 'product', controller: new ProductController({ tenantField: '_id' }), tenantField: '_id' });
|
|
795
|
-
```
|
|
796
|
-
|
|
797
|
-
When you pass your own controller, arc **cannot** thread `tenantField` / `schemaOptions` / `idField` / `cache` / `onFieldWriteDenied` into it. Forward via `super()` AND pass to `defineResource()`. Presets that inject controller fields (slugLookup, softDelete, tree) only reach arc's auto-built `BaseController` — extend `BaseController` or drop the preset.
|
|
798
|
-
|
|
799
|
-
**Slim mixins** (no soft-delete/tree/slug/bulk on by default):
|
|
800
|
-
|
|
801
|
-
```typescript
|
|
802
|
-
import { BaseCrudController, SoftDeleteMixin, BulkMixin, SlugMixin, TreeMixin } from '@classytic/arc';
|
|
803
|
-
class OrderController extends SoftDeleteMixin(BulkMixin(BaseCrudController)) {}
|
|
804
|
-
```
|
|
805
|
-
|
|
806
|
-
## DX helpers
|
|
807
|
-
|
|
808
|
-
```typescript
|
|
809
|
-
import type { ArcRequest } from '@classytic/arc';
|
|
810
|
-
import { envelope } from '@classytic/arc';
|
|
811
|
-
import { multipartBody } from '@classytic/arc/middleware';
|
|
812
|
-
|
|
813
|
-
// Typed request — no `(req as any).user`
|
|
814
|
-
rawHandler: async (req: ArcRequest, reply) => { req.user?.id; req.scope; req.signal; }
|
|
815
|
-
|
|
816
|
-
// File upload — no-op for JSON requests, safe to always add
|
|
817
|
-
defineResource({
|
|
818
|
-
name: 'product',
|
|
819
|
-
middlewares: { create: [multipartBody({ allowedMimeTypes: ['image/png'], maxFileSize: 5 * 1024 * 1024 })] },
|
|
820
|
-
hooks: {
|
|
821
|
-
'before:create': async (data) => {
|
|
822
|
-
if (data._files?.image) { data.imageUrl = await uploadToS3(data._files.image); delete data._files; }
|
|
823
|
-
return data;
|
|
824
|
-
},
|
|
825
|
-
},
|
|
826
|
-
});
|
|
827
|
-
|
|
828
|
-
// SSE — preAuth runs before auth (EventSource can't set headers); rawHandler streams the response
|
|
829
|
-
routes: [
|
|
830
|
-
{ preAuth: [(req) => { req.headers.authorization = `Bearer ${req.query.token}`; }] },
|
|
831
|
-
{ method: 'GET', path: '/stream', rawHandler: async (req, reply) => reply.send(stream) },
|
|
832
|
-
]
|
|
833
|
-
|
|
834
|
-
// Per-route rate limit (2.20) — overrides the resource/app default for ONE endpoint.
|
|
835
|
-
// `false` = never throttle, object = tighten, omit = inherit. Custom routes only;
|
|
836
|
-
// actions share one POST /:id/action mount, so throttle an action by making it a route.
|
|
837
|
-
routes: [
|
|
838
|
-
{ method: 'POST', path: '/export', handler: 'export', permissions: requireAuth(),
|
|
839
|
-
rateLimit: { max: 5, timeWindow: '1 minute' } },
|
|
840
|
-
{ method: 'GET', path: '/health', handler: 'health', permissions: allowPublic(),
|
|
841
|
-
rateLimit: false },
|
|
842
|
-
]
|
|
843
|
-
|
|
844
|
-
// Per-resource opt-out of resourcePrefix (webhooks / admin routes)
|
|
845
|
-
defineResource({ name: 'webhook', prefix: '/hooks', skipGlobalPrefix: true });
|
|
846
|
-
|
|
847
|
-
// Reply helpers — opt-in via createApp({ replyHelpers: true })
|
|
848
|
-
return reply.sendList({ method: 'offset', data, total, page, limit, pages, hasNext, hasPrev });
|
|
849
|
-
return reply.stream(csvReadable, { contentType: 'text/csv', filename: 'export.csv' });
|
|
850
|
-
```
|
|
851
|
-
|
|
852
|
-
## Subpath imports
|
|
853
|
-
|
|
854
|
-
```typescript
|
|
855
|
-
import { defineResource, BaseController, allowPublic } from '@classytic/arc';
|
|
856
|
-
import { createApp, loadResources } from '@classytic/arc/factory';
|
|
857
|
-
import { createMongooseAdapter } from '@classytic/mongokit/adapter';
|
|
858
|
-
import type { DataAdapter, RepositoryLike } from '@classytic/repo-core/adapter';
|
|
859
|
-
import { getUserId, getOrgId, requireOrgId } from '@classytic/arc/scope';
|
|
860
|
-
import { mcpPlugin } from '@classytic/arc/mcp';
|
|
861
|
-
import { createTestApp, expectArc } from '@classytic/arc/testing';
|
|
862
|
-
```
|
|
84
|
+
## Never
|
|
863
85
|
|
|
864
|
-
|
|
86
|
+
- Hand-written `.parse()` in every handler, cron or marker-row gates, `setInterval` jobs, manual tenant filters.
|
|
87
|
+
- A bare `fastify.get()` (bypasses auth, OpenAPI, MCP).
|
|
88
|
+
- Reading `node_modules` for the API; deep imports.
|
|
865
89
|
|
|
866
90
|
## References
|
|
867
91
|
|
|
868
|
-
-
|
|
869
|
-
-
|
|
870
|
-
-
|
|
871
|
-
-
|
|
872
|
-
-
|
|
873
|
-
-
|
|
874
|
-
-
|
|
875
|
-
-
|
|
876
|
-
- **[multi-tenancy](references/multi-tenancy.md)** — Scope ladder, `tenantField`, parent-child orgs, API-key auth
|
|
877
|
-
- **[production](references/production.md)** — Health, audit, idempotency, tracing, metrics, versioning, SSE, bulk ops
|
|
878
|
-
- **[testing](references/testing.md)** — Test app, mocks, fixtures, in-memory Mongo
|
|
92
|
+
- Core: `references/resources.md` defineResource, presets, fieldRules; `references/boot.md` createApp, roles, controllers, CLI; `references/validation.md` zod slots, routeInput; `references/querying.md` parser, aggregations, cache; `references/writes-hooks-errors.md` transactions, hooks, errors, audit
|
|
93
|
+
- Jobs: `references/schedules.md` interval and daily jobs, ledger
|
|
94
|
+
- Access: `references/permissions-scope.md` checks and scope; `references/auth-strategies.md`, `references/auth-better-auth.md`, `references/auth-better-auth-overlay.md`, `references/auth-api-keys.md`, `references/auth-permissions.md` auth setups; `references/multi-tenancy.md`, `references/tenancy-scope-install.md` tenants; `references/scim.md`, `references/agent-auth.md`, `references/enterprise-auth.md` enterprise auth
|
|
95
|
+
- Events: `references/events.md` bus, transports; `references/events-outbox.md` outbox; `references/integrations-jobs.md` BullMQ; `references/integrations-realtime.md` websocket; `references/integrations-webhooks.md`; `references/integrations-workflows.md`
|
|
96
|
+
- MCP: `references/mcp-setup.md`, `references/mcp-auth.md`, `references/mcp-custom-tools.md`, `references/mcp-testing.md`
|
|
97
|
+
- Ops: `references/production-boot.md` runtime, `references/production-distributed.md` stores table, `references/production-observability.md`, `references/production-shutdown.md`, `references/production-idempotency.md`, `references/production-audit.md`, `references/production-realtime.md`, `references/production-caching.md`, `references/production-api.md` versioning and rate limit, `references/production-reliability.md`, `references/usage-cleanup-capabilities.md` usage, tenant cleanup
|
|
98
|
+
- `references/testing.md` test app; `references/api-reference.md` subpath imports
|
|
99
|
+
- Skills: `arc-code-review` audit; `arc-module-publishing` ship a module
|