@gaganref/confect-alchemy 10.6.0-fork.3 → 10.6.0-fork.30

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 (99) hide show
  1. package/dist/Backend.d.ts +64 -5
  2. package/dist/Backend.d.ts.map +1 -1
  3. package/dist/Backend.js +187 -3
  4. package/dist/Backend.js.map +1 -1
  5. package/dist/Code.d.ts +14 -2
  6. package/dist/Code.d.ts.map +1 -1
  7. package/dist/Code.js +2 -2
  8. package/dist/Code.js.map +1 -1
  9. package/dist/Confect.d.ts +1 -1
  10. package/dist/Confect.d.ts.map +1 -1
  11. package/dist/Confect.js +8 -3
  12. package/dist/Confect.js.map +1 -1
  13. package/dist/Convex.d.ts +4 -1
  14. package/dist/Convex.d.ts.map +1 -1
  15. package/dist/Convex.js +10 -1
  16. package/dist/Convex.js.map +1 -1
  17. package/dist/ConvexClient.d.ts +92 -3
  18. package/dist/ConvexClient.d.ts.map +1 -1
  19. package/dist/ConvexClient.js +149 -27
  20. package/dist/ConvexClient.js.map +1 -1
  21. package/dist/CustomDomain.d.ts +156 -0
  22. package/dist/CustomDomain.d.ts.map +1 -0
  23. package/dist/CustomDomain.js +255 -0
  24. package/dist/CustomDomain.js.map +1 -0
  25. package/dist/DeployKey.js +3 -3
  26. package/dist/Deployment.d.ts +29 -3
  27. package/dist/Deployment.d.ts.map +1 -1
  28. package/dist/Deployment.js +39 -15
  29. package/dist/Deployment.js.map +1 -1
  30. package/dist/EnvironmentVariables.d.ts +76 -21
  31. package/dist/EnvironmentVariables.d.ts.map +1 -1
  32. package/dist/EnvironmentVariables.js +203 -19
  33. package/dist/EnvironmentVariables.js.map +1 -1
  34. package/dist/LogStream.d.ts +134 -0
  35. package/dist/LogStream.d.ts.map +1 -0
  36. package/dist/LogStream.js +324 -0
  37. package/dist/LogStream.js.map +1 -0
  38. package/dist/Project.js +2 -2
  39. package/dist/Providers.d.ts.map +1 -1
  40. package/dist/Providers.js +30 -15
  41. package/dist/Providers.js.map +1 -1
  42. package/dist/UsageLimit.d.ts +140 -0
  43. package/dist/UsageLimit.d.ts.map +1 -0
  44. package/dist/UsageLimit.js +145 -0
  45. package/dist/UsageLimit.js.map +1 -0
  46. package/dist/internal/CodeDeployment.d.ts +28 -1
  47. package/dist/internal/CodeDeployment.d.ts.map +1 -1
  48. package/dist/internal/CodeDeployment.js +85 -2
  49. package/dist/internal/CodeDeployment.js.map +1 -1
  50. package/dist/internal/CommandRunner.d.ts +4 -0
  51. package/dist/internal/CommandRunner.d.ts.map +1 -1
  52. package/dist/internal/CommandRunner.js +92 -6
  53. package/dist/internal/CommandRunner.js.map +1 -1
  54. package/dist/internal/FileLock.js +1 -1
  55. package/dist/internal/FunctionsDirectory.d.ts +12 -0
  56. package/dist/internal/FunctionsDirectory.d.ts.map +1 -0
  57. package/dist/internal/FunctionsDirectory.js +22 -0
  58. package/dist/internal/FunctionsDirectory.js.map +1 -0
  59. package/dist/internal/Lifecycle.d.ts +1 -0
  60. package/dist/internal/Lifecycle.d.ts.map +1 -1
  61. package/dist/internal/Lifecycle.js +24 -2
  62. package/dist/internal/Lifecycle.js.map +1 -1
  63. package/dist/internal/LocalBackend.d.ts +9 -0
  64. package/dist/internal/LocalBackend.d.ts.map +1 -1
  65. package/dist/internal/LocalBackend.js +14 -5
  66. package/dist/internal/LocalBackend.js.map +1 -1
  67. package/dist/internal/LogStream.d.ts +115 -0
  68. package/dist/internal/LogStream.d.ts.map +1 -0
  69. package/dist/internal/LogStream.js +123 -0
  70. package/dist/internal/LogStream.js.map +1 -0
  71. package/dist/internal/MountInit.d.ts.map +1 -1
  72. package/dist/internal/MountInit.js +4 -6
  73. package/dist/internal/MountInit.js.map +1 -1
  74. package/dist/internal/PushLock.d.ts +1 -0
  75. package/dist/internal/PushLock.d.ts.map +1 -1
  76. package/dist/internal/PushLock.js +4 -3
  77. package/dist/internal/PushLock.js.map +1 -1
  78. package/dist/internal/ResourceIdentity.js +1 -1
  79. package/dist/internal/Zip.js +1 -1
  80. package/package.json +4 -4
  81. package/src/Backend.ts +422 -12
  82. package/src/Code.ts +13 -0
  83. package/src/Confect.ts +7 -1
  84. package/src/Convex.ts +24 -1
  85. package/src/ConvexClient.ts +364 -31
  86. package/src/CustomDomain.ts +453 -0
  87. package/src/Deployment.ts +74 -12
  88. package/src/EnvironmentVariables.ts +505 -19
  89. package/src/LogStream.ts +662 -0
  90. package/src/Providers.ts +18 -0
  91. package/src/UsageLimit.ts +253 -0
  92. package/src/internal/CodeDeployment.ts +115 -0
  93. package/src/internal/CommandRunner.ts +182 -1
  94. package/src/internal/FunctionsDirectory.ts +27 -0
  95. package/src/internal/Lifecycle.ts +21 -1
  96. package/src/internal/LocalBackend.ts +9 -0
  97. package/src/internal/LogStream.ts +154 -0
  98. package/src/internal/MountInit.ts +3 -13
  99. package/src/internal/PushLock.ts +4 -1
