@samebase/alchemy-convex 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +85 -17
  2. package/lib/index.d.ts +352 -9
  3. package/lib/index.d.ts.map +1 -1
  4. package/lib/index.js +962 -10
  5. package/lib/index.js.map +1 -1
  6. package/package.json +7 -4
  7. package/src/Adoption.ts +30 -0
  8. package/src/DefaultEnvironmentVariable.ts +127 -29
  9. package/src/Deploy.ts +37 -15
  10. package/src/DeployKey.ts +221 -60
  11. package/src/EnvironmentVariable.ts +174 -41
  12. package/src/ManagementApi.ts +57 -1
  13. package/src/PreviewDeployKey.ts +65 -38
  14. package/src/Project.ts +236 -52
  15. package/src/index.ts +9 -0
  16. package/lib/Credentials.d.ts +0 -39
  17. package/lib/Credentials.d.ts.map +0 -1
  18. package/lib/Credentials.js +0 -49
  19. package/lib/Credentials.js.map +0 -1
  20. package/lib/DefaultEnvironmentVariable.d.ts +0 -58
  21. package/lib/DefaultEnvironmentVariable.d.ts.map +0 -1
  22. package/lib/DefaultEnvironmentVariable.js +0 -93
  23. package/lib/DefaultEnvironmentVariable.js.map +0 -1
  24. package/lib/Deploy.d.ts +0 -62
  25. package/lib/Deploy.d.ts.map +0 -1
  26. package/lib/Deploy.js +0 -92
  27. package/lib/Deploy.js.map +0 -1
  28. package/lib/DeployKey.d.ts +0 -48
  29. package/lib/DeployKey.d.ts.map +0 -1
  30. package/lib/DeployKey.js +0 -104
  31. package/lib/DeployKey.js.map +0 -1
  32. package/lib/EnvironmentVariable.d.ts +0 -37
  33. package/lib/EnvironmentVariable.d.ts.map +0 -1
  34. package/lib/EnvironmentVariable.js +0 -65
  35. package/lib/EnvironmentVariable.js.map +0 -1
  36. package/lib/ManagementApi.d.ts +0 -50
  37. package/lib/ManagementApi.d.ts.map +0 -1
  38. package/lib/ManagementApi.js +0 -103
  39. package/lib/ManagementApi.js.map +0 -1
  40. package/lib/PreviewDeployKey.d.ts +0 -34
  41. package/lib/PreviewDeployKey.d.ts.map +0 -1
  42. package/lib/PreviewDeployKey.js +0 -78
  43. package/lib/PreviewDeployKey.js.map +0 -1
  44. package/lib/Project.d.ts +0 -29
  45. package/lib/Project.d.ts.map +0 -1
  46. package/lib/Project.js +0 -114
  47. package/lib/Project.js.map +0 -1
  48. package/lib/Providers.d.ts +0 -13
  49. package/lib/Providers.d.ts.map +0 -1
  50. package/lib/Providers.js +0 -30
  51. package/lib/Providers.js.map +0 -1
