@shivaedev/platform 0.16.0 → 0.17.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.
@@ -1,6 +1,8 @@
1
- import { Context, type Effect } from "effect";
1
+ import { Context, type Effect, Layer } from "effect";
2
2
  import type { Rpc } from "effect/rpc";
3
3
  import type { makeLiveServer } from "@shivaedev/effect-contract/makeLiveServer.ts";
4
+ import type { AppHostFactory } from "#server/AppHostFactory.ts";
5
+ import type { AppHostInput, HostPreflight } from "#server/AppHostInput.ts";
4
6
  import { appHostHttp, deferredHost, migratedHost } from "#server/appHostHttp.ts";
5
7
  import { type DatabaseConfig, databaseLayer } from "#server/databaseLayer.ts";
6
8
  import type { HostOptions, HostPolicy } from "#server/hostOptions.ts";
@@ -27,11 +29,15 @@ export type AppHostOptions<
27
29
  TServiceRequirements = never,
28
30
  TMigrations = never,
29
31
  TSession extends SessionShape = SessionShape,
30
- > = HostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements> & {
31
- readonly migrations: AppDatabaseOptions<TMigrations>["migrations"];
32
- readonly policy?: undefined;
33
- readonly sessions: SessionPolicy<TSession>;
34
- };
32
+ TPreflight = never,
33
+ TPreflightError = never,
34
+ TPreflightRequirements = never,
35
+ > = HostPreflight<TPreflight, TPreflightError, TPreflightRequirements> &
36
+ HostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements> & {
37
+ readonly migrations: AppDatabaseOptions<TMigrations>["migrations"];
38
+ readonly policy?: undefined;
39
+ readonly sessions: SessionPolicy<TSession>;
40
+ };
35
41
 
36
42
  export type AppLocalHostOptions<
37
43
  TRpcs extends Rpc.Any,
@@ -42,11 +48,15 @@ export type AppLocalHostOptions<
42
48
  TServiceError = never,
43
49
  TServiceRequirements = never,
44
50
  TMigrations = never,
45
- > = HostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements> & {
46
- readonly migrations: AppDatabaseOptions<TMigrations>["migrations"];
47
- readonly policy: "loopback";
48
- readonly sessions?: never;
49
- };
51
+ TPreflight = never,
52
+ TPreflightError = never,
53
+ TPreflightRequirements = never,
54
+ > = HostPreflight<TPreflight, TPreflightError, TPreflightRequirements> &
55
+ HostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements> & {
56
+ readonly migrations: AppDatabaseOptions<TMigrations>["migrations"];
57
+ readonly policy: "loopback";
58
+ readonly sessions?: never;
59
+ };
50
60
 
51
61
  export type AppHttpHostOptions<
52
62
  TRpcs extends Rpc.Any,
@@ -57,10 +67,13 @@ export type AppHttpHostOptions<
57
67
  TServiceError = never,
58
68
  TServiceRequirements = never,
59
69
  TSession extends SessionShape = SessionShape,
60
- > = HostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements> &
70
+ TPreflight = never,
71
+ TPreflightError = never,
72
+ TPreflightRequirements = never,
73
+ > = HostPreflight<TPreflight, TPreflightError, TPreflightRequirements> &
74
+ HostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements> &
61
75
  HostPolicy<TSession> & { readonly migrations?: undefined };
62
-
63
- export function appHost<
76
+ export const appHost: AppHostFactory = <
64
77
  TRpcs extends Rpc.Any,
65
78
  THandlers,
66
79
  THandlerError,
@@ -72,19 +85,11 @@ export function appHost<
72
85
  TSession extends SessionShape = SessionShape,
73
86
  TApplicationError = never,
74
87
  TApplicationRequirements = never,
88
+ TPreflight = never,
89
+ TPreflightError = never,
90
+ TPreflightRequirements = never,
75
91
  >(
76
- options:
77
- | (AppDatabaseOptions<TMigrations> & {
78
- readonly application: Effect.Effect<
79
- AppHttpHostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements, TSession>,
80
- TApplicationError,
81
- TApplicationRequirements
82
- >;
83
- })
84
- | AppHostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements, TMigrations, TSession>
85
- | AppLocalHostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements, TMigrations>,
86
- ): ReturnType<
87
- typeof deferredHost<
92
+ options: AppHostInput<
88
93
  TRpcs,
89
94
  THandlers,
90
95
  THandlerError,
@@ -95,51 +100,18 @@ export function appHost<
95
100
  TMigrations,
96
101
  TSession,
97
102
  TApplicationError,
