@alchemy.run/turso 0.0.0 → 2.0.0-beta.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +68 -4
  3. package/lib/ApiToken.d.ts +73 -0
  4. package/lib/ApiToken.d.ts.map +1 -0
  5. package/lib/ApiToken.js +120 -0
  6. package/lib/ApiToken.js.map +1 -0
  7. package/lib/AuthProvider.d.ts +36 -0
  8. package/lib/AuthProvider.d.ts.map +1 -0
  9. package/lib/AuthProvider.js +85 -0
  10. package/lib/AuthProvider.js.map +1 -0
  11. package/lib/Connect.d.ts +79 -0
  12. package/lib/Connect.d.ts.map +1 -0
  13. package/lib/Connect.js +22 -0
  14. package/lib/Connect.js.map +1 -0
  15. package/lib/Contributions.d.ts +7 -0
  16. package/lib/Contributions.d.ts.map +1 -0
  17. package/lib/Contributions.js +6 -0
  18. package/lib/Contributions.js.map +1 -0
  19. package/lib/Credentials.d.ts +39 -0
  20. package/lib/Credentials.d.ts.map +1 -0
  21. package/lib/Credentials.js +80 -0
  22. package/lib/Credentials.js.map +1 -0
  23. package/lib/Database.d.ts +217 -0
  24. package/lib/Database.d.ts.map +1 -0
  25. package/lib/Database.js +271 -0
  26. package/lib/Database.js.map +1 -0
  27. package/lib/DatabaseToken.d.ts +95 -0
  28. package/lib/DatabaseToken.d.ts.map +1 -0
  29. package/lib/DatabaseToken.js +128 -0
  30. package/lib/DatabaseToken.js.map +1 -0
  31. package/lib/Group.d.ts +93 -0
  32. package/lib/Group.d.ts.map +1 -0
  33. package/lib/Group.js +162 -0
  34. package/lib/Group.js.map +1 -0
  35. package/lib/GroupToken.d.ts +48 -0
  36. package/lib/GroupToken.d.ts.map +1 -0
  37. package/lib/GroupToken.js +83 -0
  38. package/lib/GroupToken.js.map +1 -0
  39. package/lib/Hrana.d.ts +42 -0
  40. package/lib/Hrana.d.ts.map +1 -0
  41. package/lib/Hrana.js +105 -0
  42. package/lib/Hrana.js.map +1 -0
  43. package/lib/ManageDatabases.d.ts +73 -0
  44. package/lib/ManageDatabases.d.ts.map +1 -0
  45. package/lib/ManageDatabases.js +81 -0
  46. package/lib/ManageDatabases.js.map +1 -0
  47. package/lib/OrganizationInvite.d.ts +46 -0
  48. package/lib/OrganizationInvite.d.ts.map +1 -0
  49. package/lib/OrganizationInvite.js +72 -0
  50. package/lib/OrganizationInvite.js.map +1 -0
  51. package/lib/OrganizationMember.d.ts +47 -0
  52. package/lib/OrganizationMember.d.ts.map +1 -0
  53. package/lib/OrganizationMember.js +81 -0
  54. package/lib/OrganizationMember.js.map +1 -0
  55. package/lib/OrganizationSettings.d.ts +52 -0
  56. package/lib/OrganizationSettings.d.ts.map +1 -0
  57. package/lib/OrganizationSettings.js +93 -0
  58. package/lib/OrganizationSettings.js.map +1 -0
  59. package/lib/Providers.d.ts +24 -0
  60. package/lib/Providers.d.ts.map +1 -0
  61. package/lib/Providers.js +42 -0
  62. package/lib/Providers.js.map +1 -0
  63. package/lib/index.d.ts +14 -0
  64. package/lib/index.d.ts.map +1 -0
  65. package/lib/index.js +14 -0
  66. package/lib/index.js.map +1 -0
  67. package/package.json +54 -3
  68. package/src/ApiToken.ts +197 -0
  69. package/src/AuthProvider.ts +113 -0
  70. package/src/Connect.ts +103 -0
  71. package/src/Contributions.ts +9 -0
  72. package/src/Credentials.ts +139 -0
  73. package/src/Database.ts +504 -0
  74. package/src/DatabaseToken.ts +203 -0
  75. package/src/Group.ts +256 -0
  76. package/src/GroupToken.ts +119 -0
  77. package/src/Hrana.ts +182 -0
  78. package/src/ManageDatabases.ts +195 -0
  79. package/src/OrganizationInvite.ts +118 -0
  80. package/src/OrganizationMember.ts +122 -0
  81. package/src/OrganizationSettings.ts +145 -0
  82. package/src/Providers.ts +67 -0
  83. package/src/index.ts +20 -0