package/lib/index.js CHANGED
@@ -1,11 +1,963 @@
1
- // @samebase/alchemy-convex: Convex resources for Alchemy v2.
2
- export { ACCESS_TOKEN_ENV, Credentials, CredentialsError, fromConfig, fromToken, } from "./Credentials.js";
3
- export { DefaultEnvironmentVariable, } from "./DefaultEnvironmentVariable.js";
4
- export { Deploy, deployArgs, parseDeployOutput, } from "./Deploy.js";
5
- export { DeployKey, } from "./DeployKey.js";
6
- export { EnvironmentVariable, } from "./EnvironmentVariable.js";
7
- export { ConvexApiError, ManagementApi } from "./ManagementApi.js";
8
- export { PreviewDeployKey, } from "./PreviewDeployKey.js";
9
- export { Project, } from "./Project.js";
10
- export { Providers, providers } from "./Providers.js";
1
+ import { readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import * as Config from "effect/Config";
5
+ import * as Context from "effect/Context";
6
+ import * as Effect from "effect/Effect";
7
+ import * as Layer from "effect/Layer";
8
+ import * as Redacted from "effect/Redacted";
9
+ import * as Schema from "effect/Schema";
10
+ import { Resource } from "alchemy";
11
+ import { AdoptPolicy, OwnedBySomeoneElse, Unowned } from "alchemy/AdoptPolicy";
12
+ import { havePropsChanged, isResolved } from "alchemy/Diff";
13
+ import * as Provider from "alchemy/Provider";
14
+ import { AlchemyContext } from "alchemy/AlchemyContext";
15
+ import { Stack } from "alchemy/Stack";
16
+ import * as Option from "effect/Option";
17
+ import { createDeploymentClient, createManagementClient } from "@convex-dev/platform";
18
+ import * as Schedule from "effect/Schedule";
19
+ import { stripVTControlCharacters } from "node:util";
20
+ import { CommandExecutor, CommandExecutorLive } from "alchemy/Command";
21
+ import { hashDirectory } from "alchemy/Command/Memo";
22
+ import { createHash } from "node:crypto";
23
+ //#region src/Credentials.ts
24
+ var Credentials = class extends Context.Service()("@samebase/alchemy-convex/Credentials") {};
25
+ /** Environment variable read by {@link fromConfig}. */
26
+ const ACCESS_TOKEN_ENV = "CONVEX_ACCESS_TOKEN";
27
+ /** The Convex CLI stores its device login here after `npx convex login`. */
28
+ const convexCliConfigPath = () => join(homedir(), ".convex", "config.json");
29
+ const CliConfig = Schema.Struct({ accessToken: Schema.String });
30
+ /**
31
+ * Token the Convex CLI saved on this machine. It works on the Management API
32
+ * for the teams the logged-in user belongs to. Fails when nobody is logged in.
33
+ */
34
+ const readConvexCliLogin = Effect.gen(function* () {
35
+ const path = convexCliConfigPath();
36
+ const text = yield* Effect.tryPromise({
37
+ try: () => readFile(path, "utf8"),
38
+ catch: () => new CredentialsError({ reason: `no Convex CLI login at ${path}` })
39
+ });
40
+ const parsed = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(CliConfig))(text).pipe(Effect.mapError(() => new CredentialsError({ reason: `${path} has no accessToken` })));
41
+ return {
42
+ accessToken: Redacted.make(parsed.accessToken),
43
+ source: "convex-cli-login"
44
+ };
45
+ });
46
+ var CredentialsError = class extends Schema.TaggedError()("CredentialsError", { reason: Schema.String }) {};
47
+ /**
48
+ * Default resolution: `CONVEX_ACCESS_TOKEN` from the stack ConfigProvider
49
+ * (process env, `.env`, stack secrets), then the Convex CLI login on this
50
+ * machine. CI sets the variable; a developer who ran `npx convex login` needs
51
+ * nothing.
52
+ */
53
+ const fromConfig = () => Layer.succeed(Credentials, Effect.cached(Config.Redacted(ACCESS_TOKEN_ENV).pipe(Effect.map((accessToken) => ({
54
+ accessToken,
55
+ source: "env"
56
+ })), Effect.catch(() => readConvexCliLogin), Effect.orDie)).pipe(Effect.flatten));
57
+ /** Explicit token, for tests or callers that already hold a value. */
58
+ const fromToken = (accessToken) => Layer.succeed(Credentials, Effect.succeed({
59
+ accessToken,
60
+ source: "explicit"
61
+ }));
62
+ //#endregion
63
+ //#region src/Adoption.ts
64
+ /** True when the resource `fqn` may take over an object that is not in state. */
65
+ const shouldAdopt = (fqn) => Effect.gen(function* () {
66
+ const stack = yield* Effect.serviceOption(Stack);
67
+ const own = Option.isSome(stack) ? stack.value.resources[fqn]?.Adopt : void 0;
68
+ if (own !== void 0) return own;
69
+ const policy = yield* Effect.serviceOption(AdoptPolicy);
70
+ if (Option.isSome(policy)) return policy.value;
71
+ const context = yield* Effect.serviceOption(AlchemyContext);
72
+ return Option.isSome(context) && context.value.adopt;
73
+ });
74
+ //#endregion
75
+ //#region src/ManagementApi.ts
76
+ /**
77
+ * One error for every control-plane and deployment call. Resources branch on
78
+ * `status` (404 means absent for read and delete), so the class is load
79
+ * bearing, not decorative.
80
+ */
81
+ var ConvexApiError = class extends Schema.TaggedError()("ConvexApiError", {
82
+ operation: Schema.String,
83
+ status: Schema.Number,
84
+ code: Schema.optionalKey(Schema.String),
85
+ message: Schema.String
86
+ }) {};
87
+ const ErrorBody = Schema.Struct({
88
+ code: Schema.optionalKey(Schema.String),
89
+ message: Schema.optionalKey(Schema.String)
90
+ });
91
+ const toApiError = (operation, result) => {
92
+ const body = Schema.decodeUnknownSync(Schema.NullishOr(ErrorBody))(result.error ?? null);
93
+ const code = body?.code;
94
+ return new ConvexApiError({
95
+ operation,
96
+ status: result.response.status,
97
+ ...code === void 0 ? {} : { code },
98
+ message: body?.message ?? `${operation} failed with HTTP ${result.response.status}`
99
+ });
100
+ };
101
+ /** The part of a Convex token after the first "|", or the whole value when it has none. */
102
+ const tokenPart = (value) => value.slice(value.indexOf("|") + 1);
103
+ var ManagementApi = class extends Context.Service()("@samebase/alchemy-convex/ManagementApi") {};
104
+ const attempt = (operation, run) => Effect.tryPromise({
105
+ try: run,
106
+ catch: (cause) => new ConvexApiError({
107
+ operation,
108
+ status: 0,
109
+ message: cause instanceof Error ? cause.message : String(cause)
110
+ })
111
+ });
112
+ /** Reads `data` or fails with the HTTP status and the API's own code and message. */
113
+ const settle = (operation, run) => attempt(operation, run).pipe(Effect.flatMap((result) => result.response.ok && result.data !== void 0 ? Effect.succeed(result.data) : Effect.fail(toApiError(operation, result))));
114
+ /** For endpoints that answer with an empty body, such as delete calls. */
115
+ const settleVoid = (operation, run) => attempt(operation, run).pipe(Effect.flatMap((result) => result.response.ok ? Effect.void : Effect.fail(toApiError(operation, result))));
116
+ /**
117
+ * True when an idempotent write can succeed on a new attempt:
118
+ *
119
+ * - A Convex write conflict. Two parallel update_environment_variables calls
120
+ * on one deployment gave HTTP 503 `OptimisticConcurrencyControlFailure`,
121
+ * "Data read or written in this mutation changed while it was being run",
122
+ * in a live run. The platform codes `OCC` and `WriteConflict` and the
123
+ * message "... changed while this mutation was being run ..." mean the same.
124
+ * - Any other 5xx answer. Two parallel delete_preview_deploy_key calls on one
125
+ * project gave HTTP 500 `InternalServerError`, "Your request couldn't be
126
+ * completed. Try again later.", in a live run. The next attempt succeeded.
127
+ */
128
+ const isRetryableWriteError = (error) => error.code === "OptimisticConcurrencyControlFailure" || error.code === "OCC" || error.code === "WriteConflict" || /changed while (it|this mutation) was being run/.test(error.message) || error.status >= 500;
129
+ /**
130
+ * Runs an idempotent write again after a retryable Convex error: at most
131
+ * four more attempts, with exponential backoff from 100 ms and jitter. Other
132
+ * errors fail at once, and so does the last retryable error. Use it only for
133
+ * a write that has the same result when it runs twice, such as setting a
134
+ * value or deleting by id. Never for a create that does not check first.
135
+ */
136
+ const retryIdempotentWrite = (effect) => effect.pipe(Effect.retry({
137
+ while: (error) => error instanceof ConvexApiError && isRetryableWriteError(error),
138
+ times: 4,
139
+ schedule: Schedule.exponential("100 millis").pipe(Schedule.jittered)
140
+ }));
141
+ /** Turns a 404 into `undefined` so read and delete stay idempotent. */
142
+ const absentAsUndefined = (effect) => effect.pipe(Effect.catchIf((error) => error.status === 404, () => Effect.succeed(void 0)));
143
+ const TeamRow = Schema.Struct({
144
+ id: Schema.Number,
145
+ slug: Schema.String
146
+ });
147
+ const TeamRows = Schema.Array(TeamRow);
148
+ const ManagementApiLive = () => Layer.effect(ManagementApi, Effect.gen(function* () {
149
+ const credentials = yield* Credentials;
150
+ const client = Effect.cached(credentials.pipe(Effect.map((resolved) => createManagementClient(Redacted.value(resolved.accessToken))))).pipe(Effect.flatten);
151
+ const request = (operation, run) => client.pipe(Effect.flatMap((c) => settle(operation, () => run(c))));
152
+ const requestVoid = (operation, run) => client.pipe(Effect.flatMap((c) => settleVoid(operation, () => run(c))));
153
+ const deploymentRequest = (operation, deploymentUrlOrName, deployKey, run) => settle(operation, () => run(createDeploymentClient(deploymentUrlOrName, Redacted.value(deployKey))));
154
+ const resolveTeamId = (team) => Effect.gen(function* () {
155
+ if (typeof team === "number") return team;
156
+ if (/^\d+$/.test(team)) return Number(team);
157
+ const resolved = yield* credentials;
158
+ const match = (yield* Effect.tryPromise({
159
+ try: async () => {
160
+ const response = await fetch("https://api.convex.dev/api/dashboard/teams", { headers: { Authorization: `Bearer ${Redacted.value(resolved.accessToken)}` } });
161
+ if (!response.ok) throw new Error(`team lookup for "${team}" failed with HTTP ${response.status}`);
162
+ return Schema.decodeUnknownSync(TeamRows)(await response.json());
163
+ },
164
+ catch: (cause) => new ConvexApiError({
165
+ operation: "resolve team",
166
+ status: 0,
167
+ message: cause instanceof Error ? cause.message : String(cause)
168
+ })
169
+ })).find((row) => row.slug === team);
170
+ if (match === void 0) return yield* new ConvexApiError({
171
+ operation: "resolve team",
172
+ status: 404,
173
+ message: `no team with slug "${team}" for this token`
174
+ });
175
+ return match.id;
176
+ });
177
+ const isCredentialToken = (secret) => credentials.pipe(Effect.map((resolved) => tokenPart(Redacted.value(resolved.accessToken)) === tokenPart(secret)));
178
+ return {
179
+ request,
180
+ requestVoid,
181
+ deploymentRequest,
182
+ resolveTeamId,
183
+ isCredentialToken
184
+ };
185
+ }));
186
+ //#endregion
187
+ //#region src/EnvironmentVariable.ts
188
+ /**
189
+ * The variable's identity when the listing has `name`. Own keys only: a
190
+ * valid variable name such as `toString` must not match the object prototype.
191
+ */
192
+ const findVariable = (list, deployment, name) => Object.hasOwn(list.environmentVariables, name) ? {
193
+ deployment,
194
+ name
195
+ } : void 0;
196
+ /**
197
+ * One attempt to set one variable, or to remove it when `value` is null. The
198
+ * deployment answers 200 with an empty body, so this reads no response data.
199
+ */
200
+ const writeVariable = (deployment, deployKey, name, value) => settleVoid("update environment variables", () => createDeploymentClient(deployment, Redacted.value(deployKey)).POST("/update_environment_variables", { body: { changes: [{
201
+ name,
202
+ value: Redacted.isRedacted(value) ? Redacted.value(value) : value
203
+ }] } }));
204
+ /**
205
+ * Sets one variable, or removes it when `value` is null. The call sets a
206
+ * value, so it runs again after a write conflict or a 5xx answer, for example
207
+ * when another resource writes a variable of the same deployment at the same
208
+ * time. Use it only where the variable is already ours to set.
209
+ */
210
+ const updateVariable = (deployment, deployKey, name, value) => retryIdempotentWrite(writeVariable(deployment, deployKey, name, value));
211
+ /** GET https://<deployment>.convex.cloud/api/v1/list_environment_variables */
212
+ const EnvironmentVariableList = Schema.Struct({ environmentVariables: Schema.Record(Schema.String, Schema.String) });
213
+ /** The variable's identity, or undefined when the variable or the deployment is absent. */
214
+ const readVariable = (api, deployment, deployKey, name) => absentAsUndefined(api.deploymentRequest("list environment variables", deployment, deployKey, (client) => client.GET("/list_environment_variables"))).pipe(Effect.map((body) => body === void 0 ? void 0 : findVariable(Schema.decodeUnknownSync(EnvironmentVariableList)(body), deployment, name)));
215
+ const EnvironmentVariable = Resource("Convex.EnvironmentVariable");
216
+ /**
217
+ * The props name another variable than the one in state. Used by
218
+ * Convex.EnvironmentVariable and Convex.DefaultEnvironmentVariable.
219
+ */
220
+ var VariableIdentityChange = class extends Schema.TaggedError()("VariableIdentityChange", {
221
+ resourceType: Schema.String,
222
+ field: Schema.Literals([
223
+ "name",
224
+ "deployment",
225
+ "projectId",
226
+ "deploymentType"
227
+ ]),
228
+ current: Schema.String,
229
+ requested: Schema.String
230
+ }) {
231
+ get message() {
232
+ return `${this.resourceType} cannot change its ${this.field} from ${this.current} to ${this.requested}. Create a new resource with a new logical id for the new name or deployment, and remove this one.`;
233
+ }
234
+ };
235
+ /** Fails with {@link VariableIdentityChange} when the props name another variable than the one in state. */
236
+ const checkIdentity$1 = (output, news) => output.name !== news.name ? Effect.fail(new VariableIdentityChange({
237
+ resourceType: EnvironmentVariable.Type,
238
+ field: "name",
239
+ current: output.name,
240
+ requested: news.name
241
+ })) : output.deployment !== news.deployment ? Effect.fail(new VariableIdentityChange({
242
+ resourceType: EnvironmentVariable.Type,
243
+ field: "deployment",
244
+ current: output.deployment,
245
+ requested: news.deployment
246
+ })) : Effect.void;
247
+ /**
248
+ * The deploy key for the variable in state: from the attributes, or, for
249
+ * state from 0.1.x, from props that name the same deployment.
250
+ */
251
+ const keyOf = (output, olds) => output.deployKey ?? (olds?.deployment === output.deployment ? olds.deployKey : void 0);
252
+ const EnvironmentVariableProvider = () => Provider.effect(EnvironmentVariable, Effect.gen(function* () {
253
+ const api = yield* ManagementApi;
254
+ return {
255
+ diff: Effect.fn(function* ({ news, output }) {
256
+ if (!isResolved(news) || output === void 0) return void 0;
257
+ yield* checkIdentity$1(output, news);
258
+ }),
259
+ read: Effect.fn(function* ({ olds, output }) {
260
+ if (output !== void 0) {
261
+ const key = keyOf(output, olds);
262
+ if (key === void 0) return output;
263
+ return (yield* readVariable(api, output.deployment, key, output.name)) === void 0 ? void 0 : output;
264
+ }
265
+ const found = yield* readVariable(api, olds.deployment, olds.deployKey, olds.name);
266
+ return found === void 0 ? void 0 : Unowned({
267
+ ...found,
268
+ deployKey: olds.deployKey
269
+ });
270
+ }),
271
+ reconcile: Effect.fn(function* ({ fqn, news, output }) {
272
+ if (output !== void 0) yield* checkIdentity$1(output, news);
273
+ const write = writeVariable(news.deployment, news.deployKey, news.name, news.value);
274
+ if (output !== void 0 || (yield* shouldAdopt(fqn))) yield* retryIdempotentWrite(write);
275
+ else yield* retryIdempotentWrite(Effect.gen(function* () {
276
+ if ((yield* readVariable(api, news.deployment, news.deployKey, news.name)) !== void 0) return yield* new OwnedBySomeoneElse({
277
+ message: `Environment variable ${news.name} already exists on deployment ${news.deployment}. Re-run with --adopt to take it over and overwrite its value, or use a different name.`,
278
+ resourceType: EnvironmentVariable.Type,
279
+ physicalName: news.name
280
+ });
281
+ yield* write;
282
+ }));
283
+ return {
284
+ deployment: news.deployment,
285
+ name: news.name,
286
+ deployKey: news.deployKey
287
+ };
288
+ }),
289
+ delete: Effect.fn(function* ({ olds, output }) {
290
+ const key = keyOf(output, olds);
291
+ if (key === void 0) {
292
+ yield* Effect.logWarning(`Environment variable ${output.name} on deployment ${output.deployment} stays: Alchemy has no deploy key for that deployment. Remove it in the Convex dashboard.`);
293
+ return;
294
+ }
295
+ yield* absentAsUndefined(updateVariable(output.deployment, key, output.name, null));
296
+ })
297
+ };
298
+ }));
299
+ //#endregion
300
+ //#region src/DefaultEnvironmentVariable.ts
301
+ /**
302
+ * Attributes when the listing has `name` for `deploymentType`. An unfiltered
303
+ * listing merges the deployment types that share one value into one row, so
304
+ * the match checks membership in `deploymentTypes`.
305
+ */
306
+ const findDefault = (list, projectId, name, deploymentType) => list.items.some((item) => item.name === name && item.deploymentTypes.includes(deploymentType)) ? {
307
+ projectId,
308
+ name,
309
+ deploymentType
310
+ } : void 0;
311
+ /**
312
+ * Lists the defaults named `name` for `deploymentType`. Convex filters on
313
+ * both, so the listing has at most one row and needs no pagination.
314
+ */
315
+ const listDefaults = (api, projectId, name, deploymentType) => api.request("list default environment variables", (client) => client.GET("/projects/{project_id}/list_default_environment_variables", { params: {
316
+ path: { project_id: projectId },
317
+ query: {
318
+ name,
319
+ deploymentType
320
+ }
321
+ } })).pipe(Effect.map((body) => Schema.decodeUnknownSync(DefaultEnvironmentVariableList)(body)));
322
+ /** One attempt to set one default, or to remove it when `value` is null. */
323
+ const writeDefault = (api, projectId, name, deploymentType, value) => api.requestVoid("update default environment variables", (client) => client.POST("/projects/{project_id}/update_default_environment_variables", {
324
+ params: { path: { project_id: projectId } },
325
+ body: { changes: [{
326
+ name,
327
+ deploymentType,
328
+ value: Redacted.isRedacted(value) ? Redacted.value(value) : value
329
+ }] }
330
+ }));
331
+ /**
332
+ * Sets one default, or removes it when `value` is null. Convex answers 200
333
+ * with an empty body, so this reads no response data. The call sets a value,
334
+ * so it runs again after a write conflict or a 5xx answer, for example when
335
+ * another resource writes a default of the same project at the same time.
336
+ */
337
+ const updateDefault = (api, projectId, name, deploymentType, value) => retryIdempotentWrite(writeDefault(api, projectId, name, deploymentType, value));
338
+ /** The default's identity, or undefined when the default or the project is absent. */
339
+ const readDefault = (api, projectId, name, deploymentType) => absentAsUndefined(listDefaults(api, projectId, name, deploymentType)).pipe(Effect.map((list) => list === void 0 ? void 0 : findDefault(list, projectId, name, deploymentType)));
340
+ /**
341
+ * GET /projects/{project_id}/list_default_environment_variables. Only the
342
+ * fields the provider uses: the row's `value` is the secret in plain text.
343
+ */
344
+ const DefaultEnvironmentVariableList = Schema.Struct({ items: Schema.Array(Schema.Struct({
345
+ name: Schema.String,
346
+ deploymentTypes: Schema.Array(Schema.String)
347
+ })) });
348
+ const DefaultEnvironmentVariable = Resource("Convex.DefaultEnvironmentVariable");
349
+ /** Fails with VariableIdentityChange when the props name another default than the one in state. */
350
+ const checkIdentity = (output, news) => {
351
+ const changed = output.projectId !== news.projectId ? {
352
+ field: "projectId",
353
+ current: `${output.projectId}`,
354
+ requested: `${news.projectId}`
355
+ } : output.name !== news.name ? {
356
+ field: "name",
357
+ current: output.name,
358
+ requested: news.name
359
+ } : output.deploymentType !== news.deploymentType ? {
360
+ field: "deploymentType",
361
+ current: output.deploymentType,
362
+ requested: news.deploymentType
363
+ } : void 0;
364
+ return changed === void 0 ? Effect.void : Effect.fail(new VariableIdentityChange({
365
+ resourceType: DefaultEnvironmentVariable.Type,
366
+ ...changed
367
+ }));
368
+ };
369
+ const DefaultEnvironmentVariableProvider = () => Provider.effect(DefaultEnvironmentVariable, Effect.gen(function* () {
370
+ const api = yield* ManagementApi;
371
+ return {
372
+ diff: Effect.fn(function* ({ news, output }) {
373
+ if (!isResolved(news) || output === void 0) return void 0;
374
+ yield* checkIdentity(output, news);
375
+ }),
376
+ read: Effect.fn(function* ({ olds, output }) {
377
+ const at = output ?? olds;
378
+ const found = yield* readDefault(api, at.projectId, at.name, at.deploymentType);
379
+ if (found === void 0) return void 0;
380
+ return output ?? Unowned(found);
381
+ }),
382
+ reconcile: Effect.fn(function* ({ fqn, news, output }) {
383
+ if (output !== void 0) yield* checkIdentity(output, news);
384
+ const write = writeDefault(api, news.projectId, news.name, news.deploymentType, news.value);
385
+ if (output !== void 0 || (yield* shouldAdopt(fqn))) yield* retryIdempotentWrite(write);
386
+ else yield* retryIdempotentWrite(Effect.gen(function* () {
387
+ if ((yield* readDefault(api, news.projectId, news.name, news.deploymentType)) !== void 0) return yield* new OwnedBySomeoneElse({
388
+ message: `Project ${news.projectId} already has a ${news.deploymentType} default environment variable ${news.name}. Re-run with --adopt to take it over and overwrite its value, or use a different name.`,
389
+ resourceType: DefaultEnvironmentVariable.Type,
390
+ physicalName: news.name
391
+ });
392
+ yield* write;
393
+ }));
394
+ return {
395
+ projectId: news.projectId,
396
+ name: news.name,
397
+ deploymentType: news.deploymentType
398
+ };
399
+ }),
400
+ delete: Effect.fn(function* ({ output }) {
401
+ yield* absentAsUndefined(updateDefault(api, output.projectId, output.name, output.deploymentType, null));
402
+ })
403
+ };
404
+ }));
405
+ //#endregion
406
+ //#region src/Deploy.ts
407
+ const Deploy = Resource("Convex.Deploy");
408
+ /**
409
+ * The CLI prints this line with `logFinishedStep` after the push succeeds, to
410
+ * stderr (convex 1.45 `cli/lib/deploy2.js` for existing deployments,
411
+ * `cli/deploy.js` for preview deployments). The host is
412
+ * `<deployment>.convex.cloud` or `<deployment>.<region>.convex.cloud`.
413
+ */
414
+ const DEPLOYED_LINE = /Deployed Convex functions to (https:\/\/([a-z0-9]+(?:-[a-z0-9]+)*)(?:\.[a-z0-9]+(?:-[a-z0-9]+)*)?\.convex\.cloud)\/?(?=\s|$)/m;
415
+ /** Reads the deployment URL from `convex deploy` output. ANSI escape codes are removed first. */
416
+ const parseDeployOutput = (text) => {
417
+ const match = DEPLOYED_LINE.exec(stripVTControlCharacters(text));
418
+ const url = match?.[1];
419
+ const deploymentName = match?.[2];
420
+ return url === void 0 || deploymentName === void 0 ? void 0 : {
421
+ url,
422
+ deploymentName
423
+ };
424
+ };
425
+ /** The `convex deploy` argv, starting with `npx`. */
426
+ const deployArgs = (props) => [
427
+ "npx",
428
+ "convex",
429
+ "deploy",
430
+ ...props.previewName === void 0 ? [] : ["--preview-name", props.previewName],
431
+ ...props.previewCreate === void 0 ? [] : ["--preview-create", props.previewCreate],
432
+ ...props.previewRun === void 0 ? [] : ["--preview-run", props.previewRun],
433
+ ...props.extraArgs ?? []
434
+ ];
435
+ /** A `convex deploy` argument contains whitespace, which Alchemy's command runner splits on. */
436
+ var DeployArgumentError = class extends Schema.TaggedError()("DeployArgumentError", { argument: Schema.String }) {
437
+ get message() {
438
+ return `Convex.Deploy argument "${this.argument}" contains whitespace, and Alchemy splits the command on whitespace. Use the --flag=value form, such as --typecheck=disable, and names without spaces.`;
439
+ }
440
+ };
441
+ /** `npx convex deploy` exited 0 but did not print the deployment URL. */
442
+ var DeployOutputError = class extends Schema.TaggedError()("DeployOutputError", { outputTail: Schema.String }) {
443
+ get message() {
444
+ return `npx convex deploy exited 0 but printed no "Deployed Convex functions to <url>" line, so Convex.Deploy has no deployment URL. Remove --dry-run from extraArgs if it is there, and read the CLI output. Last output:\n${this.outputTail}`;
445
+ }
446
+ };
447
+ const DeployProvider = () => Provider.effect(Deploy, Effect.gen(function* () {
448
+ const { run } = yield* CommandExecutor;
449
+ const hashOf = (props) => props.memo === false ? Effect.succeed(void 0) : hashDirectory({
450
+ ...props.cwd === void 0 ? {} : { cwd: props.cwd },
451
+ memo: props.memo === true || props.memo === void 0 ? {} : props.memo
452
+ });
453
+ return {
454
+ diff: Effect.fn(function* ({ olds, news, output }) {
455
+ if (!isResolved(news)) return void 0;
456
+ if (news.previewName !== void 0 || news.previewCreate !== void 0 || output === void 0 || output.hash === void 0 || havePropsChanged(olds, news)) return { action: "update" };
457
+ return { action: (yield* hashOf(news)) === output.hash ? "noop" : "update" };
458
+ }),
459
+ reconcile: Effect.fn(function* ({ news, session }) {
460
+ const args = deployArgs(news);
461
+ const spaced = args.find((arg) => /\s/.test(arg));
462
+ if (spaced !== void 0) return yield* new DeployArgumentError({ argument: spaced });
463
+ const { stdout, stderr } = yield* run({
464
+ command: args.join(" "),
465
+ ...news.cwd === void 0 ? {} : { cwd: news.cwd },
466
+ ...news.timeout === void 0 ? {} : { timeout: news.timeout },
467
+ env: {
468
+ ...news.env,
469
+ CONVEX_DEPLOY_KEY: news.deployKey
470
+ }
471
+ }, session);
472
+ const output = `${stdout}\n${stderr}`;
473
+ const deployed = parseDeployOutput(output);
474
+ if (deployed === void 0) return yield* new DeployOutputError({ outputTail: stripVTControlCharacters(output).split(/\r?\n|\r/).filter((line) => line.trim() !== "").slice(-20).join("\n") });
475
+ return {
476
+ ...deployed,
477
+ hash: yield* hashOf(news)
478
+ };
479
+ }),
480
+ delete: () => Effect.void
481
+ };
482
+ }));
483
+ //#endregion
484
+ //#region src/DeployKey.ts
485
+ /**
486
+ * True when `listedName` is how Convex lists a key created as `name`: the
487
+ * requested name itself, or the requested name, a space, and one
488
+ * parenthesized suffix without spaces. The suffix check keeps `my-key` from
489
+ * matching a key created as `my-key (old)`.
490
+ */
491
+ const isListedAs = (listedName, name) => {
492
+ const prefix = `${name} (`;
493
+ return listedName === name || listedName.startsWith(prefix) && /^[^\s()]+\)$/.test(listedName.slice(prefix.length));
494
+ };
495
+ /**
496
+ * True when the listing still has the key in state: by numeric id, or by
497
+ * listed name for state written by 0.1.x, which has no id.
498
+ */
499
+ const isKeyListed = (entries, key) => entries.some((entry) => key.keyId === void 0 ? entry.name === key.uniqueName : entry.id === key.keyId);
500
+ /** The listed keys that Convex shows for a key created as `name`. */
501
+ const keysListedAs = (entries, name) => entries.filter((entry) => isListedAs(entry.name, name));
502
+ /**
503
+ * The name that a resource instance requests: `name`, a dash, and the first
504
+ * 12 hex characters of sha256("<fqn>:<instanceId>"). Two resources, or the
505
+ * old and the new generation of one replaced resource, never request the
506
+ * same name. Pattern from Confect `packages/alchemy/src/internal/ResourceIdentity.ts`
507
+ * (https://github.com/rjdellecese/confect, ISC license).
508
+ */
509
+ const requestedKeyName = (name, fqn, instanceId) => `${name}-${createHash("sha256").update(`${fqn}:${instanceId}`).digest("hex").slice(0, 12)}`;
510
+ /** One row of list_deploy_keys and list_preview_deploy_keys. Only the fields the providers use. */
511
+ const ListedKey = Schema.Struct({
512
+ id: Schema.Number,
513
+ name: Schema.String
514
+ });
515
+ /** GET /deployments/{deployment_name}/list_deploy_keys */
516
+ const DeployKeyList = Schema.Array(ListedKey);
517
+ /** POST /deployments/{deployment_name}/create_deploy_key */
518
+ const CreatedDeployKey = Schema.Struct({ deployKey: Schema.String });
519
+ /**
520
+ * A key cannot be tied to one resource: before the create, listed keys
521
+ * already have the requested name, or after the create, not exactly one has it.
522
+ */
523
+ var DeployKeyRecoveryRequired = class extends Schema.TaggedError()("DeployKeyRecoveryRequired", {
524
+ /** Where the keys live, such as `deployment happy-otter-123` or `project 3145389`. */
525
+ target: Schema.String,
526
+ /** The requested name. */
527
+ name: Schema.String,
528
+ /** The listed keys with the requested name. */
529
+ keys: Schema.Array(ListedKey),
530
+ /** True when this run created a key before the listing check failed. */
531
+ afterCreate: Schema.Boolean
532
+ }) {
533
+ get message() {
534
+ const listed = this.keys.length === 0 ? "no key" : this.keys.map((key) => `"${key.name}" (id ${key.id})`).join(", ");
535
+ return this.afterCreate ? `Convex created deploy key "${this.name}" on ${this.target}, but the listing shows ${listed} with that name, not exactly one, so this resource cannot track the new key. Alchemy does not revoke it. Delete the keys with that name in the Convex dashboard, then run the deploy again.` : `${this.target} already lists ${listed} with the name "${this.name}", but Alchemy state has no such key. An interrupted run probably created it, and its secret is lost. Delete these keys in the Convex dashboard, then run the deploy again.`;
536
+ }
537
+ };
538
+ /**
539
+ * Convex returned the Management API credential itself as the new key. This
540
+ * happens with an OAuth token: Convex creates no key. A delete of the
541
+ * returned secret would revoke the credential, so the resource does not keep it.
542
+ */
543
+ var DeployKeyIsCredential = class extends Schema.TaggedError()("DeployKeyIsCredential", {
544
+ target: Schema.String,
545
+ name: Schema.String
546
+ }) {
547
+ get message() {
548
+ return `Convex returned the Management API credential itself as deploy key "${this.name}" on ${this.target}. With an OAuth token, Convex creates no new key, and deleting the returned key would revoke the OAuth token. Alchemy does not keep it. Use a team access token in CONVEX_ACCESS_TOKEN, or the Convex CLI login.`;
549
+ }
550
+ };
551
+ /**
552
+ * Creates a key named `name` and ties it to the caller. Fails before the
553
+ * create when keys with that name already exist. After the create, fails
554
+ * when the secret is the Management API credential itself, or when the
555
+ * listing does not show exactly one key with that name. It never revokes a
556
+ * key: the returned secret can be a shared credential.
557
+ */
558
+ const createTrackedKey = (options) => Effect.gen(function* () {
559
+ const { target, name } = options;
560
+ const existing = keysListedAs(yield* options.list, name);
561
+ if (existing.length > 0) return yield* new DeployKeyRecoveryRequired({
562
+ target,
563
+ name,
564
+ keys: existing,
565
+ afterCreate: false
566
+ });
567
+ const secret = yield* options.create;
568
+ if (yield* options.isCredentialToken(secret)) return yield* new DeployKeyIsCredential({
569
+ target,
570
+ name
571
+ });
572
+ const listed = keysListedAs(yield* options.list, name);
573
+ const [only] = listed;
574
+ if (only === void 0 || listed.length !== 1) return yield* new DeployKeyRecoveryRequired({
575
+ target,
576
+ name,
577
+ keys: listed,
578
+ afterCreate: true
579
+ });
580
+ return {
581
+ keyId: only.id,
582
+ uniqueName: only.name,
583
+ secret: Redacted.make(secret)
584
+ };
585
+ });
586
+ /**
587
+ * The secret to send to a delete call, or undefined when a delete is not
588
+ * safe. Only a key with a `keyId` in state is known to be a new key that
589
+ * this resource owns: createTrackedKey found exactly one new listed key, and
590
+ * the secret was not the credential. State from 0.1.x has no `keyId`, and its
591
+ * secret can be an OAuth token that Convex returned as a key, so a delete
592
+ * could revoke that OAuth token. Such a key stays, and a warning names it.
593
+ */
594
+ const secretToDelete = (key, label) => Effect.gen(function* () {
595
+ if (key.keyId === void 0 || !Redacted.isRedacted(key.secret)) {
596
+ yield* Effect.logWarning(`${label} has no verified key id and secret in state (state from 0.1.x, for example), so Alchemy does not delete it. Delete it in the Convex dashboard.`);
597
+ return;
598
+ }
599
+ return Redacted.value(key.secret);
600
+ });
601
+ const DeployKey = Resource("Convex.DeployKey");
602
+ const DeployKeyProvider = () => Provider.effect(DeployKey, Effect.gen(function* () {
603
+ const api = yield* ManagementApi;
604
+ const listKeys = (deployment) => api.request("list deploy keys", (client) => client.GET("/deployments/{deployment_name}/list_deploy_keys", { params: { path: { deployment_name: deployment } } })).pipe(Effect.map((body) => Schema.decodeUnknownSync(DeployKeyList)(body)));
605
+ /**
606
+ * `id` is the secret: Convex accepts it, and it matches only the key
607
+ * that this resource created. A second delete answers 404.
608
+ */
609
+ const deleteKey = (deployment, secret) => retryIdempotentWrite(api.requestVoid("delete deploy key", (client) => client.POST("/deployments/{deployment_name}/delete_deploy_key", {
610
+ params: { path: { deployment_name: deployment } },
611
+ body: { id: secret }
612
+ })));
613
+ return {
614
+ stables: ["uniqueName", "deployment"],
615
+ diff: ({ olds, news, output }) => {
616
+ if (!isResolved(news)) return Effect.succeed(void 0);
617
+ return Effect.succeed(output !== void 0 && output.deployKey === void 0 || havePropsChanged(olds, news) ? { action: "replace" } : { action: "noop" });
618
+ },
619
+ read: Effect.fn(function* ({ output }) {
620
+ if (output === void 0) return void 0;
621
+ const entries = yield* absentAsUndefined(listKeys(output.deployment));
622
+ return entries !== void 0 && isKeyListed(entries, output) ? output : void 0;
623
+ }),
624
+ reconcile: Effect.fn(function* ({ fqn, instanceId, news, output }) {
625
+ if (output !== void 0) {
626
+ if (isKeyListed(yield* listKeys(news.deployment), output)) return output;
627
+ }
628
+ const name = requestedKeyName(news.name, fqn, instanceId);
629
+ const { keyId, uniqueName, secret } = yield* createTrackedKey({
630
+ target: `deployment ${news.deployment}`,
631
+ name,
632
+ list: listKeys(news.deployment),
633
+ create: api.request("create deploy key", (client) => client.POST("/deployments/{deployment_name}/create_deploy_key", {
634
+ params: { path: { deployment_name: news.deployment } },
635
+ body: {
636
+ name,
637
+ ...news.allowedActions === void 0 ? {} : { allowedActions: [...news.allowedActions] }
638
+ }
639
+ })).pipe(Effect.map((body) => Schema.decodeUnknownSync(CreatedDeployKey)(body).deployKey)),
640
+ isCredentialToken: api.isCredentialToken
641
+ });
642
+ return {
643
+ uniqueName,
644
+ keyId,
645
+ deployment: news.deployment,
646
+ deployKey: secret
647
+ };
648
+ }),
649
+ delete: Effect.fn(function* ({ output }) {
650
+ const secret = yield* secretToDelete({
651
+ keyId: output.keyId,
652
+ secret: output.deployKey
653
+ }, `Convex.DeployKey "${output.uniqueName}" on ${output.deployment}`);
654
+ if (secret === void 0) return;
655
+ yield* absentAsUndefined(deleteKey(output.deployment, secret));
656
+ })
657
+ };
658
+ }));
659
+ //#endregion
660
+ //#region src/PreviewDeployKey.ts
661
+ /** GET /projects/{project_id}/list_preview_deploy_keys */
662
+ const PreviewDeployKeyList = Schema.Struct({ items: Schema.Array(ListedKey) });
663
+ /** POST /projects/{project_id}/create_preview_deploy_key */
664
+ const CreatedPreviewDeployKey = Schema.Struct({ previewDeployKey: Schema.String });
665
+ const PreviewDeployKey = Resource("Convex.PreviewDeployKey");
666
+ const PreviewDeployKeyProvider = () => Provider.effect(PreviewDeployKey, Effect.gen(function* () {
667
+ const api = yield* ManagementApi;
668
+ const listKeys = (projectId) => api.request("list preview deploy keys", (client) => client.GET("/projects/{project_id}/list_preview_deploy_keys", { params: { path: { project_id: projectId } } })).pipe(Effect.map((body) => Schema.decodeUnknownSync(PreviewDeployKeyList)(body).items));
669
+ /**
670
+ * `id` is the secret: Convex accepts it, and it matches only the key
671
+ * that this resource created. A second delete answers 404.
672
+ */
673
+ const deleteKey = (projectId, secret) => retryIdempotentWrite(api.requestVoid("delete preview deploy key", (client) => client.POST("/projects/{project_id}/delete_preview_deploy_key", {
674
+ params: { path: { project_id: projectId } },
675
+ body: { id: secret }
676
+ })));
677
+ return {
678
+ stables: ["uniqueName", "projectId"],
679
+ diff: ({ olds, news, output }) => {
680
+ if (!isResolved(news)) return Effect.succeed(void 0);
681
+ return Effect.succeed(output !== void 0 && output.previewDeployKey === void 0 || havePropsChanged(olds, news) ? { action: "replace" } : { action: "noop" });
682
+ },
683
+ read: Effect.fn(function* ({ output }) {
684
+ if (output === void 0) return void 0;
685
+ const entries = yield* absentAsUndefined(listKeys(output.projectId));
686
+ return entries !== void 0 && isKeyListed(entries, output) ? output : void 0;
687
+ }),
688
+ reconcile: Effect.fn(function* ({ fqn, instanceId, news, output }) {
689
+ if (output !== void 0) {
690
+ if (isKeyListed(yield* listKeys(news.projectId), output)) return output;
691
+ }
692
+ const name = requestedKeyName(news.name, fqn, instanceId);
693
+ const { keyId, uniqueName, secret } = yield* createTrackedKey({
694
+ target: `project ${news.projectId}`,
695
+ name,
696
+ list: listKeys(news.projectId),
697
+ create: api.request("create preview deploy key", (client) => client.POST("/projects/{project_id}/create_preview_deploy_key", {
698
+ params: { path: { project_id: news.projectId } },
699
+ body: { name }
700
+ })).pipe(Effect.map((body) => Schema.decodeUnknownSync(CreatedPreviewDeployKey)(body).previewDeployKey)),
701
+ isCredentialToken: api.isCredentialToken
702
+ });
703
+ return {
704
+ uniqueName,
705
+ keyId,
706
+ projectId: news.projectId,
707
+ previewDeployKey: secret
708
+ };
709
+ }),
710
+ delete: Effect.fn(function* ({ output }) {
711
+ const secret = yield* secretToDelete({
712
+ keyId: output.keyId,
713
+ secret: output.previewDeployKey
714
+ }, `Convex.PreviewDeployKey "${output.uniqueName}" in project ${output.projectId}`);
715
+ if (secret === void 0) return;
716
+ yield* absentAsUndefined(deleteKey(output.projectId, secret));
717
+ })
718
+ };
719
+ }));
720
+ //#endregion
721
+ //#region src/Project.ts
722
+ const Project = Resource("Convex.Project", { defaultRemovalPolicy: "retain" });
723
+ /** The props change the team of an existing project. Convex cannot move a project. */
724
+ var ProjectTeamChange = class extends Schema.TaggedError()("ProjectTeamChange", {
725
+ projectId: Schema.Number,
726
+ teamId: Schema.Number,
727
+ requestedTeamId: Schema.Number
728
+ }) {
729
+ get message() {
730
+ return `Convex.Project cannot move project ${this.projectId} from team ${this.teamId} to team ${this.requestedTeamId}. Set team back to ${this.teamId}. To use the other team, create a new resource with a new logical id and move the data yourself.`;
731
+ }
732
+ };
733
+ /**
734
+ * The props change `deploymentType` or `deploymentRegion` of an existing
735
+ * project. Convex uses them only when it creates the project.
736
+ */
737
+ var ProjectDeploymentChange = class extends Schema.TaggedError()("ProjectDeploymentChange", {
738
+ projectId: Schema.Number,
739
+ field: Schema.Literals(["deploymentType", "deploymentRegion"]),
740
+ current: Schema.UndefinedOr(Schema.String),
741
+ requested: Schema.UndefinedOr(Schema.String)
742
+ }) {
743
+ get message() {
744
+ const show = (value) => value === void 0 ? "(not set)" : value;
745
+ return `Convex.Project cannot change ${this.field} of project ${this.projectId} from ${show(this.current)} to ${show(this.requested)}: Convex uses it only when it creates a project. Set ${this.field} back to ${show(this.current)}. For a new deployment, create a new resource with a new logical id and move the data yourself.`;
746
+ }
747
+ };
748
+ /** More than one project in the team has the name, so the lookup cannot choose one. */
749
+ var AmbiguousProject = class extends Schema.TaggedError()("AmbiguousProject", {
750
+ teamId: Schema.Number,
751
+ name: Schema.String,
752
+ projectIds: Schema.Array(Schema.Number)
753
+ }) {
754
+ get message() {
755
+ return `Team ${this.teamId} has ${this.projectIds.length} projects named "${this.name}" (ids ${this.projectIds.join(", ")}). Convex.Project does not choose one. Rename the projects in the Convex dashboard so that only one has this name, or use a different name.`;
756
+ }
757
+ };
758
+ /** Convex answered a create call but then did not return the project. */
759
+ var CreatedProjectNotFound = class extends Schema.TaggedError()("CreatedProjectNotFound", { projectId: Schema.Number }) {
760
+ get message() {
761
+ return `Convex created project ${this.projectId} but GET /projects/${this.projectId} did not return it. Run the deploy again with --adopt to take over project ${this.projectId}.`;
762
+ }
763
+ };
764
+ /** Fields of GET /projects/{id}, PATCH /projects/{id}, and GET /teams/{team}/projects rows that the provider uses. */
765
+ const ProjectDetails = Schema.Struct({
766
+ id: Schema.Number,
767
+ name: Schema.String,
768
+ slug: Schema.String,
769
+ teamId: Schema.Number,
770
+ prodDeploymentName: Schema.NullOr(Schema.String)
771
+ });
772
+ /** GET /teams/{team_id}/projects: one page of projects. */
773
+ const ProjectPage = Schema.Struct({
774
+ items: Schema.Array(ProjectDetails),
775
+ pagination: Schema.Struct({
776
+ hasMore: Schema.Boolean,
777
+ nextCursor: Schema.optionalKey(Schema.NullOr(Schema.String))
778
+ })
779
+ });
780
+ /** POST /teams/{team_id}/create_project. Only the id: everything else comes from GET /projects/{id}. */
781
+ const CreatedProject = Schema.Struct({ projectId: Schema.Number });
782
+ const DeploymentRow = Schema.Struct({
783
+ name: Schema.String,
784
+ deploymentType: Schema.String,
785
+ isDefault: Schema.Boolean,
786
+ deploymentUrl: Schema.String
787
+ });
788
+ const DeploymentRows = Schema.Array(DeploymentRow);
789
+ /**
790
+ * Fails with {@link ProjectDeploymentChange} when a create-time prop
791
+ * changed. An omitted `deploymentType` means `prod`.
792
+ */
793
+ const checkCreateTimeProps = (projectId, olds, news) => {
794
+ const oldType = olds.deploymentType ?? "prod";
795
+ const newType = news.deploymentType ?? "prod";
796
+ if (oldType !== newType) return Effect.fail(new ProjectDeploymentChange({
797
+ projectId,
798
+ field: "deploymentType",
799
+ current: oldType,
800
+ requested: newType
801
+ }));
802
+ if (olds.deploymentRegion !== news.deploymentRegion) return Effect.fail(new ProjectDeploymentChange({
803
+ projectId,
804
+ field: "deploymentRegion",
805
+ current: olds.deploymentRegion,
806
+ requested: news.deploymentRegion
807
+ }));
808
+ return Effect.void;
809
+ };
810
+ const ProjectProvider = () => Provider.effect(Project, Effect.gen(function* () {
811
+ const api = yield* ManagementApi;
812
+ const prodDeployment = (projectId) => api.request("list deployments", (client) => client.GET("/projects/{project_id}/list_deployments", { params: { path: { project_id: projectId } } })).pipe(Effect.map((rows) => Schema.decodeUnknownSync(DeploymentRows)(rows).find((row) => row.deploymentType === "prod" && row.isDefault)));
813
+ const attributesOf = (details) => prodDeployment(details.id).pipe(Effect.map((prod) => ({
814
+ projectId: details.id,
815
+ slug: details.slug,
816
+ name: details.name,
817
+ teamId: details.teamId,
818
+ prodDeploymentName: prod?.name ?? details.prodDeploymentName ?? void 0,
819
+ prodDeploymentUrl: prod?.deploymentUrl
820
+ })));
821
+ const getById = (projectId) => absentAsUndefined(api.request("get project", (client) => client.GET("/projects/{project_id}", { params: { path: { project_id: projectId } } }))).pipe(Effect.map((body) => body === void 0 ? void 0 : Schema.decodeUnknownSync(ProjectDetails)(body)));
822
+ /**
823
+ * The one project in the team with exactly this name, or undefined.
824
+ * Reads every page. `q` narrows the listing on the server, and the
825
+ * exact match here decides. Pattern from Confect
826
+ * `packages/alchemy/src/ConvexClient.ts` and `Project.ts`
827
+ * (https://github.com/rjdellecese/confect, ISC license).
828
+ */
829
+ const findByName = (teamId, name) => Effect.gen(function* () {
830
+ const matches = [];
831
+ const seenCursors = /* @__PURE__ */ new Set();
832
+ let cursor;
833
+ while (true) {
834
+ const body = yield* api.request("list projects", (client) => client.GET("/teams/{team_id}/projects", { params: {
835
+ path: { team_id: teamId },
836
+ query: {
837
+ q: name,
838
+ ...cursor === void 0 ? {} : { cursor }
839
+ }
840
+ } }));
841
+ const page = Schema.decodeUnknownSync(ProjectPage)(body);
842
+ matches.push(...page.items.filter((row) => row.name === name));
843
+ if (!page.pagination.hasMore) break;
844
+ const next = page.pagination.nextCursor;
845
+ if (next === void 0 || next === null || seenCursors.has(next)) return yield* new ConvexApiError({
846
+ operation: "list projects",
847
+ status: 0,
848
+ code: "InvalidPagination",
849
+ message: `The project listing of team ${teamId} reports more pages but gives no new cursor. Convex.Project stops so that it does not miss a project named "${name}".`
850
+ });
851
+ seenCursors.add(next);
852
+ cursor = next;
853
+ }
854
+ if (matches.length > 1) return yield* new AmbiguousProject({
855
+ teamId,
856
+ name,
857
+ projectIds: matches.map((row) => row.id)
858
+ });
859
+ return matches[0];
860
+ });
861
+ /**
862
+ * Brings an existing project to the desired name. The team cannot
863
+ * change, so a project in another team fails.
864
+ */
865
+ const converge = (details, teamId, name) => Effect.gen(function* () {
866
+ if (details.teamId !== teamId) return yield* new ProjectTeamChange({
867
+ projectId: details.id,
868
+ teamId: details.teamId,
869
+ requestedTeamId: teamId
870
+ });
871
+ if (details.name === name) return yield* attributesOf(details);
872
+ const updated = yield* api.request("update project", (client) => client.PATCH("/projects/{project_id}", {
873
+ params: { path: { project_id: details.id } },
874
+ body: { name }
875
+ }));
876
+ return yield* attributesOf(Schema.decodeUnknownSync(ProjectDetails)(updated));
877
+ });
878
+ return {
879
+ stables: [
880
+ "projectId",
881
+ "slug",
882
+ "teamId"
883
+ ],
884
+ diff: Effect.fn(function* ({ olds, news, output }) {
885
+ if (!isResolved(news)) return void 0;
886
+ if (output === void 0) return void 0;
887
+ if (olds.team !== news.team) {
888
+ const requestedTeamId = yield* api.resolveTeamId(news.team);
889
+ if (requestedTeamId !== output.teamId) return yield* new ProjectTeamChange({
890
+ projectId: output.projectId,
891
+ teamId: output.teamId,
892
+ requestedTeamId
893
+ });
894
+ }
895
+ return olds.name === news.name ? void 0 : { action: "update" };
896
+ }),
897
+ read: Effect.fn(function* ({ olds, output }) {
898
+ if (output !== void 0) {
899
+ const details = yield* getById(output.projectId);
900
+ return details === void 0 ? void 0 : yield* attributesOf(details);
901
+ }
902
+ const existing = yield* findByName(yield* api.resolveTeamId(olds.team), olds.name);
903
+ return existing === void 0 ? void 0 : Unowned(yield* attributesOf(existing));
904
+ }),
905
+ reconcile: Effect.fn(function* ({ fqn, olds, news, output }) {
906
+ const teamId = yield* api.resolveTeamId(news.team);
907
+ if (output !== void 0) {
908
+ if (olds !== void 0) yield* checkCreateTimeProps(output.projectId, olds, news);
909
+ if (output.teamId !== teamId) return yield* new ProjectTeamChange({
910
+ projectId: output.projectId,
911
+ teamId: output.teamId,
912
+ requestedTeamId: teamId
913
+ });
914
+ const details = yield* getById(output.projectId);
915
+ if (details !== void 0) return yield* converge(details, teamId, news.name);
916
+ } else {
917
+ const existing = yield* findByName(teamId, news.name);
918
+ if (existing !== void 0) {
919
+ if (!(yield* shouldAdopt(fqn))) return yield* new OwnedBySomeoneElse({
920
+ message: `Convex project ${existing.id} in team ${teamId} already has the name "${news.name}". Re-run with --adopt to take it over, or use a different name.`,
921
+ resourceType: Project.Type,
922
+ physicalName: news.name
923
+ });
924
+ return yield* converge(existing, teamId, news.name);
925
+ }
926
+ }
927
+ const created = yield* api.request("create project", (client) => client.POST("/teams/{team_id}/create_project", {
928
+ params: { path: { team_id: teamId } },
929
+ body: {
930
+ projectName: news.name,
931
+ deploymentType: news.deploymentType ?? "prod",
932
+ ...news.deploymentRegion === void 0 ? {} : { deploymentRegion: news.deploymentRegion }
933
+ }
934
+ }));
935
+ const { projectId } = Schema.decodeUnknownSync(CreatedProject)(created);
936
+ const details = yield* getById(projectId);
937
+ if (details === void 0) return yield* new CreatedProjectNotFound({ projectId });
938
+ return yield* converge(details, teamId, news.name);
939
+ }),
940
+ delete: Effect.fn(function* ({ output }) {
941
+ yield* absentAsUndefined(api.requestVoid("delete project", (client) => client.POST("/projects/{project_id}/delete", { params: { path: { project_id: output.projectId } } })));
942
+ })
943
+ };
944
+ }));
945
+ //#endregion
946
+ //#region src/Providers.ts
947
+ var Providers = class extends Provider.ProviderCollection()("Convex") {};
948
+ /**
949
+ * All Convex resource providers. Pass a credentials layer to override the
950
+ * default lookup (`CONVEX_ACCESS_TOKEN`, then the Convex CLI login).
951
+ */
952
+ const providers = (credentials = fromConfig()) => Layer.effect(Providers, Provider.collection([
953
+ Project,
954
+ DeployKey,
955
+ PreviewDeployKey,
956
+ EnvironmentVariable,
957
+ DefaultEnvironmentVariable,
958
+ Deploy
959
+ ])).pipe(Layer.provide(Layer.mergeAll(ProjectProvider(), DeployKeyProvider(), PreviewDeployKeyProvider(), EnvironmentVariableProvider(), DefaultEnvironmentVariableProvider(), DeployProvider())), Layer.provide(ManagementApiLive()), Layer.provide(credentials), Layer.provide(CommandExecutorLive()), Layer.orDie);
960
+ //#endregion
961
+ export { ACCESS_TOKEN_ENV, AmbiguousProject, ConvexApiError, CreatedProjectNotFound, Credentials, CredentialsError, DefaultEnvironmentVariable, Deploy, DeployArgumentError, DeployKey, DeployKeyIsCredential, DeployKeyRecoveryRequired, DeployOutputError, EnvironmentVariable, ManagementApi, PreviewDeployKey, Project, ProjectDeploymentChange, ProjectTeamChange, Providers, VariableIdentityChange, deployArgs, fromConfig, fromToken, parseDeployOutput, providers };
962
+
11
963
  //# sourceMappingURL=index.js.map