@@ -1,7 +1,21 @@
1
1
  import { OwnedBySomeoneElse, Unowned } from "alchemy/AdoptPolicy";
2
2
  import { isResolved } from "alchemy/Diff";
3
+ import type { Input, InputProps } from "alchemy/Input";
4
+ import * as Output from "alchemy/Output";
3
5
  import * as Provider from "alchemy/Provider";
4
- import { Resource } from "alchemy/Resource";
6
+ import {
7
+ Resource,
8
+ type ResourceClass,
9
+ type ResourceConstructor,
10
+ } from "alchemy/Resource";
11
+ import * as Effectable from "effect/Effectable";
12
+ import * as Config from "effect/Config";
13
+ import * as Result from "effect/Result";
14
+ import * as Duration from "effect/Duration";
15
+ import * as Option from "effect/Option";
16
+ import * as Predicate from "effect/Predicate";
17
+ import * as Schedule from "effect/Schedule";
18
+ import { PushLock, PushLockError } from "./internal/PushLock.js";
5
19
  import * as Effect from "effect/Effect";
6
20
  import * as Layer from "effect/Layer";
7
21
  import * as FetchHttpClient from "effect/http/FetchHttpClient";
@@ -15,6 +29,32 @@ import * as Arr from "effect/Array";
15
29
  import * as Rec from "effect/Record";
16
30
 