98
- TApplicationRequirements
99
- >
100
- >;
101
-
102
- export function appHost<
103
- TRpcs extends Rpc.Any,
104
- THandlers,
105
- THandlerError,
106
- THandlerRequirements,
107
- TServices = never,
108
- TServiceError = never,
109
- TServiceRequirements = never,
110
- TSession extends SessionShape = SessionShape,
111
- >(
112
- options: AppHttpHostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements, TSession>,
113
- ): ReturnType<typeof appHostHttp<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements, TSession>>;
114
- export function appHost<
115
- TRpcs extends Rpc.Any,
116
- THandlers,
117
- THandlerError,
118
- THandlerRequirements,
119
- TServices = never,
120
- TServiceError = never,
121
- TServiceRequirements = never,
122
- TMigrations = never,
123
- TSession extends SessionShape = SessionShape,
124
- TApplicationError = never,
125
- TApplicationRequirements = never,
126
- >(
127
- options:
128
- | (AppDatabaseOptions<TMigrations> & {
129
- readonly application: Effect.Effect<
130
- AppHttpHostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements, TSession>,
131
- TApplicationError,
132
- TApplicationRequirements
133
- >;
134
- })
135
- | AppHostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements, TMigrations, TSession>
136
- | AppLocalHostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements, TMigrations>
137
- | AppHttpHostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements, TSession>,
138
- ) {
103
+ TApplicationRequirements,
104
+ TPreflight,
105
+ TPreflightError,
106
+ TPreflightRequirements
107
+ >,
108
+ ) => {
139
109
  if ("application" in options) {
140
- return deferredHost(options.application, appDatabase(options));
110
+ return deferredHost(options.application, appDatabase(options)).pipe(Layer.provideMerge(options.preflight ?? Layer.empty));
141
111
  }
142
112
  return options.migrations === undefined
143
- ? appHostHttp(options)
144
- : migratedHost({ ...options, migrations: options.migrations }, appDatabase({ ...options, migrations: options.migrations }));
145
- }
113
+ ? appHostHttp(options).pipe(Layer.provideMerge(options.preflight ?? Layer.empty))
114
+ : migratedHost({ ...options, migrations: options.migrations }, appDatabase({ ...options, migrations: options.migrations })).pipe(
115
+ Layer.provideMerge(options.preflight ?? Layer.empty),
116
+ );
117
+ };
@@ -4,11 +4,12 @@ import { ByteSize, Config, Effect, Layer, Option, Schema } from "effect";
4
4
  import { HttpIncomingMessage, HttpRouter, HttpServerRequest, HttpStaticServer } from "effect/http";
5
5
  import { type Rpc, RpcSerialization, RpcServer } from "effect/rpc";
6
6
  import type { Authenticated, MaybeAuthenticated, RequestTracing } from "#rpc/middleware.ts";
7
- import type { AppHostOptions, AppHttpHostOptions, AppLocalHostOptions } from "#server/appHost.ts";
7
+ import type { AppHttpHostOptions } from "#server/appHost.ts";
8
8
  import { boundedRpcRequest } from "#server/boundedRpcRequest.ts";
9
9
  import type { databaseLayer } from "#server/databaseLayer.ts";
10
10
  import { healthRoute } from "#server/healthRoute.ts";
11
11
  import type { HostOptions, HostPolicy } from "#server/hostOptions.ts";
12
+ import type { MigrationOptions } from "#server/MigrationOptions.ts";
12
13
  import { otlpTracing } from "#server/otlpTracing.ts";
13
14
  import { localRpcGuard } from "#server/rpc-server/local.ts";
14
15
  import { authenticatedLayer, maybeAuthenticatedLayer, type SessionShape } from "#server/rpc-server/session.ts";
@@ -96,9 +97,8 @@ export function migratedHost<
96
97
  TMigrations,
97
98
  TSession extends SessionShape,
98
99
  >(
99
- options:
100
- | AppHostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements, TMigrations, TSession>
101
- | AppLocalHostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements, TMigrations>,
100
+ options: HostOptions<TRpcs, THandlers, THandlerError, THandlerRequirements, TServices, TServiceError, TServiceRequirements> &
101
+ HostPolicy<TSession> & { readonly migrations: MigrationOptions<TMigrations> },
102
102
  database: ReturnType<typeof databaseLayer<TMigrations>>,
103
103
  ) {
104
104
  const services = Layer.mergeAll(options.services ?? Layer.empty);
@@ -1,4 +1,4 @@
1
- import { Effect, Option } from "effect";
1
+ import { Effect, Option, Predicate } from "effect";
2
2
  import type { Headers } from "effect/http";
3
3
  import { AuthUnavailable } from "#errors/taxonomy.ts";
4
4
  import type { ProviderAccountValue } from "#rpc/identity.ts";
@@ -28,10 +28,18 @@ export function betterAuthSessions<TSession extends SessionShape>(getSession: Ge
28
28
  if (resolved === null || getProviderAccounts === undefined) {
29
29
  return resolved;
30
30
  }
31
- const accounts = await getProviderAccounts(transport);
31
+ const accounts = await getProviderAccounts(transport).catch((cause: unknown) => {
32
+ if (Predicate.hasProperty(cause, "statusCode") && cause.statusCode === 401) {
33
+ return null;
34
+ }
35
+ throw cause;
36
+ });
37
+ if (accounts === null) {
38
+ return null;
39
+ }
32
40
  return {
33
41
  ...resolved,
34
- user: { ...resolved.user, providerAccounts: accounts.map(({ accountId, providerId }) => ({ accountId, providerId })) },
42
+ user: { ...resolved.user, providerAccounts: accounts },
35
43
  };
36
44
  }).pipe(Effect.catch((error) => unavailable(error.cause)));
