@shivaedev/test-kits 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1 - 2026-11-03
4
+
5
+ ### Changed
6
+
7
+ - Update `@shivaedev/identity` from 0.21.0 to 0.22.0.
8
+
9
+ ## 0.1.0 - 2026-11-03
10
+
11
+ ### Added
12
+
13
+ - Compose email inboxes, Better Auth session preconditions, PostgreSQL change assertions and native RPC subscription helpers in application story kits through domain-specific imports.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ShivaeDev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1 +1,40 @@
1
1
  # @shivaedev/test-kits
2
+
3
+ Reusable building blocks let application stories send real email requests, start signed in and observe committed changes without carrying test infrastructure in production dependencies.
4
+
5
+ ## Compose a story's preconditions
6
+
7
+ Keep the application's engine running and give its local story kit the preconditions and readouts it needs.
8
+
9
+ ```ts
10
+ import { signedInUser } from "@shivaedev/test-kits/identity/adapters/betterAuth.ts";
11
+
12
+ const alice = yield* signedInUser(auth, { email: "alice@example.test", name: "alice" });
13
+ const response = yield* client.get("/notes", { headers: alice.headers });
14
+ ```
15
+
16
+ The signed-in precondition mints a session; it does not exercise the application's sign-in flow. Keep sign-in stories at that flow's real boundary.
17
+
18
+ ## Use the building blocks
19
+
20
+ Compose these helpers in the application's `test-support` facade. Keep actions and observations there and assertions in the spec. Effect owns each helper's scope, clock and failures.
21
+
22
+ ### Email delivery
23
+
24
+ Import `inbox`, `emailLink` and the `ReceivedEmail` type from `@shivaedev/test-kits/email/adapters/inbox.ts`. Acquire `inbox()` in a scope and provide its `mailerLayer` to the real email worker. It routes the Resend SDK to a loopback HTTP provider. `nextEmail` waits for the next accepted message, `emails()` reads accepted messages and `endpoint` exposes provider controls. `emailLink(email)` extracts the first HTTP link from its text.
25
+
26
+ ### Signed-in identities
27
+
28
+ Import `signedInUser`, `signInAgain`, `passwordUser` and `storedProviderAccounts` from `@shivaedev/test-kits/identity/adapters/betterAuth.ts`. They use Better Auth's adapter without requiring its test plugin. `signedInUser(auth, fields)` returns the user, session, headers, cookies and token. Optional `providerAccounts` attach provider identities. `signInAgain(auth, userId)` renews the same user's session on the caller's Effect Clock. `passwordUser` accepts either `password` or `passwordHash`; use an existing hash when password hashing is only a precondition. `storedProviderAccounts` reports credential-presence booleans without returning credential values.
29
+
30
+ ### SQL change coverage
31
+
32
+ Import `withChangeCoverage`, `expectPublished`, `UnannouncedWrites`, `PublishedKeysMismatch` and the `ChangeCoverage` type from `@shivaedev/test-kits/sql/testing.ts`. `withChangeCoverage(body, { covers }?)` checks PostgreSQL write counters inside `transact` and rolls back writes without declared, recorded keys. `body.pipe(expectPublished(keys))` checks distinct published keys after the body; a mismatch cannot undo a completed commit. The [change guide](https://github.com/ShivaeDev/platform/blob/main/docs/framework/changes.md) explains declarations and publication boundaries. Compose these with [test-sql](https://github.com/ShivaeDev/platform/tree/main/packages/test-sql#readme) for PostgreSQL isolation.
33
+
34
+ ### Contract subscriptions
35
+
36
+ Import `watchHints`, `heard`, `layerMemoryProtocol` and the `HintViewer` type from `@shivaedev/test-kits/contract/testing.ts`. `watchHints(stream)` starts a scoped listener and waits for its first hint. `heard(viewer, keys, { within }?)` reports whether a delivered changed hint contains all requested keys, using a one-second Effect-clock deadline by default. `layerMemoryProtocol(group)` connects the native RPC client and server in-process; provide the real group's handlers and middleware.
37
+
38
+ ### Development setup
39
+
40
+ Install `@shivaedev/test-kits` as a development dependency alongside `effect`, Better Auth and the runtime packages used by the kit. The package depends on `@shivaedev/test-story` and `@shivaedev/test-sql`; runtime packages are peers. The [story-testing skill](https://github.com/ShivaeDev/platform/blob/main/packages/skills/skills/story-testing/SKILL.md) describes how to compose an application's facade and prove its behavior.
@@ -0,0 +1,17 @@
1
+ import { type Duration, Effect, Layer, Stream, SubscriptionRef } from "effect";
2
+ import { type Rpc, RpcClient, type RpcGroup, RpcSerialization, RpcServer } from "effect/rpc";
3
+ import type { Key } from "@shivaedev/changes/keys.ts";
4
+ import type { SubscriptionHint } from "@shivaedev/contract/queryUpdate.ts";
5
+ export interface HintViewer<E> {
6
+ readonly finished: Effect.Effect<void, E>;
7
+ readonly hints: SubscriptionRef.SubscriptionRef<readonly SubscriptionHint[]>;
8
+ }
9
+ export declare const watchHints: <E, R>(stream: Stream.Stream<SubscriptionHint, E, R>) => Effect.Effect<{
10
+ finished: Effect.Effect<void, E, never>;
11
+ hints: SubscriptionRef.SubscriptionRef<readonly SubscriptionHint[]>;
12
+ }, E, R | import("effect/Scope").Scope>;
13
+ export declare const heard: <E>(viewer: HintViewer<E>, keys: readonly Key[], options?: {
14
+ readonly within?: Duration.Input;
15
+ } | undefined) => Effect.Effect<boolean, E, never>;
16
+ export declare function layerMemoryProtocol<TRpcs extends Rpc.Any>(group: RpcGroup.RpcGroup<TRpcs>): Layer.Layer<RpcClient.Protocol, never, Exclude<Exclude<Exclude<Rpc.ServicesServer<TRpcs>, RpcServer.Protocol>, import("effect/Scope").Scope>, RpcSerialization.RpcSerialization> | Exclude<Exclude<Exclude<Rpc.ToHandler<TRpcs>, RpcServer.Protocol>, import("effect/Scope").Scope>, RpcSerialization.RpcSerialization>>;
17
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../../src/contract/testing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,EAAS,KAAK,EAAS,MAAM,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACvG,OAAO,EAAE,KAAK,GAAG,EAAE,SAAS,EAAE,KAAK,QAAQ,EAAmB,gBAAgB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC9G,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,4BAA4B,CAAC;AACtD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAE3E,MAAM,WAAW,UAAU,CAAC,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IAC1C,QAAQ,CAAC,KAAK,EAAE,eAAe,CAAC,eAAe,CAAC,SAAS,gBAAgB,EAAE,CAAC,CAAC;CAC7E;AAED,eAAO,MAAM,UAAU,GAA2C,CAAC,EAAE,CAAC;;;uCAYpE,CAAC;AAEH,eAAO,MAAM,KAAK,GAAsC,CAAC;sBAG3B,QAAQ,CAAC,KAAK;kDAU1C,CAAC;AAMH,wBAAgB,mBAAmB,CAAC,KAAK,SAAS,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,QAAQ,CAAC,QAAQ,CAAC,KAAK,CAAC,4TAqCzF"}
@@ -0,0 +1,51 @@
1
+ import { Deferred, Effect, Fiber, Layer, Queue, Stream, SubscriptionRef } from "effect";
2
+ import { RpcClient, RpcSerialization, RpcServer } from "effect/rpc";
3
+ export const watchHints = Effect.fn("Live.watchHints")(function* (stream) {
4
+ const hints = yield* SubscriptionRef.make([]);
5
+ const ready = yield* Deferred.make();
6
+ const fiber = yield* stream.pipe(Stream.runForEach((hint) => SubscriptionRef.update(hints, (received) => [...received, hint]).pipe(Effect.andThen(Deferred.succeed(ready, undefined)))), Effect.forkScoped);
7
+ const finished = Fiber.join(fiber);
8
+ yield* Effect.raceFirst(Deferred.await(ready), finished);
9
+ return { finished, hints };
10
+ });
11
+ export const heard = Effect.fn("Live.heard")(function* (viewer, keys, options = {}) {
12
+ const matching = SubscriptionRef.changes(viewer.hints).pipe(Stream.filter((hints) => hints.some((hint) => namesKeys(hint, keys))), Stream.runHead, Effect.as(true));
13
+ return yield* Effect.raceFirst(matching, Effect.as(viewer.finished, false)).pipe(Effect.timeoutOrElse({ duration: options.within ?? "1 second", orElse: () => Effect.succeed(false) }));
14
+ });
15
+ function namesKeys(hint, keys) {
16
+ return hint._tag === "Changed" && keys.every((key) => hint.keys.some((actual) => JSON.stringify(actual) === JSON.stringify(key)));
17
+ }
18
+ export function layerMemoryProtocol(group) {
19
+ return Layer.effect(RpcClient.Protocol, Effect.gen(function* () {
20
+ const requests = yield* Queue.unbounded();
21
+ const disconnects = yield* Queue.unbounded();
22
+ const { codecFor } = yield* RpcSerialization.RpcSerialization;
23
+ const protocol = yield* RpcClient.Protocol.make((send, clientIds) => Effect.gen(function* () {
24
+ const server = RpcServer.Protocol.of({
25
+ clientIds: Effect.sync(() => clientIds),
26
+ codecFor,
27
+ disconnects,
28
+ end: () => Effect.void,
29
+ initialMessage: Effect.succeedNone,
30
+ run: (receive) => Effect.forever(Effect.flatMap(Queue.take(requests), ([id, message]) => receive(id, message))),
31
+ send,
32
+ supportsAck: true,
33
+ supportsNotifications: true,
34
+ supportsSpanPropagation: true,
35
+ supportsTransferables: false,
36
+ });
37
+ yield* RpcServer.make(group).pipe(Effect.provideService(RpcServer.Protocol, server), Effect.forkScoped);
38
+ return {
39
+ codecFor,
40
+ send: (clientId, request) => Queue.offer(requests, [clientId, request]).pipe(Effect.asVoid),
41
+ supportsAck: true,
42
+ supportsTransferables: false,
43
+ };
44
+ }));
45
+ return {
46
+ ...protocol,
47
+ run: (clientId, receive) => protocol.run(clientId, receive).pipe(Effect.ensuring(Queue.offer(disconnects, clientId))),
48
+ };
49
+ })).pipe(Layer.provide(RpcSerialization.layerNdjson));
50
+ }
51
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","sourceRoot":"","sources":["../../src/contract/testing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAiB,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACvG,OAAO,EAAY,SAAS,EAAkC,gBAAgB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAS9G,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,EAAE,CAAC,iBAAiB,CAAC,CAAC,QAAQ,CAAC,EAAQ,MAA6C;IACpH,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,eAAe,CAAC,IAAI,CAA8B,EAAE,CAAC,CAAC;IAC3E,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAQ,CAAC;IAC3C,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAC/B,MAAM,CAAC,UAAU,CAAC,CAAC,IAAI,EAAE,EAAE,CAC1B,eAAe,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,GAAG,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,EA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,CAAC,CAAC,CAAC;gBAC/G,IAAI;gBACJ,WAAW,EAAE,IAAI;gBACjB,qBAAqB,EAAE,IAAI;gBAC3B,uBAAuB,EAAE,IAAI;gBAC7B,qBAAqB,EAAE,KAAK;aAC5B,CAAC,CAAC;YACH,KAAK,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,SAAS,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;YACxG,OAAO;gBACN,QAAQ;gBACR,IAAI,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;gBAC3F,WAAW,EAAE,IAAI;gBACjB,qBAAqB,EAAE,KAAK;aAC5B,CAAC;QACH,CAAC,CAAC,CACF,CAAC;QACF,OAAO;YACN,GAAG,QAAQ;YACX,GAAG,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC;SAC7E,CAAC;IAC3C,CAAC,CAAC,CACF,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC,CAAC;AACrD,CAAC"}
@@ -0,0 +1,31 @@
1
+ import { Effect } from "effect";
2
+ import { Email } from "@shivaedev/email/Email.ts";
3
+ export interface ReceivedEmail extends Email {
4
+ readonly idempotencyKey: string | undefined;
5
+ }
6
+ export declare const inbox: () => Effect.Effect<{
7
+ emails: () => Effect.Effect<ReceivedEmail[], never, never>;
8
+ endpoint: {
9
+ completed: import("effect/Stream").Stream<import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpRequestRecord, never, never>;
10
+ fault: (route: string, fault: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpFault, scope?: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpScope) => Effect.Effect<void, never, never>;
11
+ hold: (route: string, holdOptions?: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpHoldOptions) => Effect.Effect<{
12
+ release: Effect.Effect<void, never, never>;
13
+ waiting: Effect.Effect<void, never, never>;
14
+ }, never, never>;
15
+ narrate: (sink: (line: string) => void) => void;
16
+ received: import("effect/Stream").Stream<import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpRequestRecord, never, never>;
17
+ releaseOnArrival: (route: string, arrival: string, scope?: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpScope) => Effect.Effect<void, never, never>;
18
+ readonly requests: readonly import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpRequestRecord[];
19
+ scriptFault: (route: string, fault: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpFault, scriptOptions?: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpScriptOptions) => Effect.Effect<import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpScript, never, never>;
20
+ stall: (route: string, scope?: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpScope) => Effect.Effect<{
21
+ release: Effect.Effect<void, never, never>;
22
+ waiting: Effect.Effect<void, never, never>;
23
+ }, never, never>;
24
+ untilAbandoned: (matches: (request: import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpRequestRecord) => boolean, wait: import("@shivaedev/test-story/server/until.ts").UntilOptions) => Effect.Effect<import("@shivaedev/test-story/server/fakeHttpService.ts").FakeHttpRequestRecord, import("@shivaedev/test-story/server/until.ts").SignalNotReceived, never>;
25
+ url: string;
26
+ };
27
+ mailerLayer: import("effect/Layer").Layer<"@shivaedev/email/Mailer", import("effect/Config").ConfigError, never>;
28
+ nextEmail: Effect.Effect<ReceivedEmail, import("effect/Cause").TimeoutError, never>;
29
+ }, import("effect/Cause").UnknownError, import("effect/Scope").Scope>;
30
+ export declare function emailLink(email: Email): string;
31
+ //# sourceMappingURL=inbox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inbox.d.ts","sourceRoot":"","sources":["../../../src/email/adapters/inbox.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAA2B,MAAM,QAAQ,CAAC;AACzD,OAAO,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAC;AAKlD,MAAM,WAAW,aAAc,SAAQ,KAAK;IAC3C,QAAQ,CAAC,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;CAC5C;AAED,eAAO,MAAM,KAAK;;;;;;;;;;;;;;;;;;;;;;;qEAyBhB,CAAC;AAEH,wBAAgB,SAAS,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,CAM9C"}
@@ -0,0 +1,39 @@
1
+ import { Effect, Queue, Redacted, Schema } from "effect";
2
+ import { Email } from "@shivaedev/email/Email.ts";
3
+ import { resendMailerLayer } from "@shivaedev/email/server/adapters/resendMailerLayer.ts";
4
+ import { fakeHttpService } from "@shivaedev/test-story/server/fakeHttpService.ts";
5
+ import { routeOutbound } from "@shivaedev/test-story/server/routeOutbound.ts";
6
+ export const inbox = Effect.fnUntraced(function* () {
7
+ const arrivals = yield* Queue.unbounded();
8
+ const emails = [];
9
+ const decode = Schema.decodeUnknownSync(Schema.fromJsonString(Email));
10
+ const endpoint = yield* fakeHttpService({
11
+ routes: {
12
+ send: {
13
+ method: "POST",
14
+ path: "/emails",
15
+ reply: (request) => {
16
+ const email = { ...decode(request.body.toString()), idempotencyKey: request.headers["idempotency-key"]?.toString() };
17
+ emails.push(email);
18
+ Queue.offerUnsafe(arrivals, email);
19
+ return { body: { id: `email-${emails.length}` } };
20
+ },
21
+ },
22
+ },
23
+ });
24
+ yield* routeOutbound({ "api.resend.com": endpoint.url });
25
+ return {
26
+ emails: () => Effect.sync(() => [...emails]),
27
+ endpoint,
28
+ mailerLayer: resendMailerLayer({ apiKey: Redacted.make("re_story") }),
29
+ nextEmail: Queue.take(arrivals).pipe(Effect.timeout("10 seconds")),
30
+ };
31
+ });
32
+ export function emailLink(email) {
33
+ const link = email.text.match(/https?:\/\/[^\s<>]+/u)?.[0];
34
+ if (link === undefined) {
35
+ throw new Error("The delivered email has no link in its text");
36
+ }
37
+ return link;
38
+ }
39
+ //# sourceMappingURL=inbox.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inbox.js","sourceRoot":"","sources":["../../../src/email/adapters/inbox.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACzD,OAAO,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uDAAuD,CAAC;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,iDAAiD,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,+CAA+C,CAAC;AAM9E,MAAM,CAAC,MAAM,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC;IAC/C,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,SAAS,EAAiB,CAAC;IACzD,MAAM,MAAM,GAAoB,EAAE,CAAC;IACnC,MAAM,MAAM,GAAG,MAAM,CAAC,iBAAiB,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC;IACtE,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,eAAe,CAAC;QACvC,MAAM,EAAE;YACP,IAAI,EAAE;gBACL,MAAM,EAAE,MAAM;gBACd,IAAI,EAAE,SAAS;gBACf,KAAK,EAAE,CAAC,OAAO,EAAE,EAAE;oBAClB,MAAM,KAAK,GAAG,EAAE,GAAG,MAAM,CAAC,OAAO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;
4
+ type SessionContext = AccountContext & Pick<AuthContext, "sessionConfig" | "secret" | "authCookies" | "baseURL">;
5
+ export declare const signedInUser: (auth: {
6
+ readonly $context: Promise<SessionContext>;
7
+ }, args_1: Partial<{
8
+ id: string;
9
+ createdAt: Date;
10
+ updatedAt: Date;
11
+ email: string;
12
+ emailVerified: boolean;
13
+ name: string;
14
+ image?: string | null | undefined;
15
+ }> & Record<string, unknown> & {
16
+ readonly providerAccounts?: readonly {
17
+ readonly providerId: string;
18
+ readonly accountId: string;
19
+ }[];
20
+ }) => Effect.Effect<import("better-auth/plugins").LoginResult, never, never>;
21
+ export declare const signInAgain: (auth: {
22
+ readonly $context: Promise<SessionContext>;
23
+ }, userId: string) => Effect.Effect<import("better-auth/plugins").LoginResult, never, never>;
24
+ export declare function storedProviderAccounts(auth: {
25
+ readonly $context: Promise<AccountContext>;
26
+ }, userId: string): Promise<{
27
+ accountId: string;
28
+ hasAccessToken: boolean;
29
+ hasIdToken: boolean;
30
+ hasPassword: boolean;
31
+ hasRefreshToken: boolean;
32
+ providerId: string;
33
+ }[]>;
34
+ export declare const passwordUser: (auth: {
35
+ readonly $context: Promise<AccountContext & {
36
+ readonly password: Pick<AuthContext["password"], "hash">;
37
+ }>;
38
+ }, args_1: Partial<{
39
+ id: string;
40
+ createdAt: Date;
41
+ updatedAt: Date;
42
+ email: string;
43
+ emailVerified: boolean;
44
+ name: string;
45
+ image?: string | null | undefined;
46
+ }> & Record<string, unknown> & ({
47
+ readonly email: string;
48
+ } & ({
49
+ readonly password: string;
50
+ readonly passwordHash?: never;
51
+ } | {
52
+ readonly passwordHash: string;
53
+ readonly password?: never;
54
+ }))) => Effect.Effect<Record<string, any> & {
55
+ id: string;
56
+ createdAt: Date;
57
+ updatedAt: Date;
58
+ email: string;
59
+ emailVerified: boolean;
60
+ name: string;
61
+ image?: string | null | undefined;
62
+ }, never, never>;
63
+ export {};
64
+ //# sourceMappingURL=betterAuth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"betterAuth.d.ts","sourceRoot":"","sources":["../../../src/identity/adapters/betterAuth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,EAAS,MAAM,EAAE,MAAM,QAAQ,CAAC;AAMvC,KAAK,cAAc,GAAG,IAAI,CAAC,WAAW,EAAE,iBAAiB,CAAC,CAAC;AAC3D,KAAK,cAAc,GAAG,cAAc,GAAG,IAAI,CAAC,WAAW,EAAE,eAAe,GAAG,QAAQ,GAAG,aAAa,GAAG,SAAS,CAAC,CAAC;AAqBjH,eAAO,MAAM,YAAY;uBACG,OAAO,CAAC,cAAc,CAAC;;;;;;;;;;gCAKrB,SAAS;QAAE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;KAAE,EAAE;4EASlG,CAAC;AAEH,eAAO,MAAM,WAAW;uBACI,OAAO,CAAC,cAAc,CAAC;4FA2BjD,CAAC;AAEH,wBAAsB,sBAAsB,CAAC,IAAI,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;CAAE,EAAE,MAAM,EAAE,MAAM;;;;;;;KAWhH;AAED,eAAO,MAAM,YAAY;uBACG,OAAO,CAAC,cAAc,GAAG;QAAE,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;;;;;;;;;;oBAK/E,MAAM;;uBACf,MAAM;4BAA0B,KAAK;;2BACjC,MAAM;wBAAsB,KAAK;;;;;;;;;gBAU7D,CAAC"}
@@ -0,0 +1,69 @@
1
+ import { Clock, Effect } from "effect";
2
+ import { signedSessionToken, testUserEmail } from "./testingCredentials.js";
3
+ function saveUser(context, fields) {
4
+ return Effect.flatMap(testUserEmail, (email) => Effect.promise(() => context.internalAdapter.createUser({ email, emailVerified: true, image: null, name: "Test User", ...fields }, { method: "test" })));
5
+ }
6
+ function cookieSameSite(value) {
7
+ switch (value?.toLowerCase()) {
8
+ case "strict":
9
+ return "Strict";
10
+ case "none":
11
+ return "None";
12
+ default:
13
+ return "Lax";
14
+ }
15
+ }
16
+ export const signedInUser = Effect.fnUntraced(function* (auth, { providerAccounts = [], ...fields }) {
17
+ const context = yield* Effect.promise(() => auth.$context);
18
+ const user = yield* saveUser(context, fields);
19
+ for (const { providerId, accountId } of providerAccounts) {
20
+ yield* Effect.promise(() => context.internalAdapter.createAccount({ accountId, providerId, userId: user.id }));
21
+ }
22
+ return yield* signInAgain(auth, user.id);
23
+ });
24
+ export const signInAgain = Effect.fnUntraced(function* (auth, userId) {
25
+ const { internalAdapter, sessionConfig, authCookies, secret, baseURL } = yield* Effect.promise(() => auth.$context);
26
+ const now = yield* Clock.currentTimeMillis;
27
+ const session = yield* Effect.promise(() => internalAdapter.createSession(userId, false, {}, true));
28
+ const expiresAt = new Date(now + sessionConfig.expiresIn * 1000);
29
+ yield* Effect.promise(() => internalAdapter.updateSession(session.token, { expiresAt }));
30
+ const user = yield* Effect.promise(() => internalAdapter.findUserById(userId));
31
+ if (user === null) {
32
+ return yield* Effect.die(`User not found: ${userId}`);
33
+ }
34
+ const value = yield* signedSessionToken(session.token, secret);
35
+ const { name, attributes } = authCookies.sessionToken;
36
+ const cookies = [
37
+ {
38
+ domain: URL.canParse(baseURL) ? new URL(baseURL).hostname : "localhost",
39
+ httpOnly: attributes.httpOnly ?? true,
40
+ name,
41
+ path: attributes.path || "/",
42
+ sameSite: cookieSameSite(attributes.sameSite),
43
+ secure: attributes.secure ?? false,
44
+ value,
45
+ ...(attributes.maxAge ? { expires: Math.floor(now / 1000) + attributes.maxAge } : {}),
46
+ },
47
+ ];
48
+ return { cookies, headers: new Headers({ cookie: `${name}=${value}` }), session: { ...session, expiresAt }, token: session.token, user };
49
+ });
50
+ export async function storedProviderAccounts(auth, userId) {
51
+ const { internalAdapter } = await auth.$context;
52
+ const accounts = await internalAdapter.findAccounts(userId);
53
+ return accounts.map(({ providerId, accountId, accessToken, refreshToken, idToken, password }) => ({
54
+ accountId,
55
+ hasAccessToken: Boolean(accessToken),
56
+ hasIdToken: Boolean(idToken),
57
+ hasPassword: Boolean(password),
58
+ hasRefreshToken: Boolean(refreshToken),
59
+ providerId,
60
+ }));
61
+ }
62
+ export const passwordUser = Effect.fnUntraced(function* (auth, { password, passwordHash, ...fields }) {
63
+ const context = yield* Effect.promise(() => auth.$context);
64
+ const user = yield* saveUser(context, fields);
65
+ const hash = passwordHash ?? (yield* Effect.promise(() => context.password.hash(password)));
66
+ yield* Effect.promise(() => context.internalAdapter.createAccount({ accountId: user.id, password: hash, providerId: "credential", userId: user.id }));
67
+ return user;
68
+ });
69
+ //# sourceMappingURL=betterAuth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"betterAuth.js","sourceRoot":"","sources":["../../../src/identity/adapters/betterAuth.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAQ5E,SAAS,QAAQ,CAAC,OAAuB,EAAE,MAAkB;IAC5D,OAAO,MAAM,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,KAAK,EAAE,EAAE,CAC9C,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CACnB,OAAO,CAAC,eAAe,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CACjI,CACD,CAAC;AACH,CAAC;AAED,SAAS,cAAc,CAAC,KAAyB;IAChD,QAAQ,KAAK,EAAE,WAAW,EAAE,EAAE,CAAC;QAC9B,KAAK,QAAQ;YACZ,OAAO,QAAQ,CA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AAQ,CAAC,CAAC;IAC3D,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAC9C,MAAM,IAAI,GAAG,YAAY,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC5F,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAC1B,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CACxH,CAAC;IACF,OAAO,IAAI,CAAC;AACb,CAAC,CAAC,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { Effect } from "effect";
2
+ export declare const testUserEmail: Effect.Effect<string, never, never>;
3
+ export declare const signedSessionToken: (token: string, secret: string) => Effect.Effect<string, never, never>;
4
+ //# sourceMappingURL=testingCredentials.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testingCredentials.d.ts","sourceRoot":"","sources":["../../../src/identity/adapters/testingCredentials.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,eAAO,MAAM,aAAa,qCAAmE,CAAC;AAE9F,eAAO,MAAM,kBAAkB,wEAG7B,CAAC"}
@@ -0,0 +1,8 @@
1
+ import { generateRandomString, makeSignature } from "better-auth/crypto";
2
+ import { Effect } from "effect";
3
+ export const testUserEmail = Effect.sync(() => `test-${generateRandomString(8)}@example.com`);
4
+ export const signedSessionToken = Effect.fnUntraced(function* (token, secret) {
5
+ const signature = yield* Effect.promise(() => makeSignature(token, secret));
6
+ return `${token}.${signature}`;
7
+ });
8
+ //# sourceMappingURL=testingCredentials.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testingCredentials.js","sourceRoot":"","sources":["../../../src/identity/adapters/testingCredentials.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACzE,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,oBAAoB,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC;AAE9F,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,KAAa,EAAE,MAAc;IAC3F,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;IAC5E,OAAO,GAAG,KAAK,IAAI,SAAS,EAAE,CAAC;AAChC,CAAC,CAAC,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+ import { type BucketKey, type ItemKey } from "@shivaedev/changes/keys.ts";
4
+ declare const UnannouncedWrites_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
5
+ readonly _tag: "UnannouncedWrites";
6
+ } & Readonly<A>;
7
+ export declare class UnannouncedWrites extends UnannouncedWrites_base<{
8
+ readonly tables: readonly string[];
9
+ }> {
10
+ }
11
+ export interface ChangeCoverage {
12
+ readonly covers: Readonly<Record<string, readonly (ItemKey | BucketKey)[]>>;
13
+ }
14
+ export declare const withChangeCoverage: <A, E, R>(body: Effect.Effect<A, E, R>, options?: ChangeCoverage | undefined) => Effect.Effect<A, Schema.SchemaError | import("effect/sql/SqlError").SqlError | UnannouncedWrites | Exclude<E, import("effect/sql/SqlError").SqlError>, import("effect/reactivity/Reactivity").Reactivity | SqlClient.SqlClient | Exclude<Exclude<R, never>, never>>;
15
+ declare const PublishedKeysMismatch_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
16
+ readonly _tag: "PublishedKeysMismatch";
17
+ } & Readonly<A>;
18
+ export declare class PublishedKeysMismatch extends PublishedKeysMismatch_base<{
19
+ readonly expected: readonly unknown[];
20
+ readonly actual: readonly unknown[];
21
+ }> {
22
+ get message(): string;
23
+ }
24
+ export declare function expectPublished(keys: readonly unknown[]): <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E | PublishedKeysMismatch, R>;
25
+ export declare function expectPublished<A>(keys: (result: A) => readonly unknown[]): <E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E | PublishedKeysMismatch, R>;
26
+ export {};
27
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../../src/sql/testing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK,OAAO,EAAoB,MAAM,4BAA4B,CAAC;;;;AAI5F,qBAAa,iBAAkB,SAAQ,uBAAsC;IAAE,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CAAC;CAAG;AAEvH,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,OAAO,GAAG,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC;CAC5E;AAED,eAAO,MAAM,kBAAkB,GAAsD,CAAC,EAAE,CAAC,EAAE,CAAC,4UAuD1F,CAAC;;;;AAEH,qBAAa,qBAAsB,SAAQ,2BAA0C;IACpF,QAAQ,CAAC,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;IACtC,QAAQ,CAAC,MAAM,EAAE,SAAS,OAAO,EAAE,CAAC;CACpC,CAAC;IACD,IAAa,OAAO,WAEnB;CACD;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,SAAS,OAAO,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,KAAK,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,GAAG,qBAAqB,EAAE,CAAC,CAAC,CAAC;AACrJ,wBAAgB,eAAe,CAAC,CAAC,EAChC,IAAI,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,SAAS,OAAO,EAAE,GACrC,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,KAAK,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,GAAG,qBAAqB,EAAE,CAAC,CAAC,CAAC"}
@@ -0,0 +1,75 @@
1
+ import { Data, Effect, Schema } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+ import { invalidationKeys } from "@shivaedev/changes/keys.ts";
4
+ import { ChangeDeclarations } from "@shivaedev/sql/ChangeDeclarations.ts";
5
+ import { ChangeObserver, transact } from "@shivaedev/sql/transact.ts";
6
+ export class UnannouncedWrites extends Data.TaggedError("UnannouncedWrites") {
7
+ }
8
+ export const withChangeCoverage = Effect.fn("Changes.withChangeCoverage")(function* (body, options) {
9
+ const observer = yield* ChangeObserver;
10
+ const sql = yield* SqlClient.SqlClient;
11
+ const named = new Set();
12
+ const declarations = new Map();
13
+ const outer = yield* ChangeDeclarations;
14
+ const written = sql `select relid, relname, (n_tup_ins + n_tup_upd + n_tup_del)::int as writes from pg_stat_xact_user_tables`.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Schema.Struct({ relid: Schema.Int, relname: Schema.String, writes: Schema.Int })))));
15
+ const checked = Effect.gen(function* () {
16
+ const before = new Map((yield* written).map((row) => [row.relid, row.writes]));
17
+ const result = yield* body;
18
+ const missing = (yield* written).filter((row) => {
19
+ const count = row.writes - (before.get(row.relid) ?? 0);
20
+ if (count <= 0) {
21
+ return false;
22
+ }
23
+ const automatic = declarations.get(row.relname);
24
+ const explicit = options?.covers[row.relname] ?? [];
25
+ const expected = [...(automatic?.keys ?? []), ...invalidationKeys(explicit)];
26
+ return (count > (automatic?.rows ?? 0) && explicit.length === 0) || expected.some((key) => !named.has(key));
27
+ });
28
+ if (missing.length > 0) {
29
+ return yield* Effect.fail(new UnannouncedWrites({ tables: missing.map((row) => row.relname).sort() }));
30
+ }
31
+ return result;
32
+ });
33
+ return yield* checked.pipe(transact({ onSqlError: (error) => error }), Effect.provideService(ChangeDeclarations, {
34
+ declare: (table, keys, rows) => Effect.andThen(Effect.sync(() => {
35
+ const entry = declarations.get(table) ?? { keys: new Set(), rows: 0 };
36
+ for (const key of keys) {
37
+ entry.keys.add(key);
38
+ }
39
+ entry.rows += rows;
40
+ declarations.set(table, entry);
41
+ }), outer.declare(table, keys, rows)),
42
+ }), Effect.provideService(ChangeObserver, (event) => {
43
+ if (event._tag === "Recorded") {
44
+ for (const key of event.changes) {
45
+ named.add(key);
46
+ }
47
+ }
48
+ return observer(event);
49
+ }));
50
+ });
51
+ export class PublishedKeysMismatch extends Data.TaggedError("PublishedKeysMismatch") {
52
+ get message() {
53
+ return `Expected published keys ${JSON.stringify(this.expected)}; actual published keys ${JSON.stringify(this.actual)}`;
54
+ }
55
+ }
56
+ export function expectPublished(keys) {
57
+ return Effect.fn("Changes.expectPublished")(function* (body) {
58
+ const observer = yield* ChangeObserver;
59
+ const actual = new Set();
60
+ const result = yield* body.pipe(Effect.provideService(ChangeObserver, (event) => {
61
+ if (event._tag === "Published") {
62
+ for (const key of event.changes) {
63
+ actual.add(key);
64
+ }
65
+ }
66
+ return observer(event);
67
+ }));
68
+ const expected = new Set(typeof keys === "function" ? keys(result) : keys);
69
+ if (actual.size !== expected.size || [...expected].some((key) => !actual.has(key))) {
70
+ return yield* Effect.fail(new PublishedKeysMismatch({ actual: [...actual], expected: [...expected] }));
71
+ }
72
+ return result;
73
+ });
74
+ }
75
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","sourceRoot":"","sources":["../../src/sql/testing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAgC,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC5F,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAEtE,MAAM,OAAO,iBAAkB,SAAQ,IAAI,CAAC,WAAW,CAAC,mBAAmB,CAAyC;CAAG;AAMvH,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAC,EAAE,CAAC,4BAA4B,CAAC,CAAC,QAAQ,CAAC,EAClF,IAA4B,EAC5B,OAAwB;IAExB,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,cAAc,CAAC;IACvC,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,SAAS,CAAC,SAAS,CAAC;IACvC,MAAM,KAAK,GAAG,IAAI,GAAG,EAAW,CAAC;IACjC,MAAM,YAAY,GAAG,IAAI,GAAG,EAA+C,CAAC;IAC5E,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,kBAAkB,CAAC;IACxC,MAAM,OAAO,GAAG,GAAG,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ACD,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;QACxB,CAAC,CAAC,CACF,CAAC;QACF,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,OAAO,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QAC3E,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;YACpF,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,qBAAqB,CAAC,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAAC,EAAE,QAAQ,EAAE,CAAC,GAAG,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,MAAM,CAAC;IACf,CAAC,CAAC,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,11 +1,78 @@
1
1
  {
2
2
  "name": "@shivaedev/test-kits",
3
- "version": "0.0.0",
4
- "description": "Placeholder for @shivaedev/test-kits.",
5
- "license": "MIT",
3
+ "version": "0.1.1",
4
+ "description": "Reusable story building blocks for Platform applications",
5
+ "keywords": [
6
+ "effect"
7
+ ],
8
+ "homepage": "https://github.com/ShivaeDev/platform/tree/main/packages/test-kits#readme",
9
+ "bugs": {
10
+ "url": "https://github.com/ShivaeDev/platform/issues"
11
+ },
6
12
  "repository": {
7
13
  "type": "git",
8
14
  "url": "git+https://github.com/ShivaeDev/platform.git",
9
15
  "directory": "packages/test-kits"
16
+ },
17
+ "license": "MIT",
18
+ "sideEffects": false,
19
+ "type": "module",
20
+ "imports": {
21
+ "#test/*": "./src/test-support/*",
22
+ "#*.ts": {
23
+ "source": "./src/*.ts",
24
+ "types": "./dist/*.d.ts",
25
+ "default": "./dist/*.js"
26
+ }
27
+ },
28
+ "exports": {
29
+ "./*.ts": {
30
+ "source": "./src/*.ts",
31
+ "types": "./dist/*.d.ts",
32
+ "default": "./dist/*.js"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "src",
39
+ "!src/**/*.test.ts",
40
+ "!src/**/*.spec.ts",
41
+ "!src/**/test-support",
42
+ "CHANGELOG.md",
43
+ "README.md"
44
+ ],
45
+ "dependencies": {
46
+ "@shivaedev/test-sql": "0.18.0",
47
+ "@shivaedev/test-story": "0.36.0"
48
+ },
49
+ "devDependencies": {
50
+ "@shivaedev/quality": "0.57.1",
51
+ "@types/node": "24.19.2",
52
+ "better-auth": "1.7.14",
53
+ "effect": "4.0.6",
54
+ "typescript": "7.0.2",
55
+ "vitest": "5.0.5"
56
+ },
57
+ "peerDependencies": {
58
+ "@shivaedev/changes": "0.9.0",
59
+ "@shivaedev/contract": "0.33.0",
60
+ "@shivaedev/email": "0.3.0",
61
+ "@shivaedev/identity": "0.22.0",
62
+ "@shivaedev/sql": "0.35.0",
63
+ "better-auth": "1.7.14",
64
+ "effect": "4.0.6"
65
+ },
66
+ "engines": {
67
+ "node": ">=24"
68
+ },
69
+ "publishConfig": {
70
+ "access": "public",
71
+ "provenance": true
72
+ },
73
+ "scripts": {
74
+ "build": "node --eval \"import('node:fs').then(({ rmSync }) => rmSync('dist', { force: true, recursive: true }))\" && tsc --project tsconfig.build.json",
75
+ "ready": "pnpm typecheck && pnpm build",
76
+ "typecheck": "tsc --noEmit"
10
77
  }
11
78
  }
@@ -0,0 +1,81 @@
1
+ import { Deferred, type Duration, Effect, Fiber, Layer, Queue, Stream, SubscriptionRef } from "effect";
2
+ import { type Rpc, RpcClient, type RpcGroup, type RpcMessage, RpcSerialization, RpcServer } from "effect/rpc";
3
+ import type { Key } from "@shivaedev/changes/keys.ts";
4
+ import type { SubscriptionHint } from "@shivaedev/contract/queryUpdate.ts";
5
+
6
+ export interface HintViewer<E> {
7
+ readonly finished: Effect.Effect<void, E>;
8
+ readonly hints: SubscriptionRef.SubscriptionRef<readonly SubscriptionHint[]>;
9
+ }
10
+
11
+ export const watchHints = Effect.fn("Live.watchHints")(function* <E, R>(stream: Stream.Stream<SubscriptionHint, E, R>) {
12
+ const hints = yield* SubscriptionRef.make<readonly SubscriptionHint[]>([]);
13
+ const ready = yield* Deferred.make<void>();
14
+ const fiber = yield* stream.pipe(
15
+ Stream.runForEach((hint) =>
16
+ SubscriptionRef.update(hints, (received) => [...received, hint]).pipe(Effect.andThen(Deferred.succeed(ready, undefined))),
17
+ ),
18
+ Effect.forkScoped,
19
+ );
20
+ const finished = Fiber.join(fiber);
21
+ yield* Effect.raceFirst(Deferred.await(ready), finished);
22
+ return { finished, hints } satisfies HintViewer<E>;
23
+ });
24
+
25
+ export const heard = Effect.fn("Live.heard")(function* <E>(
26
+ viewer: HintViewer<E>,
27
+ keys: readonly Key[],
28
+ options: { readonly within?: Duration.Input } = {},
29
+ ) {
30
+ const matching = SubscriptionRef.changes(viewer.hints).pipe(
31
+ Stream.filter((hints) => hints.some((hint) => namesKeys(hint, keys))),
32
+ Stream.runHead,
33
+ Effect.as(true),
34
+ );
35
+ return yield* Effect.raceFirst(matching, Effect.as(viewer.finished, false)).pipe(
36
+ Effect.timeoutOrElse({ duration: options.within ?? "1 second", orElse: () => Effect.succeed(false) }),
37
+ );
38
+ });
39
+
40
+ function namesKeys(hint: SubscriptionHint, keys: readonly Key[]): boolean {
41
+ return hint._tag === "Changed" && keys.every((key) => hint.keys.some((actual) => JSON.stringify(actual) === JSON.stringify(key)));
42
+ }
43
+
44
+ export function layerMemoryProtocol<TRpcs extends Rpc.Any>(group: RpcGroup.RpcGroup<TRpcs>) {
45
+ return Layer.effect(
46
+ RpcClient.Protocol,
47
+ Effect.gen(function* () {
48
+ const requests = yield* Queue.unbounded<readonly [number, RpcMessage.FromClientEncoded]>();
49
+ const disconnects = yield* Queue.unbounded<number>();
50
+ const { codecFor } = yield* RpcSerialization.RpcSerialization;
51
+ const protocol = yield* RpcClient.Protocol.make((send, clientIds) =>
52
+ Effect.gen(function* () {
53
+ const server = RpcServer.Protocol.of({
54
+ clientIds: Effect.sync(() => clientIds),
55
+ codecFor,
56
+ disconnects,
57
+ end: () => Effect.void,
58
+ initialMessage: Effect.succeedNone,
59
+ run: (receive) => Effect.forever(Effect.flatMap(Queue.take(requests), ([id, message]) => receive(id, message))),
60
+ send,
61
+ supportsAck: true,
62
+ supportsNotifications: true,
63
+ supportsSpanPropagation: true,
64
+ supportsTransferables: false,
65
+ });
66
+ yield* RpcServer.make(group).pipe(Effect.provideService(RpcServer.Protocol, server), Effect.forkScoped);
67
+ return {
68
+ codecFor,
69
+ send: (clientId, request) => Queue.offer(requests, [clientId, request]).pipe(Effect.asVoid),
70
+ supportsAck: true,
71
+ supportsTransferables: false,
72
+ };
73
+ }),
74
+ );
75
+ return {
76
+ ...protocol,
77
+ run: (clientId, receive) => protocol.run(clientId, receive).pipe(Effect.ensuring(Queue.offer(disconnects, clientId))),
78
+ } satisfies RpcClient.Protocol["Service"];
79
+ }),
80
+ ).pipe(Layer.provide(RpcSerialization.layerNdjson));
81
+ }
@@ -0,0 +1,44 @@
1
+ import { Effect, Queue, Redacted, Schema } from "effect";
2
+ import { Email } from "@shivaedev/email/Email.ts";
3
+ import { resendMailerLayer } from "@shivaedev/email/server/adapters/resendMailerLayer.ts";
4
+ import { fakeHttpService } from "@shivaedev/test-story/server/fakeHttpService.ts";
5
+ import { routeOutbound } from "@shivaedev/test-story/server/routeOutbound.ts";
6
+
7
+ export interface ReceivedEmail extends Email {
8
+ readonly idempotencyKey: string | undefined;
9
+ }
10
+
11
+ export const inbox = Effect.fnUntraced(function* () {
12
+ const arrivals = yield* Queue.unbounded<ReceivedEmail>();
13
+ const emails: ReceivedEmail[] = [];
14
+ const decode = Schema.decodeUnknownSync(Schema.fromJsonString(Email));
15
+ const endpoint = yield* fakeHttpService({
16
+ routes: {
17
+ send: {
18
+ method: "POST",
19
+ path: "/emails",
20
+ reply: (request) => {
21
+ const email = { ...decode(request.body.toString()), idempotencyKey: request.headers["idempotency-key"]?.toString() };
22
+ emails.push(email);
23
+ Queue.offerUnsafe(arrivals, email);
24
+ return { body: { id: `email-${emails.length}` } };
25
+ },
26
+ },
27
+ },
28
+ });
29
+ yield* routeOutbound({ "api.resend.com": endpoint.url });
30
+ return {
31
+ emails: () => Effect.sync(() => [...emails]),
32
+ endpoint,
33
+ mailerLayer: resendMailerLayer({ apiKey: Redacted.make("re_story") }),
34
+ nextEmail: Queue.take(arrivals).pipe(Effect.timeout("10 seconds")),
35
+ };
36
+ });
37
+
38
+ export function emailLink(email: Email): string {
39
+ const link = email.text.match(/https?:\/\/[^\s<>]+/u)?.[0];
40
+ if (link === undefined) {
41
+ throw new Error("The delivered email has no link in its text");
42
+ }
43
+ return link;
44
+ }
@@ -0,0 +1,109 @@
1
+ import type { AuthContext } from "better-auth";
2
+ import type { testUtils } from "better-auth/plugins";
3
+ import { Clock, Effect } from "effect";
4
+ import { signedSessionToken, testUserEmail } from "./testingCredentials.ts";
5
+
6
+ type TestContext = ReturnType<ReturnType<typeof testUtils>["init"]>["context"];
7
+ type UserFields = NonNullable<Parameters<TestContext["test"]["createUser"]>[0]>;
8
+ type Login = Awaited<ReturnType<TestContext["test"]["login"]>>;
9
+ type AccountContext = Pick<AuthContext, "internalAdapter">;
10
+ type SessionContext = AccountContext & Pick<AuthContext, "sessionConfig" | "secret" | "authCookies" | "baseURL">;
11
+
12
+ function saveUser(context: AccountContext, fields: UserFields) {
13
+ return Effect.flatMap(testUserEmail, (email) =>
14
+ Effect.promise(() =>
15
+ context.internalAdapter.createUser({ email, emailVerified: true, image: null, name: "Test User", ...fields }, { method: "test" }),
16
+ ),
17
+ );
18
+ }
19
+
20
+ function cookieSameSite(value: string | undefined) {
21
+ switch (value?.toLowerCase()) {
22
+ case "strict":
23
+ return "Strict";
24
+ case "none":
25
+ return "None";
26
+ default:
27
+ return "Lax";
28
+ }
29
+ }
30
+
31
+ export const signedInUser = Effect.fnUntraced(function* (
32
+ auth: { readonly $context: Promise<SessionContext> },
33
+ {
34
+ providerAccounts = [],
35
+ ...fields
36
+ }: UserFields & {
37
+ readonly providerAccounts?: readonly { readonly providerId: string; readonly accountId: string }[];
38
+ },
39
+ ): Effect.fn.Return<Login> {
40
+ const context = yield* Effect.promise(() => auth.$context);
41
+ const user = yield* saveUser(context, fields);
42
+ for (const { providerId, accountId } of providerAccounts) {
43
+ yield* Effect.promise(() => context.internalAdapter.createAccount({ accountId, providerId, userId: user.id }));
44
+ }
45
+ return yield* signInAgain(auth, user.id);
46
+ });
47
+
48
+ export const signInAgain = Effect.fnUntraced(function* (
49
+ auth: { readonly $context: Promise<SessionContext> },
50
+ userId: string,
51
+ ): Effect.fn.Return<Login> {
52
+ const { internalAdapter, sessionConfig, authCookies, secret, baseURL } = yield* Effect.promise(() => auth.$context);
53
+ const now = yield* Clock.currentTimeMillis;
54
+ const session = yield* Effect.promise(() => internalAdapter.createSession(userId, false, {}, true));
55
+ const expiresAt = new Date(now + sessionConfig.expiresIn * 1000);
56
+ yield* Effect.promise(() => internalAdapter.updateSession(session.token, { expiresAt }));
57
+ const user = yield* Effect.promise(() => internalAdapter.findUserById(userId));
58
+ if (user === null) {
59
+ return yield* Effect.die(`User not found: ${userId}`);
60
+ }
61
+ const value = yield* signedSessionToken(session.token, secret);
62
+ const { name, attributes } = authCookies.sessionToken;
63
+ const cookies: Login["cookies"] = [
64
+ {
65
+ domain: URL.canParse(baseURL) ? new URL(baseURL).hostname : "localhost",
66
+ httpOnly: attributes.httpOnly ?? true,
67
+ name,
68
+ path: attributes.path || "/",
69
+ sameSite: cookieSameSite(attributes.sameSite),
70
+ secure: attributes.secure ?? false,
71
+ value,
72
+ ...(attributes.maxAge ? { expires: Math.floor(now / 1000) + attributes.maxAge } : {}),
73
+ },
74
+ ];
75
+ return { cookies, headers: new Headers({ cookie: `${name}=${value}` }), session: { ...session, expiresAt }, token: session.token, user };
76
+ });
77
+
78
+ export async function storedProviderAccounts(auth: { readonly $context: Promise<AccountContext> }, userId: string) {
79
+ const { internalAdapter } = await auth.$context;
80
+ const accounts = await internalAdapter.findAccounts(userId);
81
+ return accounts.map(({ providerId, accountId, accessToken, refreshToken, idToken, password }) => ({
82
+ accountId,
83
+ hasAccessToken: Boolean(accessToken),
84
+ hasIdToken: Boolean(idToken),
85
+ hasPassword: Boolean(password),
86
+ hasRefreshToken: Boolean(refreshToken),
87
+ providerId,
88
+ }));
89
+ }
90
+
91
+ export const passwordUser = Effect.fnUntraced(function* (
92
+ auth: { readonly $context: Promise<AccountContext & { readonly password: Pick<AuthContext["password"], "hash"> }> },
93
+ {
94
+ password,
95
+ passwordHash,
96
+ ...fields
97
+ }: UserFields & { readonly email: string } & (
98
+ | { readonly password: string; readonly passwordHash?: never }
99
+ | { readonly passwordHash: string; readonly password?: never }
100
+ ),
101
+ ) {
102
+ const context = yield* Effect.promise(() => auth.$context);
103
+ const user = yield* saveUser(context, fields);
104
+ const hash = passwordHash ?? (yield* Effect.promise(() => context.password.hash(password)));
105
+ yield* Effect.promise(() =>
106
+ context.internalAdapter.createAccount({ accountId: user.id, password: hash, providerId: "credential", userId: user.id }),
107
+ );
108
+ return user;
109
+ });
@@ -0,0 +1,9 @@
1
+ import { generateRandomString, makeSignature } from "better-auth/crypto";
2
+ import { Effect } from "effect";
3
+
4
+ export const testUserEmail = Effect.sync(() => `test-${generateRandomString(8)}@example.com`);
5
+
6
+ export const signedSessionToken = Effect.fnUntraced(function* (token: string, secret: string) {
7
+ const signature = yield* Effect.promise(() => makeSignature(token, secret));
8
+ return `${token}.${signature}`;
9
+ });
@@ -0,0 +1,103 @@
1
+ import { Data, Effect, Schema } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+ import { type BucketKey, type ItemKey, invalidationKeys } from "@shivaedev/changes/keys.ts";
4
+ import { ChangeDeclarations } from "@shivaedev/sql/ChangeDeclarations.ts";
5
+ import { ChangeObserver, transact } from "@shivaedev/sql/transact.ts";
6
+
7
+ export class UnannouncedWrites extends Data.TaggedError("UnannouncedWrites")<{ readonly tables: readonly string[] }> {}
8
+
9
+ export interface ChangeCoverage {
10
+ readonly covers: Readonly<Record<string, readonly (ItemKey | BucketKey)[]>>;
11
+ }
12
+
13
+ export const withChangeCoverage = Effect.fn("Changes.withChangeCoverage")(function* <A, E, R>(
14
+ body: Effect.Effect<A, E, R>,
15
+ options?: ChangeCoverage,
16
+ ) {
17
+ const observer = yield* ChangeObserver;
18
+ const sql = yield* SqlClient.SqlClient;
19
+ const named = new Set<unknown>();
20
+ const declarations = new Map<string, { keys: Set<string>; rows: number }>();
21
+ const outer = yield* ChangeDeclarations;
22
+ const written = sql`select relid, relname, (n_tup_ins + n_tup_upd + n_tup_del)::int as writes from pg_stat_xact_user_tables`.pipe(
23
+ Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Schema.Struct({ relid: Schema.Int, relname: Schema.String, writes: Schema.Int })))),
24
+ );
25
+ const checked = Effect.gen(function* () {
26
+ const before = new Map((yield* written).map((row) => [row.relid, row.writes]));
27
+ const result = yield* body;
28
+ const missing = (yield* written).filter((row) => {
29
+ const count = row.writes - (before.get(row.relid) ?? 0);
30
+ if (count <= 0) {
31
+ return false;
32
+ }
33
+ const automatic = declarations.get(row.relname);
34
+ const explicit = options?.covers[row.relname] ?? [];
35
+ const expected = [...(automatic?.keys ?? []), ...invalidationKeys(explicit)];
36
+ return (count > (automatic?.rows ?? 0) && explicit.length === 0) || expected.some((key) => !named.has(key));
37
+ });
38
+ if (missing.length > 0) {
39
+ return yield* Effect.fail(new UnannouncedWrites({ tables: missing.map((row) => row.relname).sort() }));
40
+ }
41
+ return result;
42
+ });
43
+ return yield* checked.pipe(
44
+ transact({ onSqlError: (error) => error }),
45
+ Effect.provideService(ChangeDeclarations, {
46
+ declare: (table, keys, rows) =>
47
+ Effect.andThen(
48
+ Effect.sync(() => {
49
+ const entry = declarations.get(table) ?? { keys: new Set<string>(), rows: 0 };
50
+ for (const key of keys) {
51
+ entry.keys.add(key);
52
+ }
53
+ entry.rows += rows;
54
+ declarations.set(table, entry);
55
+ }),
56
+ outer.declare(table, keys, rows),
57
+ ),
58
+ }),
59
+ Effect.provideService(ChangeObserver, (event) => {
60
+ if (event._tag === "Recorded") {
61
+ for (const key of event.changes) {
62
+ named.add(key);
63
+ }
64
+ }
65
+ return observer(event);
66
+ }),
67
+ );
68
+ });
69
+
70
+ export class PublishedKeysMismatch extends Data.TaggedError("PublishedKeysMismatch")<{
71
+ readonly expected: readonly unknown[];
72
+ readonly actual: readonly unknown[];
73
+ }> {
74
+ override get message() {
75
+ return `Expected published keys ${JSON.stringify(this.expected)}; actual published keys ${JSON.stringify(this.actual)}`;
76
+ }
77
+ }
78
+
79
+ export function expectPublished(keys: readonly unknown[]): <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E | PublishedKeysMismatch, R>;
80
+ export function expectPublished<A>(
81
+ keys: (result: A) => readonly unknown[],
82
+ ): <E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E | PublishedKeysMismatch, R>;
83
+ export function expectPublished<A>(keys: readonly unknown[] | ((result: A) => readonly unknown[])) {
84
+ return Effect.fn("Changes.expectPublished")(function* <E, R>(body: Effect.Effect<A, E, R>) {
85
+ const observer = yield* ChangeObserver;
86
+ const actual = new Set<unknown>();
87
+ const result = yield* body.pipe(
88
+ Effect.provideService(ChangeObserver, (event) => {
89
+ if (event._tag === "Published") {
90
+ for (const key of event.changes) {
91
+ actual.add(key);
92
+ }
93
+ }
94
+ return observer(event);
95
+ }),
96
+ );
97
+ const expected = new Set(typeof keys === "function" ? keys(result) : keys);
98
+ if (actual.size !== expected.size || [...expected].some((key) => !actual.has(key))) {
99
+ return yield* Effect.fail(new PublishedKeysMismatch({ actual: [...actual], expected: [...expected] }));
100
+ }
101
+ return result;
102
+ });
103
+ }