@samebase/alchemy-convex 0.30.0 → 0.31.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
@@ -304,20 +304,6 @@ call.
304
304
  as the build inputs `["src/**", "public/**", "vite.config.ts"]`. A minted key for a command has
305
305
  every action, because the command can do more than a push.
306
306
 
307
- - `Convex.HubClient`: `{ team, app, redirectUri, deploymentType, clientName, softwareVersion? }`
308
- registers one deployment as a client of the identity hub of the team. The hub is the production
309
- deployment of the project `identity-hub`. The resource finds it by name and runs its internal
310
- functions `identityBroker:renewClient` and `identityBroker:registerClient` with a short-lived key,
311
- so the stack needs no other credential and no hub address. The first client of an `app` creates
312
- the app. Outputs `issuer`, `clientId`, `clientSecret`, `redirectUri`, `deploymentType`, and
313
- `clientName`, which the `env` of the `Convex.Deployment` writes to the deployment.
314
- - Each deploy renews the client on the hub. A preview or development client expires 14 days after
315
- its last deploy or use, and a production client never expires. A client that the hub no longer
316
- has gets a new one in the same run.
317
- - Another `redirectUri` is a new client, and the old one goes.
318
- - A destroy deletes a preview or development client. It does nothing to a production client,
319
- because the production deployment can stay.
320
-
321
307
  - `Convex.SharedHubClient`:
322
308
  `{ app, redirectUri, deploymentType, initialAccessToken?, softwareVersion? }` gets a client of the
323
309
  central identity hub, for an app that deploys in its own GitHub Actions run, on any host, and for
@@ -376,22 +362,6 @@ call.
376
362
  - With a `local:` deployment selected in `.env.local`, the Convex CLI login takes the team of the
377
363
  project in `config.json`.
378
364
 
379
- A development deployment of a team app (`Convex.HubClient`) has no stack, so the package has a
380
- command for it. Run it in the directory of the app, before the first push and at each dev start,
381
- with `CONVEX_ACCESS_TOKEN` or the Convex CLI login. It renews the client that `HUB_CLIENT_ID` names,
382
- so the client expires 14 days after the last dev start or use. A deployment without all three
383
- variables, or whose client the hub no longer has, gets a new client, and the command writes
384
- `HUB_ISSUER`, `HUB_CLIENT_ID`, and `HUB_CLIENT_SECRET` to it.
385
-
386
- ```sh
387
- npx alchemy-convex hub-client --team my-team --app scout --callback-path /auth/hub/callback
388
- ```
389
-
390
- For a separate API-connection callback, register another client with
391
- `--callback-path /oauth/hub/callback --env-prefix RESOURCE_HUB`. This writes `RESOURCE_HUB_ISSUER`,
392
- `RESOURCE_HUB_CLIENT_ID`, and `RESOURCE_HUB_CLIENT_SECRET`, preserving the sign-in client's
393
- variables. Each callback remains one exact registered URI.
394
-
395
365
  ### The development stage
396
366
 
397
367
  A laptop gets its client from a stage `dev-<name>` of the app's stack, run on purpose, not at each
@@ -27,10 +27,10 @@ import { hashDirectory } from "alchemy/Command/Memo";
27
27
  import * as Clock from "effect/Clock";
28
28
  import * as ChildProcess from "effect/process/ChildProcess";
29
29
  import * as Stream from "effect/Stream";
30
- import { fileURLToPath } from "node:url";
31
- import * as Scope from "effect/Scope";
32
30
  import { STATE_STORE_VERSION, State, StateStoreError, encodeState, reviveState } from "alchemy/State";
33
31
  import { execFile } from "node:child_process";
32
+ import { fileURLToPath } from "node:url";
33
+ import * as Scope from "effect/Scope";
34
34
  //#region src/Credentials.ts
35
35
  var Credentials = class extends Context.Service()("@samebase/alchemy-convex/Credentials") {};
36
36
  /** Environment variable for the access token, read by {@link fromConfig}. */
@@ -167,13 +167,6 @@ const retryIdempotentWrite = (effect) => effect.pipe(Effect.retry({
167
167
  }));
168
168
  /** Turns a 404 into `undefined` so read and delete stay idempotent. */
169
169
  const absentAsUndefined = (effect) => effect.pipe(Effect.catchIf((error) => error.status === 404, () => Effect.succeed(void 0)));