37
45
  return Option.fromNullishOr(session);
@@ -1,36 +0,0 @@
1
- # North star
2
-
3
- ## The problem
4
-
5
- A service can express its work clearly in Effect and still lose that clarity at its boundary. An HTTP request arrives with cookies and headers; native RPC supplies middleware arguments; an authentication provider returns a Promise; a database transaction replaces a service for one invocation; and a test must reach all of them together. Rebuilding that glue in each application gives the same concepts different names and leaves room for differences that matter: credentials taken from an RPC message, a shared Layer holding one user's identity, an outage mistaken for a missing session, or a Promise call escaping the test's transaction.
6
-
7
- Callers also need a common language for expected failures. A field rejection should arrive with its field and message, while a defect should remain a defect and diagnostics should not expose its credentials. Neither concern belongs in each feature's business logic.
8
-
9
- ## The ideal
10
-
11
- An application declares errors and native RPC middleware in modules its browser can import. The server supplies a session provider and an explicit Origin policy, and a handler reads a small request-local identity service. It then makes its own resource-authorization decision. The same request id identifies the invocation in its handler, logs and span.
12
-
13
- A Promise boundary uses the application's runtime and its invocation's services. A long-lived Node response has one cancellation signal and an explicit cleanup function. An application using Better Auth with Effect Prisma can store its auth rows through that runtime. An application using Prisma and tRPC can set up its test composition once and write feature tests against the caller and database in one rollback transaction.
14
-
15
- These are separate entry modules. The core request/error/runtime work should require Effect alone. Optional storage and test composition should load their own peers only when selected.
16
-
17
- ## Which trade-offs win
18
-
19
- 1. **Native Effect semantics.** Typed failures, invocation-local services, interruption and transaction scope matter more than a short integration example. A convenience must not hide a boundary that its caller needs to reason about.
20
- 2. **An explicit source of trust.** HTTP authentication and Origin decisions use transport headers, not values an RPC message can override. The request id is correlation data a caller may choose; it must not become an authorization credential. A provider outage must remain distinct from an anonymous caller.
21
- 3. **One owner for each job.** Platform supplies shared request services and the glue across boundaries. Native repositories belong to effect-sql, declarations to effect-contract, services to effect-service and generic test execution to effect-test. The optional adapters compose effect-prisma and effect-trpc rather than implementing them again.
22
- 4. **Useful evidence and diagnostics.** Describe the composition a test actually runs. A bounded redactor can reduce common credential leaks; it cannot decide every application's sensitive fields or justify putting secrets in messages. Keep application-specific data policy explicit.
23
- 5. **Small conveniences.** A provider function, a Layer and a defining-module import are preferable to a second configuration language or application container. Add a helper when it removes repeated work while leaving the native pieces visible.
24
-
25
- ## What the package deliberately leaves out
26
-
27
- - Authentication-provider selection, OAuth configuration, cookies, session lifetimes and client refresh policy.
28
- - Resource ownership and role checks. An authenticated user id is input to authorization, not permission to access every resource.
29
- - Application transports, CORS configuration, subscription limits, event buses and deployment policy.
30
- - A native SQL auth storage choice. Session resolution can use a provider without making its storage part of the application's repository model.
31
- - A second service container, RPC framework, persistence model or generic test runner.
32
- - Guarantees about SSR isolation, mobile cookie persistence or a particular Node/Bun host inferred from local fixtures.
33
-
34
- ## Where planning belongs
35
-
36
- [The package roadmap](roadmap.md) owns changes to these modules, their evidence and the maintainer's scope decisions. [The framework roadmap](https://github.com/ShivaeDev/platform/blob/main/docs/framework/roadmap.md) owns composed fixtures, application adoption and deployment validation across packages.
package/docs/roadmap.md DELETED
@@ -1,31 +0,0 @@
1
- # Roadmap
2
-
3
- This file owns Platform's module implementation, package tests and scope questions. The [framework roadmap](https://github.com/ShivaeDev/platform/blob/main/docs/framework/roadmap.md) owns cross-package fixtures, application adoption and browser, mobile and deployment validation.
4
-
5
- ## Built
6
-
7
- - [x] `localRpcGuard` rejects unknown or non-loopback transport addresses before calling the handler and accepts known IPv4, IPv6 and mapped loopback addresses. [Injected-request evidence](https://github.com/ShivaeDev/platform/blob/main/packages/platform/src/server/rpc-server/local.test.ts); this is separate from deployed host or proxy validation.
8
- - [x] `rpcBoundary` passes declared errors and successes through, normalizes unexpected failures and defects to a declared rejection with a redacted public message, retains the original cause off the wire, and preserves interruption, including mixed failure/cancellation causes. [Boundary evidence](https://github.com/ShivaeDev/platform/blob/main/packages/platform/src/server/rpc-server/boundary.test.ts).
9
- - [x] Shared Schema tagged errors and field-rejection extraction, with native RPC JSON and tRPC rejection tests.
10
- - [x] Browser-safe native RPC middleware declarations and request-id, identity and optional-identity services, with compile-time checks on guarded handlers.
11
- - [x] Request-local session middleware, a Better Auth session-provider boundary and an explicit Origin policy. Tests cover concurrent identities, anonymous callers, provider failures and rejection before provider lookup.
12
- - [x] HTTP transport-header authentication, direct tests of the RPC-header fallback and HTTP-header precedence, and a WebSocket protocol fixture that uses upgrade-request headers instead of RPC message credentials. [Header selection evidence](https://github.com/ShivaeDev/platform/blob/main/packages/platform/src/server/rpc-server/transportHeaders.test.ts).
13
- - [x] Request-id log/span annotations and redaction of failure payloads, defects, reported causes and credential-shaped strings, with bounded collection and string output. [Tracing tests](https://github.com/ShivaeDev/platform/blob/main/packages/platform/src/server/rpc-server/tracing.test.ts) cover successful requests and interruption without failure logs.
14
- - [x] An application runtime that acquires its Layer once, releases it exactly once, shares an explicit development cache key and recreates disposed cache entries, bypasses caching in production, and carries service overrides across Promise calls. [Runtime tests](https://github.com/ShivaeDev/platform/blob/main/packages/platform/src/server/runtime/makePlatform.test.ts) cover typed Layer build failures, Promise rejection, signal interruption with finalization, and nested override replacement and restoration.
15
- - [x] Node subscription cancellation from Web/procedure signals and simulated request/socket close events, with listener cleanup.
16
- - [x] A Better Auth Effect Prisma database adapter and Prisma/tRPC rollback harness. Real PostgreSQL tests cover shared transactions, failed transaction rollback, selected row operations and harness types; they require `PLATFORM_EFFECT_PRISMA_TEST_DATABASE_URL`.
17
- - [x] Better Auth adapter filters preserve PostgreSQL null, membership, comparison and literal-pattern semantics, including nonunique updates, OR-filter updates and deletes, and rejection of nonstring patterns. Configured model names map by default. Reads retain their filters through selection, ascending/descending ordering and limit/offset pagination; experimental native joins are rejected for both single and collection reads. [Adapter boundary tests](../src/server/better-auth/filterBoundaries.spec.ts) assert these paths against PostgreSQL.
18
- - [x] Packed-consumer checks for defining-module imports, types and core entries installed without optional peers.
19
- - [x] A local app host Layer and reusable database Layer, extracted from the PostgreSQL composition: migrations before services, guarded NDJSON RPC, session policy, static assets, scoped shutdown and commit-bound live delivery. The composed fixture covers two HTTP server processes and a worker. Fleet’s daemon adopts `appHost` and `appDatabase` with a custom RPC route, session-free loopback policy and its existing migration ledger. Platform’s real HTTP option tests cover hosting without a database, while Fleet’s PostgreSQL daemon tests cover pool limits, migration upgrades and existing clients.
20
-
21
- ## Next
22
-
23
- - [ ] Add focused adapter tests for the remaining public options, `debugLogs` and `usePlural`.
24
-
25
- ## Open questions
26
-
27
- - What comprehensive application redaction policy should cover span names, free text and custom attributes, and how should request/action correlation work across boundaries?
28
-
29
- - Should the package keep the optional Better Auth storage adapter and Prisma/tRPC harness beside its native request-context modules, or should those compositions live with the integration packages? Both serve real boundary work, but they give this package a wider surface than its request-identity job alone.
30
- - If an application needs Better Auth storage on native Effect SQL, should Platform own that adapter or should the provider retain separate storage? The request middleware needs a session provider, not a particular database.
31
- - The exports make Better Auth translation helpers importable beside the adapter. Are these helpers intended as supported consumer APIs, or should a future public API change narrow the surface to the adapter?