@samebase/alchemy-convex 0.40.0 → 0.41.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.
package/README.md CHANGED
@@ -14,21 +14,21 @@ the "Convex Plain" mode of
14
14
  [rjdellecese/confect#408](https://github.com/rjdellecese/confect/issues/408).
15
15
  [docs/design/convex-plane.md](docs/design/convex-plane.md) records the decisions.
16
16
 
17
- Status: pinned to `alchemy@2.0.0-beta.85` and Effect 4.1. Alchemy ships breaking changes between
17
+ Status: pinned to `alchemy@2.0.0-beta.87` and Effect 4.1. Alchemy ships breaking changes between
18
18
  betas; upgrade this package and Alchemy together. A live test runs the full sequence with the real
19
19
  Convex CLI: create, push, no-op, change, preview, deploy keys alone, and destroy.
20
20
 
21
21
  ## Install
22
22
 
23
23
  ```sh
24
- pnpm add -D @samebase/alchemy-convex alchemy@2.0.0-beta.85 effect@^4.1.0 @effect/platform-node@^4.1.0 convex
24
+ pnpm add -D @samebase/alchemy-convex alchemy@2.0.0-beta.87 effect@^4.1.4 @effect/platform-node@^4.1.4 convex
25
25
  ```
26
26
 
27
27
  Use one version for `effect` and for each `@effect/*` package. A mix fails at load time, such as
28
28
  `@effect/platform-node-shared` 4.0.5 next to `effect` 4.0.3.
29
29
 
30
30
  Alchemy providers are separate packages. The example below also needs
31
- `@alchemy.run/cloudflare@2.0.0-beta.85`, the same version as `alchemy`.
31
+ `@alchemy.run/cloudflare@2.0.0-beta.87`, the same version as `alchemy`.
32
32
 
33
33
  ## Example
34
34
 
@@ -240,7 +240,8 @@ stage output of any state layer, `Convex.state()` or `Cloudflare.state()`: the d
240
240
  `setOutput` stores is the stack's output plus the key `samebase.run`. Samebase shows a stage only
241
241
  when its output has this record. On GitHub Actions the record comes from the run's variables and the
242
242
  event payload; on a development machine from git, which needs a branch and an `origin` remote. It
243
- holds no secret.
243
+ holds no secret. The function comes from `@samebase/alchemy-kit/run-record` and works over any state
244
+ layer.
244
245
 
245
246
  ```json
246
247
  {
@@ -3,9 +3,9 @@ import { createRequire } from "node:module";
3
3
  import { Stack } from "alchemy/Stack";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as Schema from "effect/Schema";
6
- import { access, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
6
+ import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
7
7
  import { homedir, tmpdir } from "node:os";
8
- import { dirname, join, posix, relative, resolve, sep, win32 } from "node:path";
8
+ import { dirname, join, posix, relative, resolve, win32 } from "node:path";
9
9
  import * as Config from "effect/Config";
10
10
  import * as Context from "effect/Context";
11
11
  import * as Layer from "effect/Layer";
@@ -19,7 +19,7 @@ import * as Provider from "alchemy/Provider";
19
19
  import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
20
20
  import { AlchemyContext } from "alchemy/AlchemyContext";
21
21
  import { readFileSync } from "node:fs";
22
- import { parseEnv, promisify, stripVTControlCharacters } from "node:util";
22
+ import { parseEnv, stripVTControlCharacters } from "node:util";
23
23
  import { createDeploymentClient, createManagementClient } from "@convex-dev/platform";
24
24
  import * as Schedule from "effect/Schedule";
25
25
  import { createHash } from "node:crypto";
@@ -28,7 +28,6 @@ import * as Clock from "effect/Clock";
28
28
  import * as ChildProcess from "effect/process/ChildProcess";
29
29
  import * as Stream from "effect/Stream";
30
30
  import { STATE_STORE_VERSION, State, StateStoreError, encodeState, reviveState } from "alchemy/State";
31
- import { execFile } from "node:child_process";
32
31
  import { fileURLToPath } from "node:url";
33
32
  import * as Scope from "effect/Scope";
34
33
  //#region src/Credentials.ts
@@ -1436,164 +1435,6 @@ const ProjectProvider = () => Provider.effect(Project, Effect.gen(function* () {
1436
1435
  };
1437
1436
  }));
1438
1437
  //#endregion
1439
- //#region src/RunRecord.ts
1440
- /** The key of the record in the stage output document. */
1441
- const RUN_RECORD_KEY = "samebase.run";
1442
- /** The name of the stack file. Alchemy resolves `--config` against the working directory and does not expose it to a state layer, so the record assumes the default name. */
1443
- const STACK_FILE_NAME = "alchemy.run.ts";
1444
- var RunRecordError = class extends Schema.TaggedError()("RunRecordError", { reason: Schema.String }) {
1445
- get message() {
1446
- return `The run record of the stage output cannot be made: ${this.reason}`;
1447
- }
1448
- };
1449
- /** The part of the GitHub Actions event payload that the record reads. A push event has no `pull_request`. */
1450
- const EventPayload = Schema.Struct({ pull_request: Schema.optionalKey(Schema.Struct({
1451
- number: Schema.Number,
1452
- head: Schema.Struct({ sha: Schema.String })
1453
- })) });
1454
- /** `owner/name` of an https, ssh, or scp-like git URL with a host. A local path is not one. */
1455
- const REMOTE_URL = /^(?:[a-z+]+:\/\/[^/]+\/|[^/@:]+@[^:/]+:)([^/]+)\/([^/]+?)(?:\.git)?\/?$/;
1456
- const execFileAsync = promisify(execFile);
1457
- const now = Clock.currentTimeMillis.pipe(Effect.map((millis) => new Date(millis).toISOString()));
1458
- const git = (cwd, args) => Effect.tryPromise({
1459
- try: async () => (await execFileAsync("git", [
1460
- "-C",
1461
- cwd,
1462
- ...args
1463
- ], { encoding: "utf8" })).stdout.trim(),
1464
- catch: (error) => new RunRecordError({ reason: `git ${args.join(" ")} failed in ${cwd} (${error instanceof Error ? error.message.split("\n")[0] : String(error)})` })
1465
- });
1466
- /** The stack file from the repository root: the working directory below the git top level, plus {@link STACK_FILE_NAME}. */
1467
- const stackFileOf = (cwd) => Effect.gen(function* () {
1468
- const top = yield* git(cwd, ["rev-parse", "--show-toplevel"]);
1469
- const [realTop, realCwd] = yield* Effect.tryPromise({
1470
- try: () => Promise.all([realpath(top), realpath(cwd)]),
1471
- catch: () => new RunRecordError({ reason: `${cwd} is gone` })
1472
- });
1473
- return [...relative(realTop, realCwd).split(sep).filter((part) => part !== ""), STACK_FILE_NAME].join("/");
1474
- });
1475
- const variable = (env, name) => Effect.suspend(() => {
1476
- const value = env[name];
1477
- return value === void 0 || value === "" ? Effect.fail(new RunRecordError({ reason: `GITHUB_ACTIONS is true, and ${name} is not set` })) : Effect.succeed(value);
1478
- });
1479
- const fromGitHubActions = (where) => Effect.gen(function* () {
1480
- const { env } = where;
1481
- const repository = yield* variable(env, "GITHUB_REPOSITORY");
1482
- const refName = yield* variable(env, "GITHUB_REF_NAME");
1483
- const sha = yield* variable(env, "GITHUB_SHA");
1484
- const serverUrl = yield* variable(env, "GITHUB_SERVER_URL");
1485
- const runId = yield* variable(env, "GITHUB_RUN_ID");
1486
- const runAttempt = yield* variable(env, "GITHUB_RUN_ATTEMPT");
1487
- const eventPath = env["GITHUB_EVENT_PATH"];
1488
- const pullRequest = (eventPath === void 0 || eventPath === "" ? void 0 : yield* Effect.tryPromise({
1489
- try: () => readFile(eventPath, "utf8"),
1490
- catch: () => new RunRecordError({ reason: `GITHUB_EVENT_PATH ${eventPath} cannot be read` })
1491
- }).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(EventPayload))), Effect.mapError((error) => error instanceof RunRecordError ? error : new RunRecordError({ reason: `GITHUB_EVENT_PATH ${eventPath} is not an event payload` }))))?.pull_request;
1492
- const headCommit = pullRequest?.head.sha ?? sha;
1493
- const headRef = env["GITHUB_HEAD_REF"];
1494
- const mergeRef = /^refs\/pull\/(\d+)\/merge$/.exec(env["GITHUB_REF"] ?? "");
1495
- return {
1496
- version: 1,
1497
- repository,
1498
- stackFile: yield* stackFileOf(where.cwd),
1499
- branch: headRef === void 0 || headRef === "" ? refName : headRef,
1500
- pullRequest: pullRequest?.number ?? (mergeRef === null ? null : Number(mergeRef[1])),
1501
- headCommit,
1502
- runUrl: `${serverUrl}/${repository}/actions/runs/${runId}/attempts/${runAttempt}`,
1503
- source: "github-actions",
1504
- recordedAt: yield* now
1505
- };
1506
- });
1507
- const fromGit = (where) => Effect.gen(function* () {
1508
- const { cwd } = where;
1509
- const origin = yield* git(cwd, [
1510
- "remote",
1511
- "get-url",
1512
- "origin"
1513
- ]);
1514
- const match = REMOTE_URL.exec(origin);
1515
- if (match === null) return yield* new RunRecordError({ reason: `the origin remote of ${cwd} is not a git URL with a host and owner/name: ${origin}` });
1516
- const branch = yield* git(cwd, [
1517
- "rev-parse",
1518
- "--abbrev-ref",
1519
- "HEAD"
1520
- ]);
1521
- if (branch === "HEAD") return yield* new RunRecordError({ reason: `the checkout at ${cwd} is on no branch (detached HEAD)` });
1522
- return {
1523
- version: 1,
1524
- repository: `${match[1]}/${match[2]}`,
1525
- stackFile: yield* stackFileOf(cwd),
1526
- branch,
1527
- pullRequest: null,
1528
- headCommit: yield* git(cwd, ["rev-parse", "HEAD"]),
1529
- runUrl: null,
1530
- source: "checkout",
1531
- recordedAt: yield* now
1532
- };
1533
- });
1534
- /**
1535
- * The record of this run: from the GitHub Actions variables and the event
1536
- * payload when GITHUB_ACTIONS is `true`, else from git in `cwd`, which needs
1537
- * a branch and an `origin` remote with `owner/name`. Fails when a value is
1538
- * missing; nothing is guessed.
1539
- */
1540
- const runRecord = (where) => where.env["GITHUB_ACTIONS"] === "true" ? fromGitHubActions(where) : fromGit(where);
1541
- /** A plain object, which a spread keeps whole. A Date, a Duration, or a Redacted value is an object too, and a spread loses it. */
1542
- const isPlainObject = (value) => {
1543
- if (typeof value !== "object" || value === null) return false;
1544
- const prototype = Object.getPrototypeOf(value);
1545
- return prototype === Object.prototype || prototype === null;
1546
- };
1547
- /**
1548
- * The output document of a stage: the stack's output plus the record under
1549
- * {@link RUN_RECORD_KEY}, or undefined for an output with no place for the
1550
- * key: a string, an array, null, or an object that is not plain, such as a
1551
- * Date. A value that the stack itself put under the key stays.
1552
- */
1553
- const outputWithRunRecord = (output, record) => isPlainObject(output) ? "samebase.run" in output ? output : {
1554
- ...output,
1555
- [RUN_RECORD_KEY]: record
1556
- } : void 0;
1557
- /**
1558
- * The state of `inner`, with the record of this run in each stage output that it writes, under
1559
- * {@link RUN_RECORD_KEY}: `state: withRunRecord(Convex.state())`, or the same over another state
1560
- * layer, such as the Cloudflare state store of Alchemy. Every other call goes to `inner` as it is.
1561
- *
1562
- * The record is derived once, at the first use of the state, and `recordedAt` is the time of the
1563
- * output write. A checkout that gives no record, such as a tarball without git, a checkout without
1564
- * `origin`, or a detached HEAD, still reads, plans, and destroys: its outputs are written without
1565
- * the record, and the log says why. The engine writes the output only after a full successful
1566
- * apply, so the record names the last full successful deploy of the stage.
1567
- */
1568
- const withRunRecord = (inner) => Layer.effect(State, Effect.gen(function* () {
1569
- const open = yield* State;
1570
- return yield* Effect.cached(Effect.gen(function* () {
1571
- const service = yield* open;
1572
- const run = yield* runRecord({
1573
- cwd: process.cwd(),
1574
- env: process.env
1575
- }).pipe(Effect.catch((error) => Effect.logWarning(`The stage outputs of this run carry no run record. ${error.message}`).pipe(Effect.as(void 0))));
1576
- const documentOf = (request) => Effect.gen(function* () {
1577
- if (run === void 0) return request.value;
1578
- const document = outputWithRunRecord(request.value, {
1579
- ...run,
1580
- recordedAt: yield* now
1581
- });
1582
- if (document !== void 0) return document;
1583
- yield* Effect.logWarning(`The output of ${request.stack}/${request.stage} is not a plain object, so it carries no run record.`);
1584
- return request.value;
1585
- });
1586
- return {
1587
- ...service,
1588
- setOutput: (request) => documentOf(request).pipe(Effect.flatMap((value) => service.setOutput({
1589
- stack: request.stack,
1590
- stage: request.stage,
1591
- value
1592
- })))
1593
- };
1594
- }));
1595
- })).pipe(Layer.provide(inner));
1596
- //#endregion
1597
1438
  //#region src/store/convex/sealing.ts
1598
1439
  /** The variable of the store deployment that holds the key `keyId`. */
1599
1440
  const stateKeyName = (keyId) => `STATE_KEY_${keyId}`;
@@ -1853,6 +1694,6 @@ const state = () => Layer.effect(State, Effect.gen(function* () {
1853
1694
  }).pipe(Effect.provideContext(context), Effect.orDie));
1854
1695
  }));
1855
1696
  //#endregion
1856
- export { ManagementApi as A, ConvexCliNotFound as C, parseDeployOutput as D, VariablesOwnedBySomeoneElse as E, CredentialsError as F, DEPLOY_KEY_ENV as I, fromConfig as L, readLocalDeployment as M, ACCESS_TOKEN_ENV as N, push as O, Credentials as P, fromValues as R, ConvexAppNotFound as S, PushTargetMismatch as T, DeploymentIdentityChange as _, runRecord as a, ProductionDeploymentNotFound as b, CreatedProjectNotFound as c, ProjectNotFound as d, ProjectProvider as f, Deployment as g, AmbiguousDeployment as h, RunRecordError as i, ManagementApiLive as j, ConvexApiError as k, Project as l, AbsoluteRootDir as m, state as n, withRunRecord as o, ProjectTeamChange as p, RUN_RECORD_KEY as r, AmbiguousProject as s, STORE_PROJECT_NAME as t, ProjectDeploymentChange as u, DeploymentProvider as v, EnvironmentNeedsDeployKey as w, CodePushFailed as x, DeploymentResource as y };
1697
+ export { Credentials as A, parseDeployOutput as C, ManagementApiLive as D, ManagementApi as E, DEPLOY_KEY_ENV as M, fromConfig as N, readLocalDeployment as O, fromValues as P, VariablesOwnedBySomeoneElse as S, ConvexApiError as T, CodePushFailed as _, Project as a, EnvironmentNeedsDeployKey as b, ProjectProvider as c, AmbiguousDeployment as d, Deployment as f, ProductionDeploymentNotFound as g, DeploymentResource as h, CreatedProjectNotFound as i, CredentialsError as j, ACCESS_TOKEN_ENV as k, ProjectTeamChange as l, DeploymentProvider as m, state as n, ProjectDeploymentChange as o, DeploymentIdentityChange as p, AmbiguousProject as r, ProjectNotFound as s, STORE_PROJECT_NAME as t, AbsoluteRootDir as u, ConvexAppNotFound as v, push as w, PushTargetMismatch as x, ConvexCliNotFound as y };
1857
1698
 
1858
- //# sourceMappingURL=State-CfIbfbVv.js.map
1699
+ //# sourceMappingURL=State-Bp7iSx8T.js.map