170
- const TeamRow = Schema.Struct({
171
- id: Schema.Number,
172
- slug: Schema.String
173
- });
174
- const TeamRows = Schema.Array(TeamRow);
175
- /** The first page of GET /teams/{team_id}/projects: every row carries the slug of the team. */
176
- const ProjectSlugRows = Schema.Struct({ items: Schema.Array(Schema.Struct({ teamSlug: Schema.String })) });
177
170
  /** GET /deployments/{name}: the project of the deployment. */
178
171
  const DeploymentProject = Schema.Struct({ projectId: Schema.Number });
179
172
  /** GET /projects/{id}: the team of the project. */
@@ -260,17 +253,14 @@ const makeService = (source) => {
260
253
  const requestVoid = (operation, run) => client.pipe(Effect.flatMap((c) => settleVoid(operation, () => run(c))));
261
254
  const deploymentRequest = (operation, deploymentUrlOrName, deployKey, run) => settle(operation, () => run(createDeploymentClient(deploymentUrlOrName, Redacted.value(deployKey))));
262
255
  const tokenDetails = Effect.runSync(Effect.cached(request("get token details", (c) => c.GET("/token_details")).pipe(Effect.map((body) => Schema.decodeUnknownSync(TokenDetails)(body)), Effect.catchIf((error) => error.status === 403, () => Effect.succeed(void 0)))));
263
- /** The slug of the team, from the first project of its listing, or undefined for a team without one. Read once. */
264
- const teamSlug = (teamId) => request("list projects", (c) => c.GET("/teams/{team_id}/projects", { params: { path: { team_id: teamId } } })).pipe(Effect.map((body) => Schema.decodeUnknownSync(ProjectSlugRows)(body).items[0]?.teamSlug));
265
- const projectTokenError = (projectId) => new ConvexApiError({
266
- operation: "resolve team",
267
- status: 403,
268
- message: `the access token belongs to project ${projectId}, and a project token cannot create projects. Use a team access token.`
269
- });
270
256
  const teamId = Effect.runSync(Effect.cached(Effect.gen(function* () {
271
257
  const details = yield* tokenDetails;
272
258
  if (details?.type === "teamToken") return details.teamId;
273
- if (details?.type === "projectToken") return yield* projectTokenError(details.projectId);
259
+ if (details?.type === "projectToken") return yield* new ConvexApiError({
260
+ operation: "resolve team",
261
+ status: 403,
262
+ message: `the access token belongs to project ${details.projectId}, and a project token cannot create projects. Use a team access token.`
263
+ });
274
264
  const selected = selectedDeployment();
275
265
  if (selected === void 0) return yield* new ConvexApiError({
276
266
  operation: "resolve team",
@@ -281,45 +271,6 @@ const makeService = (source) => {
281
271
  const project = yield* request("get project", (c) => c.GET("/projects/{project_id}", { params: { path: { project_id: projectId } } }));
282
272
  return Schema.decodeUnknownSync(ProjectTeam)(project).teamId;
283
273
  })));
284
- const resolveTeamId = (team) => Effect.gen(function* () {
285
- if (typeof team === "number") return team;
286
- if (/^\d+$/.test(team)) return Number(team);
287
- const details = yield* tokenDetails;
288
- if (details?.type === "teamToken") {
289
- const slug = yield* teamSlug(details.teamId);
290
- if (slug === void 0) return yield* new ConvexApiError({
291
- operation: "resolve team",
292
- status: 0,
293
- message: `team "${team}" cannot be checked against the access token: team ${details.teamId} has no project yet. Set team to ${details.teamId}.`
294
- });
295
- if (slug !== team) return yield* new ConvexApiError({
296
- operation: "resolve team",
297
- status: 403,
298
- message: `the access token belongs to team ${details.teamId} ("${slug}"), and team is "${team}". Use a token of "${team}", or set team to ${details.teamId}.`
299
- });
300
- return details.teamId;
301
- }
302
- if (details?.type === "projectToken") return yield* projectTokenError(details.projectId);
303
- const resolved = yield* credentials;
304
- const match = (yield* Effect.tryPromise({
305
- try: async () => {
306
- const response = await fetch("https://api.convex.dev/api/dashboard/teams", { headers: { Authorization: `Bearer ${Redacted.value(resolved.accessToken)}` } });
307
- if (!response.ok) throw new Error(`team lookup for "${team}" failed with HTTP ${response.status}`);
308
- return Schema.decodeUnknownSync(TeamRows)(await response.json());
309
- },
310
- catch: (cause) => new ConvexApiError({
311
- operation: "resolve team",
312
- status: 0,
313
- message: cause instanceof Error ? cause.message : String(cause)
314
- })
315
- })).find((row) => row.slug === team);
316
- if (match === void 0) return yield* new ConvexApiError({
317
- operation: "resolve team",
318
- status: 404,
319
- message: `no team with slug "${team}" for this token`
320
- });
321
- return match.id;
322
- });
323
274
  const isCredentialToken = (secret) => credentials.pipe(Effect.map((resolved) => tokenPart(Redacted.value(resolved.accessToken)) === tokenPart(secret)));
324
275
  const isOAuthCredential = credentials.pipe(Effect.map((resolved) => /^(team|project):/.test(Redacted.value(resolved.accessToken))));
325
276
  const withToken = (token) => makeService(Effect.succeed({
@@ -331,7 +282,6 @@ const makeService = (source) => {
331
282
  requestVoid,
332
283
  deploymentRequest,
333
284
  teamId,
334
- resolveTeamId,
335
285
  isCredentialToken,
336
286
  isOAuthCredential,
337
287
  withToken
@@ -1598,14 +1548,8 @@ const stateKeyName = (keyId) => `STATE_KEY_${keyId}`;
1598
1548
  //#region src/State.ts
1599
1549
  /** The name of the state project in each team. */
1600
1550
  const STORE_PROJECT_NAME = "alchemy-state-store";
1601
- /**
1602
- * The actions of the key of one run: the internal queries and mutations of
1603
- * the store, nothing else. Measured: `deployment:data:view` and
1604
- * `deployment:data:write` do not run an internal function.
1605
- */
1606
- const RUN_KEY_ACTIONS = ["deployment:functions:runInternalQueries", "deployment:functions:runInternalMutations"];
1607
1551
  /** The actions of the key of one run on the store: its writes are actions that seal. */
1608
- const STORE_KEY_ACTIONS = [...RUN_KEY_ACTIONS, "deployment:functions:runInternalActions"];
1552
+ const STORE_KEY_ACTIONS = [...["deployment:functions:runInternalQueries", "deployment:functions:runInternalMutations"], "deployment:functions:runInternalActions"];
1609
1553
  /** The body of POST /api/function, with HTTP 200 for a function error too. */
1610
1554
  const Reply = Schema.Union([Schema.Struct({
1611
1555
  status: Schema.Literal("success"),
@@ -1894,166 +1838,6 @@ const state = () => Layer.effect(State, Effect.gen(function* () {
1894
1838
  }).pipe(Effect.provideContext(context), Effect.orDie));
1895
1839
  }));
1896
1840
  //#endregion
1897
- //#region src/HubClient.ts
1898
- /** The name of the project of the hub in each team. */
1899
- const HUB_PROJECT_NAME = "identity-hub";
1900
- const HubClient = Resource("IdentityHub.Client");
1901
- /** The hub of the team could not do the call. The reason is the Convex message: it holds no secret. */
1902
- var HubClientFailed = class extends Schema.TaggedError()("HubClientFailed", {
1903
- team: Schema.Union([Schema.String, Schema.Number]),
1904
- reason: Schema.String
1905
- }) {
1906
- get message() {
1907
- return `Convex.HubClient: the hub of team ${this.team}: ${this.reason}.`;
1908
- }
1909
- };
1910
- /** The reply of `identityBroker:registerClient`. */
1911
- const Registered = Schema.Struct({
1912
- issuer: Schema.NonEmptyString,
1913
- clientId: Schema.NonEmptyString,
1914
- clientSecret: Schema.NonEmptyString
1915
- });
1916
- /** The reply of `identityBroker:renewClient`: false when the hub no longer has the client. */
1917
- const Renewed = Schema.Boolean;
1918
- /** Runs `use` with the function API of the hub of `team`, with a key of this call only. */
1919
- const withHub = (api, team, use) => Effect.gen(function* () {
1920
- const teamId = yield* api.resolveTeamId(team);
1921
- const project = yield* findProjectByName(api, teamId, HUB_PROJECT_NAME);
1922
- if (project === void 0) return yield* new HubClientFailed({
1923
- team,
1924
- reason: `no project ${HUB_PROJECT_NAME}, which holds the hub`
1925
- });
1926
- const deployment = yield* prodDeploymentOf(api, project.id);
1927
- if (deployment === void 0) return yield* new HubClientFailed({
1928
- team,
1929
- reason: `project ${HUB_PROJECT_NAME} has no production deployment`
1930
- });
1931
- return yield* withPushKey(api, deployment.name, RUN_KEY_ACTIONS, (key) => use(makeFunctionApi(deployment.deploymentUrl, key)));
1932
- });
1933
- /** One internal function of the hub: its value, or the Convex message as an error. */
1934
- const runHub = (functions, team, name, args) => functions.call(`identityBroker:${name}`, args).pipe(Effect.mapError((error) => new HubClientFailed({
1935
- team,
1936
- reason: error.message
1937
- })), Effect.flatMap((reply) => reply.status === "success" ? Effect.succeed(reply.value) : Effect.fail(new HubClientFailed({
1938
- team,
1939
- reason: reply.errorMessage.trim()
1940
- }))));
1941
- /**
1942
- * Registers one client, which expires unless it is a production client. An
1943
- * attempt that a lost reply repeats leaves one spare client on the hub, which
1944
- * signs nobody in, and which the hub deletes after 14 days.
1945
- */
1946
- const registerHubClient = (api, props) => withHub(api, props.team, (functions) => runHub(functions, props.team, "registerClient", {
1947
- appId: props.app,
1948
- redirectUri: props.redirectUri,
1949
- deploymentType: props.deploymentType,
1950
- clientName: props.clientName,
1951
- softwareVersion: props.softwareVersion ?? "unknown",
1952
- tokenEndpointAuthMethod: "client_secret_post",
1953
- expires: true
1954
- })).pipe(Effect.flatMap((value) => Schema.decodeUnknownEffect(Registered)(value).pipe(Effect.mapError(() => new HubClientFailed({
1955
- team: props.team,
1956
- reason: "registerClient gave no client"
1957
- })))), Effect.map(({ issuer, clientId, clientSecret }) => ({
1958
- issuer,
1959
- clientId,
1960
- clientSecret: Redacted.make(clientSecret)
1961
- })));
1962
- /**
1963
- * Renews one client: true while the hub has it. A preview or development client
1964
- * then expires 14 days after this call.
1965
- */
1966
- const renewHubClient = (api, team, clientId) => withHub(api, team, (functions) => runHub(functions, team, "renewClient", {
1967
- clientId,
1968
- expires: true
1969
- })).pipe(Effect.flatMap((value) => Schema.decodeUnknownEffect(Renewed)(value).pipe(Effect.mapError(() => new HubClientFailed({
1970
- team,
1971
- reason: "renewClient gave no answer"
1972
- })))));
1973
- /**
1974
- * Renews a client whose values the caller holds: false only when the hub answers that the client is
1975
- * gone. Any other failure, such as a hub or a Convex API that cannot answer, keeps the client and
1976
- * warns, so an outage never stops a deploy or a dev start; the next one renews it.
1977
- */
1978
- const renewOrKeep = (api, team, clientId) => renewHubClient(api, team, clientId).pipe(Effect.catch((error) => Effect.logWarning(`Convex.HubClient: ${clientId} keeps its saved values, because the hub could not renew it: ${error.message}`).pipe(Effect.as(true))));
1979
- const unregister = (api, team, clientId) => withHub(api, team, (functions) => runHub(functions, team, "deleteClient", { clientId }));
1980
- /** True when the client in state serves the redirect URI and deployment type of `props`. */
1981
- const registeredFor = (output, props) => output.redirectUri === props.redirectUri && output.deploymentType === props.deploymentType;
1982
- const HubClientProvider = () => Provider.effect(HubClient, Effect.gen(function* () {
1983
- const api = yield* ManagementApi;
1984
- return {
1985
- diff: ({ news }) => Effect.succeed(isResolved(news) ? { action: "update" } : void 0),
1986
- read: ({ output }) => Effect.succeed(output),
1987
- reconcile: Effect.fn(function* ({ news, output }) {
1988
- const saved = output !== void 0 && registeredFor(output, news) ? output : void 0;
1989
- if (saved !== void 0 && (yield* renewOrKeep(api, news.team, saved.clientId))) return saved;
1990
- const client = yield* registerHubClient(api, news);
1991
- if (output !== void 0 && saved === void 0) yield* unregister(api, news.team, output.clientId).pipe(Effect.catchTag("HubClientFailed", (error) => Effect.logWarning(`Client ${output.clientId} stays on the hub: ${error.message} Delete it with \`npx convex run --prod identityBroker:deleteClient\`.`)));
1992
- return {
1993
- ...client,
1994
- redirectUri: news.redirectUri,
1995
- deploymentType: news.deploymentType,
1996
- clientName: news.clientName
1997
- };
1998
- }),
1999
- delete: ({ olds, output }) => output.deploymentType === "production" ? Effect.void : unregister(api, olds.team, output.clientId).pipe(Effect.asVoid)
2000
- };
2001
- }));
2002
- /**
2003
- * `alchemy-convex hub-client`: a stack deploys production and previews, and this covers the
2004
- * development deployment, which no stack deploys. Run it at each dev start: it renews the client
2005
- * that the three variables name, so the client expires 14 days after the last dev start or use. A
2006
- * deployment without all three variables, or whose client the hub no longer has, such as one with
2007
- * the `no-hub` values, gets a new client. Answers the callback URL of a new client, or undefined
2008
- * for a renewal. The secret reaches the Convex CLI on standard input, never in its arguments.
2009
- */
2010
- const registerDevelopmentClient = (options) => Effect.gen(function* () {
2011
- const { convex } = options;
2012
- const api = yield* ManagementApi;
2013
- const envPrefix = options.envPrefix ?? "HUB";
2014
- const variables = [
2015
- `${envPrefix}_ISSUER`,
2016
- `${envPrefix}_CLIENT_ID`,
2017
- `${envPrefix}_CLIENT_SECRET`
2018
- ];
2019
- const names = convex([
2020
- "env",
2021
- "list",
2022
- "--names-only"
2023
- ]).split("\n");
2024
- if (variables.every((name) => names.includes(name))) {
2025
- const clientId = convex([
2026
- "env",
2027
- "get",
2028
- `${envPrefix}_CLIENT_ID`
2029
- ]);
2030
- if (yield* renewOrKeep(api, options.team, clientId)) return void 0;
2031
- }
2032
- const siteUrl = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.String))(convex([
2033
- "run",
2034
- "--inline-query",
2035
- "process.env.CONVEX_SITE_URL"
2036
- ])).pipe(Effect.mapError(() => new HubClientFailed({
2037
- team: options.team,
2038
- reason: "no CONVEX_SITE_URL to register"
2039
- })));
2040
- const callbackUrl = `${siteUrl.replace(/\/$/, "")}${options.callbackPath}`;
2041
- const client = yield* registerHubClient(api, {
2042
- team: options.team,
2043
- app: options.app,
2044
- redirectUri: callbackUrl,
2045
- deploymentType: "development",
2046
- clientName: "development",
2047
- softwareVersion: new URL(siteUrl).host
2048
- });
2049
- convex([
2050
- "env",
2051
- "set",
2052
- "--force"
2053
- ], `${envPrefix}_ISSUER='${client.issuer}'\n${envPrefix}_CLIENT_ID='${client.clientId}'\n${envPrefix}_CLIENT_SECRET='${Redacted.value(client.clientSecret)}'\n`);
2054
- return callbackUrl;
2055
- });
2056
- //#endregion
2057
- export { PushTargetMismatch as A, Credentials as B, DeploymentProvider as C, ConvexAppNotFound as D, CodePushFailed as E, ConvexApiError as F, DEPLOY_KEY_ENV as H, ManagementApi as I, ManagementApiLive as L, installedCli as M, parseDeployOutput as N, ConvexCliNotFound as O, push as P, readLocalDeployment as R, DeploymentIdentityChange as S, ProductionDeploymentNotFound as T, fromConfig as U, CredentialsError as V, fromValues as W, ProjectProvider as _, registerDevelopmentClient as a, AmbiguousDeployment as b, RUN_RECORD_KEY as c, withRunRecord as d, AmbiguousProject as f, ProjectNotFound as g, ProjectDeploymentChange as h, HubClientProvider as i, VariablesOwnedBySomeoneElse as j, EnvironmentNeedsDeployKey as k, RunRecordError as l, Project as m, HubClient as n, STORE_PROJECT_NAME as o, CreatedProjectNotFound as p, HubClientFailed as r, state as s, HUB_PROJECT_NAME as t, runRecord as u, ProjectTeamChange as v, DeploymentResource as w, Deployment as x, AbsoluteRootDir as y, ACCESS_TOKEN_ENV as z };
1841
+ 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 };
2058
1842
 
2059
- //# sourceMappingURL=HubClient-X0-FgJ8v.js.map
1843
+ //# sourceMappingURL=State-t0BZggNl.js.map