17
31
  export interface EnvironmentVariablesProps {
32
+ /**
33
+ * Refuse live owned values that differ from both the last write and the
34
+ * desired value. Defaults to `overwrite`.
35
+ */
36
+ readonly driftPolicy?: "overwrite" | "error";
37
+ /**
38
+ * Adopt unowned desired names only when their live values match. Defaults to
39
+ * false.
40
+ */
41
+ readonly adoptMatching?: boolean;
42
+ /**
43
+ * Refuse live names that are neither owned nor desired. Defaults to `ignore`.
44
+ */
45
+ readonly unownedPolicy?: "ignore" | "error";
46
+ /**
47
+ * Share the deployment push lock for checks and writes. Absent by default.
48
+ */
49
+ readonly lock?: { readonly deploymentName: string };
50
+ /**
51
+ * Retry write conflicts only, with 1 to 10 attempts and a delay of 1 to 10000
52
+ * ms. Absent means one attempt.
53
+ */
54
+ readonly retry?: {
55
+ readonly maxAttempts: number;
56
+ readonly delay: Duration.Input;
57
+ };
18
58
  readonly url: string;
19
59
  readonly deployKey: Redacted.Redacted<string>;
20
60
  readonly variables: Readonly<
@@ -37,17 +77,284 @@ export type EnvironmentVariables = Resource<
37
77
  never,
38
78
  Providers
39
79
  >;
40
- export const EnvironmentVariables = Resource<EnvironmentVariables>(
80
+ const environmentVariables = Resource<EnvironmentVariables>(
41
81
  "Convex.EnvironmentVariables",
42
82
  );
43
83
 
84
+ // Alchemy skips provider reads for fresh resources with unresolved inputs.
85
+ export const EnvironmentVariables: ResourceClass<EnvironmentVariables> =
86
+ Object.assign(
87
+ new Proxy(environmentVariables, {
88
+ apply: <PropsReq>(
89
+ target: ResourceClass<EnvironmentVariables>,
90
+ _this: unknown,
91
+ args:
92
+ | [methods: object]
93
+ | [
94
+ id: string,
95
+ props:
96
+ | InputProps<EnvironmentVariablesProps>
97
+ | Effect.Effect<
98
+ InputProps<EnvironmentVariablesProps>,
99
+ never,
100
+ PropsReq
101
+ >,
102
+ ],
103
+ ) => {
104
+ if (args.length === 1)
105
+ return Object.assign(EnvironmentVariables, args[0]);
106
+ const [id, props] = args;
107
+ return target(
108
+ id,
109
+ (Effect.isEffect(props) ? props : Effect.succeed(props)).pipe(
110
+ Effect.flatMap((options) =>
111
+ Effect.fromResult(validateSafety(options)).pipe(
112
+ Effect.orDie,
113
+ Effect.as({
114
+ ...options,
115
+ ...(options.retry === undefined
116
+ ? {}
117
+ : { retry: checkedRetry(options.retry) }),
118
+ ...(options.lock === undefined
119
+ ? {}
120
+ : { lock: checkedLock(options.lock) }),
121
+ }),
122
+ ),
123
+ ),
124
+ ),
125
+ );
126
+ },
127
+ }),
128
+ Effectable.Prototype<
129
+ Effect.Effect<ResourceConstructor<EnvironmentVariables>>
130
+ >({
131
+ label: "Resource<Convex.EnvironmentVariables>",
132
+ evaluate: () => Effect.succeed(EnvironmentVariables),
133
+ }),
134
+ );
135
+
44
136
  export class EnvironmentTargetChange extends Schema.TaggedError<
45
137
  EnvironmentTargetChange,
46
138
  { readonly brand: unique symbol }
47
139
  >()("EnvironmentTargetChange", { url: Schema.String }) {}
48
140
 
141
+ export class EnvironmentVariableDrift extends Schema.TaggedError<
142
+ EnvironmentVariableDrift,
143
+ { readonly brand: unique symbol }
144
+ >()("EnvironmentVariableDrift", { variableName: Schema.String }) {
145
+ override get message() {
146
+ return `Environment variable ${this.variableName} differs from its last managed value`;
147
+ }
148
+ }
149
+
150
+ export class EnvironmentVariableUnowned extends Schema.TaggedError<
151
+ EnvironmentVariableUnowned,
152
+ { readonly brand: unique symbol }
153
+ >()("EnvironmentVariableUnowned", { variableName: Schema.String }) {
154
+ override get message() {
155
+ return `Environment variable ${this.variableName} is neither owned nor desired`;
156
+ }
157
+ }
158
+
159
+ export class EnvironmentVariablesInvalidOption extends Schema.TaggedError<
160
+ EnvironmentVariablesInvalidOption,
161
+ { readonly brand: unique symbol }
162
+ >()("EnvironmentVariablesInvalidOption", {
163
+ option: Schema.Literals(["maxAttempts", "delay", "deploymentName"]),
164
+ }) {
165
+ override get message() {
166
+ switch (this.option) {
167
+ case "maxAttempts":
168
+ return "Environment retry maxAttempts must be an integer from 1 to 10";
169
+ case "delay":
170
+ return "Environment retry delay must be from 1 to 10000 milliseconds";
171
+ case "deploymentName":
172
+ return "Environment lock deploymentName must contain lowercase letters or digits separated by single hyphens";
173
+ }
174
+ }
175
+ }
176
+
177
+ type SafetyOptions = {
178
+ readonly retry?: EnvironmentVariablesProps["retry"];
179
+ readonly lock?: EnvironmentVariablesProps["lock"];
180
+ };
181
+
182
+ const validateMaxAttempts = (
183
+ maxAttempts: number,
184
+ ): Result.Result<void, EnvironmentVariablesInvalidOption> =>
185
+ Number.isInteger(maxAttempts) && maxAttempts >= 1 && maxAttempts <= 10
186
+ ? Result.succeed(undefined)
187
+ : Result.fail(
188
+ EnvironmentVariablesInvalidOption.make({ option: "maxAttempts" }),
189
+ );
190
+
191
+ const validateDelay = (
192
+ delay: Duration.Input,
193
+ ): Result.Result<Duration.Duration, EnvironmentVariablesInvalidOption> => {
194
+ const parsed = Duration.fromInput(delay);
195
+ return Option.isSome(parsed) &&
196
+ Duration.toMillis(parsed.value) >= 1 &&
197
+ Duration.toMillis(parsed.value) <= 10000
198
+ ? Result.succeed(parsed.value)
199
+ : Result.fail(EnvironmentVariablesInvalidOption.make({ option: "delay" }));
200
+ };
201
+
202
+ const validateDeploymentName = (
203
+ deploymentName: string,
204
+ ): Result.Result<void, EnvironmentVariablesInvalidOption> =>
205
+ /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(deploymentName)
206
+ ? Result.succeed(undefined)
207
+ : Result.fail(
208
+ EnvironmentVariablesInvalidOption.make({ option: "deploymentName" }),
209
+ );
210
+
211
+ const validateSafety = (
212
+ options: Input<SafetyOptions>,
213
+ ): Result.Result<
214
+ Duration.Duration | undefined,
215
+ EnvironmentVariablesInvalidOption
216
+ > =>
217
+ Result.gen(function* () {
218
+ let duration: Duration.Duration | undefined;
219
+ if (
220
+ "retry" in options &&
221
+ options.retry !== undefined &&
222
+ "maxAttempts" in options.retry &&
223
+ "delay" in options.retry
224
+ ) {
225
+ if (isResolved(options.retry.maxAttempts))
226
+ yield* validateMaxAttempts(options.retry.maxAttempts);
227
+ if (isResolved(options.retry.delay))
228
+ duration = yield* validateDelay(options.retry.delay);
229
+ }
230
+ if (
231
+ "lock" in options &&
232
+ options.lock !== undefined &&
233
+ "deploymentName" in options.lock &&
234
+ isResolved(options.lock.deploymentName)
235
+ )
236
+ yield* validateDeploymentName(options.lock.deploymentName);
237
+ return duration;
238
+ });
239
+
240
+ const checkedInput = <A>(
241
+ input: Exclude<Input<A>, undefined>,
242
+ validate: (
243
+ value: A,
244
+ ) => Result.Result<unknown, EnvironmentVariablesInvalidOption>,
245
+ ): Exclude<Input<A>, undefined> => {
246
+ const check = (value: A) =>
247
+ Effect.fromResult(validate(value)).pipe(Effect.orDie, Effect.as(value));
248
+ if (Config.isConfig(input)) return input.pipe(Config.mapEffect(check));
249
+ return input;
250
+ };
251
+
252
+ const checkedRetry = (
253
+ input: Exclude<Input<SafetyOptions["retry"]>, undefined>,
254
+ ): Exclude<Input<SafetyOptions["retry"]>, undefined> => {
255
+ if ("maxAttempts" in input && "delay" in input)
256
+ return {
257
+ ...input,
258
+ maxAttempts: checkedInput(input.maxAttempts, validateMaxAttempts),
259
+ delay: checkedInput(input.delay, validateDelay),
260
+ };
261
+ return checkedInput(input, (retry) => validateSafety({ retry }));
262
+ };
263
+
264
+ const checkedLock = (
265
+ input: Exclude<Input<SafetyOptions["lock"]>, undefined>,
266
+ ): Exclude<Input<SafetyOptions["lock"]>, undefined> => {
267
+ if ("deploymentName" in input)
268
+ return {
269
+ ...input,
270
+ deploymentName: checkedInput(
271
+ input.deploymentName,
272
+ validateDeploymentName,
273
+ ),
274
+ };
275
+ return checkedInput(input, (lock) => validateSafety({ lock }));
276
+ };
277
+
278
+ const ownershipConflict = (variableName: string) =>
279
+ new OwnedBySomeoneElse({
280
+ message:
281
+ "An existing environment variable requires explicit adoption in a separate resource.",
282
+ resourceType: EnvironmentVariables.Type,
283
+ physicalName: variableName,
284
+ });
285
+
286
+ const definedVariables = <A>(variables: Readonly<Record<string, A>>) =>
287
+ Rec.filter(variables, (value) => value !== null && value !== undefined);
288
+
289
+ const optionsForDiff = (
290
+ olds: EnvironmentVariablesProps,
291
+ news: Input<EnvironmentVariablesProps>,
292
+ ) => {
293
+ if (!("variables" in news))
294
+ return { ...olds, desiredNames: undefined, desiredVariables: undefined };
295
+ const desiredVariables =
296
+ !Output.isExpr(news.variables) &&
297
+ !Effect.isEffect(news.variables) &&
298
+ Predicate.isReadonlyObject(news.variables)
299
+ ? definedVariables<Input<string | Redacted.Redacted<string>>>(
300
+ news.variables,
301
+ )
302
+ : undefined;
303
+ return {
304
+ driftPolicy: isResolved(news.driftPolicy)
305
+ ? news.driftPolicy
306
+ : olds.driftPolicy,
307
+ adoptMatching: isResolved(news.adoptMatching)
308
+ ? news.adoptMatching
309
+ : olds.adoptMatching,
310
+ unownedPolicy: isResolved(news.unownedPolicy)
311
+ ? news.unownedPolicy
312
+ : olds.unownedPolicy,
313
+ lock: isResolved(news.lock) ? news.lock : olds.lock,
314
+ retry: isResolved(news.retry) ? news.retry : olds.retry,
315
+ desiredVariables,
316
+ desiredNames:
317
+ desiredVariables === undefined ? undefined : Rec.keys(desiredVariables),
318
+ };
319
+ };
320
+
49
321
  export const provider = Effect.gen(function* () {
50
322
  const client = yield* ConvexClient.ConvexClient;
323
+ const lock = yield* Effect.serviceOption(PushLock);
324
+ const withSafety = Effect.fn("EnvironmentVariables.withSafety")(function* <
325
+ A,
326
+ E,
327
+ R,
328
+ >(
329
+ options: {
330
+ readonly lock?: EnvironmentVariablesProps["lock"];
331
+ readonly retry?: EnvironmentVariablesProps["retry"];
332
+ },
333
+ effect: Effect.Effect<A, E, R>,
334
+ ) {
335
+ const duration = yield* Effect.fromResult(validateSafety(options));
336
+ let attempt = effect;
337
+ if (options.retry !== undefined && duration !== undefined) {
338
+ const { maxAttempts } = options.retry;
339
+ attempt = effect.pipe(
340
+ Effect.retry({
341
+ times: maxAttempts - 1,
342
+ schedule: Schedule.spaced(duration),
343
+ while: (error) =>
344
+ Schema.is(ConvexClient.ConvexApiError)(error) &&
345
+ error.serverCode === "OptimisticConcurrencyControlFailure",
346
+ }),
347
+ );
348
+ }
349
+ if (options.lock === undefined) return yield* attempt;
350
+ if (Option.isNone(lock))
351
+ return yield* PushLockError.make({
352
+ deploymentName: options.lock.deploymentName,
353
+ reason: "configuration",
354
+ missing: "PushLock",
355
+ });
356
+ return yield* lock.value.withLock(options.lock.deploymentName, attempt);
357
+ });
51
358
  const redacted = (value: string | Redacted.Redacted<string>) =>
52
359
  typeof value === "string" ? Redacted.make(value) : value;
53
360
  const valueAt = (
@@ -63,14 +370,129 @@ export const provider = Effect.gen(function* () {
63
370
  !Rec.has(variables, name) ? [] : [[name, variables[name]]],
64
371
  ),
65
372
  );
66
- return {
67
- diff: Effect.fn("EnvironmentVariables.diff")(function* ({ news, output }) {
373
+ const checkDrift = (
374
+ policy: EnvironmentVariablesProps["driftPolicy"],
375
+ output: EnvironmentVariablesAttributes | undefined,
376
+ observed: ConvexClient.EnvironmentVariables,
377
+ desired: Input<EnvironmentVariablesProps["variables"]> | undefined,
378
+ ) => {
379
+ if (policy !== "error" || output === undefined) return Effect.void;
380
+ const desiredVariables =
381
+ Predicate.isReadonlyObject(desired) &&
382
+ !Output.isExpr(desired) &&
383
+ !Effect.isEffect(desired)
384
+ ? desired
385
+ : undefined;
386
+ for (const name of output.ownedNames) {
387
+ const previous = valueAt(output.variables, name);
388
+ const current = valueAt(observed, name);
389
+ const wanted = desiredVariables?.[name];
390
+ if (
391
+ current === undefined &&
392
+ desiredVariables !== undefined &&
393
+ !Rec.has(desiredVariables, name)
394
+ )
395
+ continue;
396
+ if (
397
+ current !== undefined &&
398
+ (desiredVariables === undefined ||
399
+ (wanted !== undefined && !isResolved(wanted)))
400
+ )
401
+ continue;
402
+ if (
403
+ current !== undefined &&
404
+ (typeof wanted === "string" || Redacted.isRedacted(wanted)) &&
405
+ Redacted.value(current) ===
406
+ (typeof wanted === "string" ? wanted : Redacted.value(wanted))
407
+ )
408
+ continue;
409
+ if (previous === undefined && current === undefined) continue;
410
+ if (
411
+ previous === undefined ||
412
+ current === undefined ||
413
+ Redacted.value(previous) !== Redacted.value(current)
414
+ )
415
+ return Effect.fail(
416
+ EnvironmentVariableDrift.make({ variableName: name }),
417
+ );
418
+ }
419
+ return Effect.void;
420
+ };
421
+ const checkUnowned = (
422
+ policy: EnvironmentVariablesProps["unownedPolicy"],
423
+ output: EnvironmentVariablesAttributes | undefined,
424
+ desiredNames: ReadonlyArray<string> | undefined,
425
+ observed: ConvexClient.EnvironmentVariables,
426
+ ) => {
427
+ if (policy !== "error" || desiredNames === undefined) return Effect.void;
428
+ for (const name of Rec.keys(observed)) {
429
+ if (
430
+ output?.ownedNames.includes(name) !== true &&
431
+ !desiredNames.includes(name)
432
+ )
433
+ return Effect.fail(
434
+ EnvironmentVariableUnowned.make({ variableName: name }),
435
+ );
436
+ }
437
+ return Effect.void;
438
+ };
439
+ const service = {
440
+ diff: Effect.fn("EnvironmentVariables.diff")(function* ({
441
+ olds,
442
+ news,
443
+ output,
444
+ }) {
445
+ const options = optionsForDiff(olds, news);
446
+ if (
447
+ output !== undefined &&
448
+ (options.driftPolicy === "error" ||
449
+ options.unownedPolicy === "error" ||
450
+ options.adoptMatching === true)
451
+ ) {
452
+ const observed = yield* client.listEnvironmentVariables(
453
+ output.url,
454
+ output.deployKey,
455
+ );
456
+ yield* checkDrift(
457
+ options.driftPolicy,
458
+ output,
459
+ observed,
460
+ options.desiredVariables,
461
+ );
462
+ if (
463
+ options.adoptMatching === true &&
464
+ Predicate.isReadonlyObject(options.desiredVariables) &&
465
+ !Output.isExpr(options.desiredVariables) &&
466
+ !Effect.isEffect(options.desiredVariables)
467
+ ) {
468
+ for (const [name, wanted] of Rec.toEntries(
469
+ options.desiredVariables,
470
+ )) {
471
+ const current = valueAt(observed, name);
472
+ if (
473
+ !output.ownedNames.includes(name) &&
474
+ current !== undefined &&
475
+ (typeof wanted === "string" || Redacted.isRedacted(wanted)) &&
476
+ Redacted.value(current) !==
477
+ (typeof wanted === "string" ? wanted : Redacted.value(wanted))
478
+ )
479
+ return yield* ownershipConflict(name);
480
+ }
481
+ }
482
+ yield* checkUnowned(
483
+ options.unownedPolicy,
484
+ output,
485
+ options.desiredNames,
486
+ observed,
487
+ );
488
+ }
68
489
  if (!isResolved(news) || output === undefined) return;
69
490
  if (news.url !== output.url)
70
491
  return yield* EnvironmentTargetChange.make({
71
492
  url: output.url,
72
493
  });
73
- const names = Rec.keys(news.variables);
494
+ const desired = definedVariables(news.variables);
495
+ const names = Rec.keys(desired);
74
496
  if (
75
497
  names.length !== output.ownedNames.length ||
76
498
  Arr.some(names, (name) => !output.ownedNames.includes(name))
@@ -80,7 +502,7 @@ export const provider = Effect.gen(function* () {
80
502
  news.url,
81
503
  news.deployKey,
82
504
  );
83
- for (const [name, value] of Rec.toEntries(news.variables)) {
505
+ for (const [name, value] of Rec.toEntries(desired)) {
84
506
  const observed = valueAt(variables, name);
85
507
  if (
86
508
  observed === undefined ||
@@ -96,11 +518,34 @@ export const provider = Effect.gen(function* () {
96
518
  url,
97
519
  olds.deployKey,
98
520
  );
99
- const ownedNames = output?.ownedNames ?? Rec.keys(olds.variables);
521
+ yield* checkDrift(
522
+ olds.driftPolicy,
523
+ output,
524
+ observed,
525
+ definedVariables(olds.variables),
526
+ );
527
+ yield* checkUnowned(
528
+ olds.unownedPolicy,
529
+ output,
530
+ Rec.keys(definedVariables(olds.variables)),
531
+ observed,
532
+ );
533
+ const ownedNames =
534
+ output?.ownedNames ?? Rec.keys(definedVariables(olds.variables));
100
535
  const variables = select(observed, ownedNames);
101
536
  if (output !== undefined)
102
537
  return { ...output, deployKey: olds.deployKey, variables };
103
538
  if (Rec.keys(variables).length === 0) return undefined;
539
+ if (olds.adoptMatching === true) {
540
+ for (const [name, value] of Rec.toEntries(variables)) {
541
+ if (
542
+ Redacted.value(value) !==
543
+ Redacted.value(redacted(olds.variables[name]))
544
+ )
545
+ return yield* ownershipConflict(name);
546
+ }
547
+ return undefined;
548
+ }
104
549
  return Unowned({
105
550
  url,
106
551
  deployKey: olds.deployKey,
@@ -115,6 +560,7 @@ export const provider = Effect.gen(function* () {
115
560
  news,
116
561
  output,
117
562
  }) {
563
+ news = { ...news, variables: definedVariables(news.variables) };
118
564
  if (output === undefined) yield* checkpointCreate(fqn, instanceId, news);
119
565
  if (output !== undefined && output.url !== news.url)
120
566
  return yield* EnvironmentTargetChange.make({
@@ -124,8 +570,19 @@ export const provider = Effect.gen(function* () {
124
570
  news.url,
125
571
  news.deployKey,
126
572
  );
573
+ yield* checkDrift(news.driftPolicy, output, observed, news.variables);
574
+ yield* checkUnowned(
575
+ news.unownedPolicy,
576
+ output,
577
+ Rec.keys(news.variables),
578
+ observed,
579
+ );
127
580
  const ownedNames = Rec.keys(news.variables);
128
- if (output === undefined && (yield* shouldAdopt(fqn))) {
581
+ if (
582
+ output === undefined &&
583
+ news.adoptMatching !== true &&
584
+ (yield* shouldAdopt(fqn))
585
+ ) {
129
586
  const variables = select(observed, ownedNames);
130
587
  output = {
131
588
  url: news.url,
@@ -137,17 +594,29 @@ export const provider = Effect.gen(function* () {
137
594
  yield* checkpointCreate(fqn, instanceId, news, output);
138
595
  }
139
596
  const previousNames = output?.ownedNames ?? [];
597
+ let originals = output?.originals ?? {};
140
598
  for (const name of ownedNames) {
599
+ const current = valueAt(observed, name);
600
+ if (previousNames.includes(name) || current === undefined) continue;
141
601
  if (
142
- !previousNames.includes(name) &&
143
- valueAt(observed, name) !== undefined
144
- )
145
- return yield* new OwnedBySomeoneElse({
146
- message:
147
- "An existing environment variable requires explicit adoption in a separate resource.",
148
- resourceType: EnvironmentVariables.Type,
149
- physicalName: name,
150
- });
602
+ news.adoptMatching === true &&
603
+ Redacted.value(current) ===
604
+ Redacted.value(redacted(news.variables[name]))
605
+ ) {
606
+ originals = Rec.set(originals, name, current);
607
+ yield* Effect.logInfo(`Adopted environment variable ${name}`);
608
+ } else {
609
+ return yield* ownershipConflict(name);
610
+ }
611
+ }
612
+ if (output === undefined && news.adoptMatching === true) {
613
+ yield* checkpointCreate(fqn, instanceId, news, {
614
+ url: news.url,
615
+ deployKey: news.deployKey,
616
+ ownedNames,
617
+ variables: select(observed, ownedNames),
618
+ originals,
619
+ } satisfies EnvironmentVariablesAttributes);
151
620
  }
152
621
  const desired = Rec.fromEntries(
153
622
  Arr.map(Rec.toEntries(news.variables), ([name, value]) => [
@@ -191,14 +660,24 @@ export const provider = Effect.gen(function* () {
191
660
  deployKey: news.deployKey,
192
661
  ownedNames,
193
662
  variables: desired,
194
- originals: select(output?.originals ?? {}, ownedNames),
663
+ originals: select(originals, ownedNames),
195
664
  };
196
665
  }),
197
- delete: Effect.fn("EnvironmentVariables.delete")(function* ({ output }) {
666
+ delete: Effect.fn("EnvironmentVariables.delete")(function* ({
667
+ olds,
668
+ output,
669
+ }) {
198
670
  const observed = yield* client
199
671
  .listEnvironmentVariables(output.url, output.deployKey)
200
672
  .pipe(Effect.catchTag("ConvexNotFound", () => Effect.void));
201
673
  if (observed === undefined) return;
674
+ yield* checkDrift(olds.driftPolicy, output, observed, {});
675
+ yield* checkUnowned(
676
+ olds.unownedPolicy,
677
+ output,
678
+ Rec.keys(definedVariables(olds.variables)),
679
+ observed,
680
+ );
202
681
  const changes: Array<{
203
682
  name: string;
204
683
  value?: Redacted.Redacted<string>;
@@ -220,6 +699,13 @@ export const provider = Effect.gen(function* () {
220
699
  .pipe(Effect.catchTag("ConvexNotFound", () => Effect.void));
221
700
  }),
222
701
  } satisfies Provider.ProviderServiceInput<EnvironmentVariables>;
702
+ return {
703
+ diff: (input) =>
704
+ withSafety(optionsForDiff(input.olds, input.news), service.diff(input)),
705
+ read: (input) => withSafety(input.olds, service.read(input)),
706
+ reconcile: (input) => withSafety(input.news, service.reconcile(input)),
707
+ delete: (input) => withSafety(input.olds, service.delete(input)),
708
+ } satisfies Provider.ProviderServiceInput<EnvironmentVariables>;
223
709
  });
224
710
 
225
711
  /**