@@ -0,0 +1,197 @@
1
+ import * as turso from "@distilled.cloud/turso/turso";
2
+ import { Unowned } from "alchemy/AdoptPolicy";
3
+ import { deepEqual, isResolved } from "alchemy/Diff";
4
+ import { createPhysicalName } from "alchemy/PhysicalName";
5
+ import * as Provider from "alchemy/Provider";
6
+ import { Resource } from "alchemy/Resource";
7
+ import * as Effect from "effect/Effect";
8
+ import * as Redacted from "effect/Redacted";
9
+ import { organization } from "./Credentials.ts";
10
+ import type { Providers } from "./Providers.ts";
11
+
12
+ /**
13
+ * A permission granted to a group-scoped API token. `read-only` and
14
+ * `full-access` are presets that expand to individual scopes.
15
+ */
16
+ export type ApiTokenScope =
17
+ | "read"
18
+ | "db:create"
19
+ | "db:delete"
20
+ | "db:configure"
21
+ | "db:mint-token"
22
+ | "db:rotate-creds"
23
+ | "group:configure"
24
+ | "group:mint-token"
25
+ | "group:rotate-creds"
26
+ | "read-only"
27
+ | "full-access";
28
+
29
+ export interface ApiTokenProps {
30
+ /**
31
+ * Token name, unique within your account. If omitted, a unique name is
32
+ * generated from the stack, stage, and logical ID.
33
+ */
34
+ name?: string;
35
+ /**
36
+ * Restrict the token to one group of the organization (e.g.
37
+ * `group.name`). Requires `scopes`. Omit for an organization-scoped token.
38
+ */
39
+ group?: string;
40
+ /**
41
+ * Permissions of a group-scoped token. Required (and non-empty) when
42
+ * `group` is set. `db:mint-token` issues new SQL tokens;
43
+ * `db:rotate-creds` invalidates every SQL token of a database.
44
+ */
45
+ scopes?: ApiTokenScope[];
46
+ }
47
+
48
+ export interface ApiTokenAttributes {
49
+ /** Token ID. */
50
+ id: string;
51
+ /** Token name. */
52
+ name: string;
53
+ /** The organization slug the token is restricted to. */
54
+ organization: string;
55
+ /** The group the token is restricted to, if group-scoped. */
56
+ group: string | undefined;
57
+ /** The expanded scopes of a group-scoped token. */
58
+ scopes: string[];
59
+ /** The Platform API token, sent as `Authorization: Bearer <token>`. */
60
+ token: Redacted.Redacted<string>;
61
+ }
62
+
63
+ export type ApiToken = Resource<
64
+ "Turso.ApiToken",
65
+ ApiTokenProps,
66
+ ApiTokenAttributes,
67
+ never,
68
+ Providers
69
+ >;
70
+
71
+ /**
72
+ * A Turso API token. It lets an app create and delete groups and databases.
73
+ * To run SQL, use a {@link DatabaseToken} instead. Limit it to one group
74
+ * with `group` and `scopes` to give an app only the access it needs.
75
+ *
76
+ * Turso only shows the token once, when it's created, so Alchemy stores it
77
+ * in state as a `Redacted` value. Changing a prop creates a new token, and
78
+ * destroying it cancels the token.
79
+ * @see https://docs.turso.tech/api-reference/tokens/create
80
+ *
81
+ * ### Creating a Token
82
+ * **Example:** Token for the whole organization
83
+ * ```typescript
84
+ * const token = yield* Turso.ApiToken("Ci", {});
85
+ * ```
86
+ *
87
+ * **Example:** Token that can only create databases in one group
88
+ * ```typescript
89
+ * const token = yield* Turso.ApiToken("Tenants", {
90
+ * group: group.name,
91
+ * scopes: ["read", "db:create", "db:delete", "db:mint-token"],
92
+ * });
93
+ * ```
94
+ *
95
+ * @resource
96
+ * @product API Token
97
+ */
98
+ export const ApiToken = Resource<ApiToken>("Turso.ApiToken");
99
+
100
+ const tokenName = (id: string, name: string | undefined) =>
101
+ name ? Effect.succeed(name) : createPhysicalName({ id, maxLength: 64, delimiter: "-" });
102
+
103
+ export const ApiTokenProvider = () =>
104
+ Provider.effect(
105
+ ApiToken,
106
+ Effect.gen(function* () {
107
+ const observe = (name: string) =>
108
+ turso
109
+ .listAPITokens({})
110
+ .pipe(Effect.map(({ tokens }) => (tokens ?? []).find((t) => t.name === name)));
111
+
112
+ const revoke = (name: string) =>
113
+ turso.revokeAPIToken({ tokenName: name }).pipe(
114
+ Effect.asVoid,
115
+ Effect.catchTag("NotFound", () => Effect.void),
116
+ );
117
+
118
+ return {
119
+ stables: ["id", "name", "organization", "group", "scopes", "token"],
120
+ diff: Effect.fn(function* ({ id, olds, news, output }) {
121
+ if (!isResolved(news)) return undefined;
122
+ const name = output?.name ?? (yield* tokenName(id, olds?.name));
123
+ // Turso tokens are immutable: any change mints a new one.
124
+ if (
125
+ (news.name !== undefined && news.name !== name) ||
126
+ news.group !== olds?.group ||
127
+ !deepEqual(news.scopes ?? [], olds?.scopes ?? [])
128
+ ) {
129
+ // A pinned name can't be held by two tokens at once.
130
+ return {
131
+ action: "replace",
132
+ deleteFirst: news.name !== undefined && news.name === name,
133
+ } as const;
134
+ }
135
+ }),
136
+ read: Effect.fn(function* ({ id, olds, output }) {
137
+ const name = output?.name ?? (yield* tokenName(id, olds?.name));
138
+ const observed = yield* observe(name);
139
+ if (!observed) return undefined;
140
+ if (output !== undefined && output.id === observed.id) return output;
141
+ // The secret is only revealed at creation, so a token we have no
142
+ // state for can't be adopted with its value — reconcile re-mints.
143
+ return Unowned({
144
+ id: observed.id ?? "",
145
+ name,
146
+ organization: observed.organization ?? "",
147
+ group: observed.group,
148
+ scopes: observed.scopes ?? [],
149
+ token: Redacted.make(""),
150
+ });
151
+ }),
152
+ reconcile: Effect.fn(function* ({ id, news, output, session }) {
153
+ const org = output?.organization ?? (yield* organization);
154
+ const name = output?.name ?? (yield* tokenName(id, news.name));
155
+
156
+ // Observe
157
+ const observed = yield* observe(name);
158
+ if (
159
+ observed &&
160
+ output &&
161
+ Redacted.value(output.token) !== "" &&
162
+ output.id === observed.id
163
+ ) {
164
+ return output;
165
+ }
166
+
167
+ // Ensure — a token we hold no secret for (a lost create, or an
168
+ // adoption) is revoked and re-minted.
169
+ if (observed) {
170
+ yield* session.note(`Re-minting API token ${name}...`);
171
+ yield* revoke(name);
172
+ }
173
+ const created = yield* turso.createAPIToken({
174
+ tokenName: name,
175
+ organization: org,
176
+ group: news.group,
177
+ scopes: news.scopes,
178
+ });
179
+ if (!created.token || !created.id) {
180
+ return yield* Effect.fail(new Error(`Turso returned no token for ${name}`));
181
+ }
182
+ const minted = yield* observe(name);
183
+ return {
184
+ id: created.id,
185
+ name,
186
+ organization: minted?.organization ?? org,
187
+ group: minted?.group ?? news.group,
188
+ scopes: minted?.scopes ?? [],
189
+ token: created.token,
190
+ };
191
+ }),
192
+ delete: Effect.fn(function* ({ output }) {
193
+ yield* revoke(output.name);
194
+ }),
195
+ };
196
+ }),
197
+ );
@@ -0,0 +1,113 @@
1
+ import { DEFAULT_API_BASE_URL } from "@distilled.cloud/turso/Credentials";
2
+ import { AuthError } from "alchemy/Auth/AuthProvider";
3
+ import { getEnv, getEnvRedacted } from "alchemy/Auth/Env";
4
+ import {
5
+ makeStoredAuthProvider,
6
+ storedSecret,
7
+ storedValueText,
8
+ type StoredAuthConfig,
9
+ } from "alchemy/Auth/StoredAuthProvider";
10
+ import * as Effect from "effect/Effect";
11
+ import * as Redacted from "effect/Redacted";
12
+
13
+ /**
14
+ * Canonical name registered in the AuthProviders registry. Use this key to
15
+ * look up the Turso AuthProvider from inside provider Layers.
16
+ */
17
+ export const TURSO_AUTH_PROVIDER_NAME = "Turso";
18
+
19
+ export type TursoAuthConfig = StoredAuthConfig;
20
+
21
+ /**
22
+ * Resolved Turso Platform API credentials.
23
+ *
24
+ * Turso has no OAuth application flow — the Platform API authenticates
25
+ * with API tokens only (`turso auth api-tokens mint <name>`). The
26
+ * organization is optional: when omitted it is discovered from the token
27
+ * (an organization-scoped token, or an account with a single organization).
28
+ */
29
+ export interface TursoResolvedCredentials {
30
+ type: "apiToken";
31
+ apiToken: Redacted.Redacted<string>;
32
+ apiBaseUrl: string;
33
+ organization: string | undefined;
34
+ source: { type: TursoAuthConfig["method"] | "env"; details?: string };
35
+ }
36
+
37
+ const readEnvironment = Effect.gen(function* () {
38
+ const apiToken = yield* getEnvRedacted("TURSO_API_TOKEN");
39
+ const apiKey = yield* getEnvRedacted("TURSO_API_KEY");
40
+ const token = apiToken ?? apiKey;
41
+ if (token === undefined || Redacted.value(token).trim().length === 0) {
42
+ return yield* new AuthError({
43
+ message: "Turso CI credentials not found. Set TURSO_API_TOKEN or TURSO_API_KEY.",
44
+ });
45
+ }
46
+ return {
47
+ type: "apiToken" as const,
48
+ apiToken: Redacted.make(Redacted.value(token).trim()),
49
+ apiBaseUrl: (yield* getEnv("TURSO_API_BASE_URL")) ?? DEFAULT_API_BASE_URL,
50
+ organization: yield* getEnv("TURSO_ORGANIZATION"),
51
+ source: {
52
+ type: "env" as const,
53
+ details: apiToken === undefined ? "TURSO_API_KEY" : "TURSO_API_TOKEN",
54
+ },
55
+ } satisfies TursoResolvedCredentials;
56
+ });
57
+
58
+ const tursoAuth = makeStoredAuthProvider<TursoResolvedCredentials>({
59
+ provider: TURSO_AUTH_PROVIDER_NAME,
60
+ fields: [
61
+ {
62
+ name: "apiToken",
63
+ label: "Turso API Token",
64
+ description: "Mint one with `turso auth api-tokens mint alchemy`.",
65
+ secret: true,
66
+ validate: (value) => (value.trim().length === 0 ? "Required" : undefined),
67
+ },
68
+ {
69
+ name: "organization",
70
+ label: "Turso Organization (slug)",
71
+ description: "Defaults to the token's organization when it has exactly one.",
72
+ optional: true,
73
+ },
74
+ ],
75
+ toResolved: (values, source) => ({
76
+ type: "apiToken",
77
+ apiToken: storedSecret(values.apiToken) ?? Redacted.make(""),
78
+ apiBaseUrl: DEFAULT_API_BASE_URL,
79
+ organization: storedValueText(values.organization),
80
+ source: { type: source },
81
+ }),
82
+ readEnvironment,
83
+ environment: [
84
+ {
85
+ name: "TURSO_API_TOKEN",
86
+ required: true,
87
+ secret: true,
88
+ alternatives: ["TURSO_API_KEY"],
89
+ description: "Turso Platform API token.",
90
+ },
91
+ {
92
+ name: "TURSO_ORGANIZATION",
93
+ required: false,
94
+ description: "Organization slug; defaults to the token's only organization.",
95
+ },
96
+ {
97
+ name: "TURSO_API_BASE_URL",
98
+ required: false,
99
+ description: "Platform API base URL override.",
100
+ },
101
+ ],
102
+ });
103
+
104
+ /**
105
+ * Layer that registers the Turso AuthProvider into the AuthProviders
106
+ * registry when built. Included in `Turso.providers()` so the alchemy CLI
107
+ * (`alchemy profile edit`) can configure it.
108
+ */
109
+ export const TursoAuth = tursoAuth.layer;
110
+
111
+ /** Schema of Turso's inline API-token values. */
112
+ export const TursoStoredCredentials = tursoAuth.storedSchema;
113
+ export type TursoStoredCredentials = typeof TursoStoredCredentials.Type;
package/src/Connect.ts ADDED
@@ -0,0 +1,103 @@
1
+ import * as Binding from "alchemy/Binding";
2
+ import type { RuntimeContext } from "alchemy/RuntimeContext";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+ import type * as Redacted from "effect/Redacted";
6
+ import type { Database } from "./Database.ts";
7
+ import { DatabaseToken, type TokenAuthorization } from "./DatabaseToken.ts";
8
+
9
+ /**
10
+ * libSQL connection accessors for one Turso database. Resolving them does
11
+ * not open a connection; pass the client to `SQL.LibSQL` or
12
+ * `Drizzle.LibSQL`, or read `url` / `authToken` for `@libsql/client`.
13
+ */
14
+ export interface ConnectClient {
15
+ /** libSQL URL of the database (`libsql://<hostname>`). */
16
+ url: Effect.Effect<string, never, RuntimeContext>;
17
+ /** SQL auth token for the database. */
18
+ authToken: Effect.Effect<Redacted.Redacted<string>, never, RuntimeContext>;
19
+ }
20
+
21
+ export interface ConnectOptions {
22
+ /**
23
+ * Access level of the token minted for this host.
24
+ * @default "full-access"
25
+ */
26
+ authorization?: TokenAuthorization;
27
+ }
28
+
29
+ /**
30
+ * Connect to a Turso database from a Worker, Lambda, or other host. The
31
+ * host gets the database's URL and its own {@link DatabaseToken}. Your
32
+ * Turso API token stays on your machine.
33
+ *
34
+ * ### Querying a Database
35
+ * **Example:** Effect SQL over a Turso database
36
+ * ```typescript
37
+ * Effect.gen(function* () {
38
+ * const conn = yield* Turso.Connect(Db);
39
+ * const sql = yield* SQL.LibSQL(conn);
40
+ * return {
41
+ * fetch: Effect.gen(function* () {
42
+ * return yield* HttpServerResponse.json(yield* sql`SELECT 1 AS value`);
43
+ * }),
44
+ * };
45
+ * }).pipe(Effect.provide(Turso.ConnectHttp));
46
+ * ```
47
+ *
48
+ * **Example:** Drizzle over a Turso database
49
+ * ```typescript
50
+ * const conn = yield* Turso.Connect(Db);
51
+ * const db = yield* Drizzle.LibSQL(conn, { relations });
52
+ * ```
53
+ *
54
+ * **Example:** AWS Lambda (install the native libSQL client)
55
+ * ```typescript
56
+ * export default class Api extends Lambda.Function<Api>()(
57
+ * "Api",
58
+ * { main: import.meta.url, build: { install: ["@libsql/client"] } },
59
+ * Effect.gen(function* () {
60
+ * const sql = yield* SQL.LibSQL(yield* Turso.Connect(Db));
61
+ * // ...
62
+ * }).pipe(Effect.provide(Turso.ConnectHttp)),
63
+ * ) {}
64
+ * ```
65
+ *
66
+ * **Example:** Read-only access
67
+ * ```typescript
68
+ * const conn = yield* Turso.Connect(Db, { authorization: "read-only" });
69
+ * ```
70
+ *
71
+ * @binding
72
+ * @product Database
73
+ */
74
+ export interface Connect extends Binding.Service<
75
+ Connect,
76
+ "Turso.Connect",
77
+ (database: Database, options?: ConnectOptions) => Effect.Effect<ConnectClient>
78
+ > {}
79
+
80
+ export const Connect = Binding.Service<Connect>("Turso.Connect");
81
+
82
+ /**
83
+ * Host-independent implementation: the URL and a per-host token are bound
84
+ * as environment values, so it works on any Platform host.
85
+ */
86
+ export const ConnectHttp = Layer.effect(
87
+ Connect,
88
+ Effect.gen(function* () {
89
+ const Token = yield* DatabaseToken;
90
+ return Effect.fn(function* (database: Database, options?: ConnectOptions) {
91
+ const host = yield* Binding.Host;
92
+ const authorization = options?.authorization ?? "full-access";
93
+ const token = yield* Token(
94
+ `${host?.LogicalId ?? ""}${database.LogicalId}${authorization === "read-only" ? "ReadOnly" : ""}Token`,
95
+ { database: database.name, authorization },
96
+ );
97
+ return {
98
+ url: yield* database.url,
99
+ authToken: yield* token.token,
100
+ } satisfies ConnectClient;
101
+ });
102
+ }),
103
+ );
@@ -0,0 +1,9 @@
1
+ import * as Contributions from "alchemy/Contributions";
2
+
3
+ export default Contributions.make({
4
+ name: "turso",
5
+ auth: Contributions.lazy(
6
+ () => import("./AuthProvider.ts"),
7
+ (module) => module.TursoAuth,
8
+ ),
9
+ });
@@ -0,0 +1,139 @@
1
+ import { ConfigError } from "@distilled.cloud/core/errors";
2
+ import {
3
+ Credentials,
4
+ DEFAULT_API_BASE_URL,
5
+ type Config as TursoClientConfig,
6
+ } from "@distilled.cloud/turso/Credentials";
7
+ import * as turso from "@distilled.cloud/turso/turso";
8
+ import {
9
+ deferUntilFirstUse,
10
+ orDieCredentialsUnavailable,
11
+ resolveProviderConfig,
12
+ } from "alchemy/Auth/Resolve";
13
+ import * as Context from "effect/Context";
14
+ import * as Effect from "effect/Effect";
15
+ import * as HttpClient from "effect/http/HttpClient";
16
+ import * as Layer from "effect/Layer";
17
+ import * as Redacted from "effect/Redacted";
18
+ import {
19
+ TURSO_AUTH_PROVIDER_NAME,
20
+ type TursoAuthConfig,
21
+ type TursoResolvedCredentials,
22
+ } from "./AuthProvider.ts";
23
+
24
+ export {
25
+ Credentials,
26
+ CredentialsFromEnv,
27
+ DEFAULT_API_BASE_URL,
28
+ } from "@distilled.cloud/turso/Credentials";
29
+
30
+ /**
31
+ * The Turso organization slug every org-scoped Platform API call targets.
32
+ * Holds an effect so the slug is resolved (and, when not configured,
33
+ * discovered from the API token) on first use, never at layer build.
34
+ */
35
+ export class Organization extends Context.Service<Organization, Effect.Effect<string>>()(
36
+ "Turso.Organization",
37
+ ) {}
38
+
39
+ /** The organization slug for the current Turso credentials. */
40
+ export const organization = Effect.gen(function* () {
41
+ return yield* yield* Organization;
42
+ });
43
+
44
+ /**
45
+ * Discover the organization an API token acts on: the token's own
46
+ * organization when it is org-scoped, else the account's only organization.
47
+ */
48
+ const discoverOrganization = Effect.gen(function* () {
49
+ const orgs = yield* turso.listOrganizations({});
50
+ if (orgs.length === 1 && orgs[0]?.slug) {
51
+ return orgs[0].slug;
52
+ }
53
+ return yield* new ConfigError({
54
+ message:
55
+ orgs.length === 0
56
+ ? "Turso: this API token has no organizations."
57
+ : `Turso: this API token can access ${orgs.length} organizations (${orgs
58
+ .map((org) => org.slug)
59
+ .join(", ")}). Set TURSO_ORGANIZATION or configure the organization in your profile.`,
60
+ });
61
+ });
62
+
63
+ const make = (
64
+ resolve: Effect.Effect<TursoResolvedCredentials>,
65
+ ): Effect.Effect<Context.Context<Credentials | Organization>, never, HttpClient.HttpClient> =>
66
+ Effect.gen(function* () {
67
+ const http = yield* HttpClient.HttpClient;
68
+ const cached = yield* Effect.cached(resolve);
69
+ const credentials: Effect.Effect<TursoClientConfig> = Effect.map(cached, (creds) => ({
70
+ apiKey: creds.apiToken,
71
+ apiBaseUrl: creds.apiBaseUrl,
72
+ }));
73
+ const organization = yield* Effect.cached(
74
+ Effect.flatMap(cached, (creds) =>
75
+ creds.organization !== undefined && creds.organization.length > 0
76
+ ? Effect.succeed(creds.organization)
77
+ : discoverOrganization.pipe(
78
+ Effect.provideService(Credentials, credentials),
79
+ Effect.provideService(HttpClient.HttpClient, http),
80
+ orDieCredentialsUnavailable(TURSO_AUTH_PROVIDER_NAME),
81
+ ),
82
+ ),
83
+ );
84
+ return Context.make(Credentials, credentials).pipe(Context.add(Organization, organization));
85
+ });
86
+
87
+ /**
88
+ * Build Turso `Credentials` + `Organization` from an explicit API token.
89
+ * Useful for tests or when the caller already has a token in hand.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * Effect.provide(Turso.fromToken({ apiToken: "...", organization: "my-org" }))
94
+ * ```
95
+ */
96
+ export const fromToken = (input: {
97
+ apiToken: string | Redacted.Redacted<string>;
98
+ organization?: string;
99
+ apiBaseUrl?: string;
100
+ }) =>
101
+ Layer.effectContext(
102
+ make(
103
+ Effect.succeed({
104
+ type: "apiToken",
105
+ apiToken:
106
+ typeof input.apiToken === "string" ? Redacted.make(input.apiToken) : input.apiToken,
107
+ apiBaseUrl: input.apiBaseUrl ?? DEFAULT_API_BASE_URL,
108
+ organization: input.organization,
109
+ source: { type: "stored" },
110
+ }),
111
+ ),
112
+ );
113
+
114
+ /**
115
+ * Build Turso `Credentials` + `Organization` that resolve through the
116
+ * Alchemy AuthProvider: environment credentials (`TURSO_API_TOKEN`) when
117
+ * present, otherwise the selected profile. Resolution is deferred until the
118
+ * first API call, so building the provider layers never needs a profile.
119
+ */
120
+ export const fromAuthProvider = () =>
121
+ Layer.effectContext(
122
+ Effect.gen(function* () {
123
+ const resolve = yield* resolveProviderConfig<TursoAuthConfig, TursoResolvedCredentials>(
124
+ TURSO_AUTH_PROVIDER_NAME,
125
+ ).pipe(
126
+ Effect.flatMap(({ profileName, resolve }) =>
127
+ Effect.mapError(
128
+ resolve,
129
+ (e) =>
130
+ new ConfigError({
131
+ message: `Failed to resolve Turso credentials from ${profileName === undefined ? "the environment" : `profile '${profileName}'`}: ${e.message}`,
132
+ }),
133
+ ),
134
+ ),
135
+ deferUntilFirstUse,
136
+ );
137
+ return yield* make(resolve.pipe(orDieCredentialsUnavailable(TURSO_AUTH_PROVIDER_NAME)));
138
+ }),
139
+ );