@gaganref/confect-alchemy 10.6.0-fork.2 → 10.6.0-fork.20

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.
@@ -15,10 +15,10 @@ export type DeployKey = Omit<ManagementApi.PlatformDeployKeyResponse, "allowedAc
15
15
  };
16
16
  export type CreateProjectInput = Pick<ManagementApi.PlatformCreateProjectArgs, "projectName">;
17
17
  export type UpdateProjectInput = Pick<ManagementApi.PlatformUpdateProjectArgs, "name">;
18
- export type CreateDeploymentInput = Pick<ManagementApi.PlatformCreateDeploymentArgs, "type" | "region" | "class"> & {
18
+ export type CreateDeploymentInput = Pick<ManagementApi.PlatformCreateDeploymentArgs, "type" | "region" | "class" | "expiresAt"> & {
19
19
  readonly reference: string;
20
20
  };
21
- export type UpdateDeploymentInput = Pick<ManagementApi.PlatformUpdateDeploymentArgs, "reference" | "expiresAt" | "sendLogsToClient">;
21
+ export type UpdateDeploymentInput = Pick<ManagementApi.PlatformUpdateDeploymentArgs, "reference" | "expiresAt" | "sendLogsToClient" | "class">;
22
22
  export type CreateDeployKeyInput = ManagementApi.PlatformCreateDeployKeyArgs;
23
23
  export type CreatedDeployKey = {
24
24
  readonly deployKey: Redacted.Redacted<ManagementApi.PlatformCreateDeployKeyResponse["deployKey"]>;
@@ -1 +1 @@
1
- {"version":3,"file":"ConvexClient.d.ts","sources":["../src/ConvexClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,aAAa,MAAM,oCAAoC,CAAC;AACzE,OAAO,KAAK,KAAK,aAAa,MAAM,oCAAoC,CAAC;AACzE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAEzD,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAC;AAC1C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AACtC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAC5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EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC3C,QAAQ,CAAC,IAAI,CAAC,EAAE,YAAY,CAAC;CAC9B,4DAC4E,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"ConvexClient.js","names":["Loopback.isOrigin"],"sources":["../src/ConvexClient.ts"],"sourcesContent":["import type * as DeploymentApi from \"@convex-dev/platform/deploymentApi\";\nimport type * as ManagementApi from \"@convex-dev/platform/managementApi\";\nimport type { ProviderMode } from \"alchemy/ProviderMode\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\nimport * as FetchHttpClient from \"effect/http/FetchHttpClient\";\nimport * as HttpClient from \"effect/http/HttpClient\";\nimport * as HttpClientRequest from \"effect/http/HttpClientRequest\";\nimport type * as HttpClientResponse from \"effect/http/HttpClientResponse\";\nimport * as Loopback from \"./internal/Loopback.js\";\nimport * as String from \"effect/String\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Rec from \"effect/Record\";\n\nexport type Project = ManagementApi.ProjectResponse;\nexport type CreatedProject = ManagementApi.PlatformCreateProjectResponse;\nexport type Deployment = ManagementApi.PlatformDeploymentResponse;\nexport type DeployKey = Omit<\n ManagementApi.PlatformDeployKeyResponse,\n \"allowedActions\"\n> & {\n readonly allowedActions: readonly string[];\n};\nexport type CreateProjectInput = Pick<\n ManagementApi.PlatformCreateProjectArgs,\n \"projectName\"\n>;\nexport type UpdateProjectInput = Pick<\n ManagementApi.PlatformUpdateProjectArgs,\n \"name\"\n>;\nexport type CreateDeploymentInput = Pick<\n ManagementApi.PlatformCreateDeploymentArgs,\n \"type\" | \"region\" | \"class\"\n> & { readonly reference: string };\nexport type UpdateDeploymentInput = Pick<\n ManagementApi.PlatformUpdateDeploymentArgs,\n \"reference\" | \"expiresAt\" | \"sendLogsToClient\"\n>;\nexport type CreateDeployKeyInput = ManagementApi.PlatformCreateDeployKeyArgs;\nexport type CreatedDeployKey = {\n readonly deployKey: Redacted.Redacted<\n ManagementApi.PlatformCreateDeployKeyResponse[\"deployKey\"]\n >;\n};\nexport type EnvironmentVariableChange = Omit<\n DeploymentApi.UpdateEnvVarRequest,\n \"value\"\n> & {\n readonly value?:\n | Exclude<DeploymentApi.UpdateEnvVarRequest[\"value\"], undefined>\n | Redacted.Redacted<string>;\n};\nexport type EnvironmentVariables = Readonly<\n Record<\n string,\n Redacted.Redacted<\n DeploymentApi.ListEnvVarsResponse[\"environmentVariables\"][string]\n >\n >\n>;\n\nconst errorFields = {\n operation: Schema.String,\n status: Schema.optionalKey(Schema.Finite),\n code: Schema.Literals([\n \"HttpError\",\n \"TransportError\",\n \"InvalidResponse\",\n \"InvalidRequest\",\n \"InvalidPagination\",\n \"InvalidConfiguration\",\n ]),\n};\n\nexport class ConvexApiError extends Schema.TaggedError<\n ConvexApiError,\n { readonly brand: unique symbol }\n>()(\"ConvexApiError\", errorFields) {}\n\nexport class ConvexNotFound extends Schema.TaggedError<\n ConvexNotFound,\n { readonly brand: unique symbol }\n>()(\"ConvexNotFound\", errorFields) {}\n\nexport class ConvexConflict extends Schema.TaggedError<\n ConvexConflict,\n { readonly brand: unique symbol }\n>()(\"ConvexConflict\", errorFields) {}\n\n/**\n * A function the deployment ran failed, with the message Convex reports.\n */\nexport class ConvexFunctionError extends Schema.TaggedError<\n ConvexFunctionError,\n { readonly brand: unique symbol }\n>()(\"ConvexFunctionError\", {\n functionPath: Schema.String,\n errorMessage: Schema.String,\n}) {}\n\nconst FunctionResponse = Schema.Union([\n Schema.Struct({ status: Schema.Literal(\"success\"), value: Schema.Unknown }),\n Schema.Struct({\n status: Schema.Literal(\"error\"),\n errorMessage: Schema.String,\n }),\n]);\n\nexport type ConvexClientError =\n | ConvexApiError\n | ConvexNotFound\n | ConvexConflict;\n\nconst ProjectSchema = Schema.Struct({\n id: Schema.Finite,\n name: Schema.String,\n slug: Schema.String,\n teamId: Schema.Finite,\n teamSlug: Schema.String,\n createTime: Schema.Finite,\n prodDeploymentName: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n devDeploymentName: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n}) satisfies Schema.Schema<Project>;\n\nconst CreatedProjectSchema = Schema.Struct({\n id: Schema.Finite,\n projectId: Schema.Finite,\n slug: Schema.String,\n deploymentName: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n deploymentUrl: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n}) satisfies Schema.Schema<CreatedProject>;\n\nconst deploymentFields = {\n name: Schema.String,\n createTime: Schema.Finite,\n deploymentType: Schema.Literals([\"dev\", \"prod\", \"preview\", \"custom\"]),\n projectId: Schema.Finite,\n previewIdentifier: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n};\n\nconst DeploymentSchema = Schema.Union([\n Schema.Struct({\n ...deploymentFields,\n kind: Schema.Literal(\"cloud\"),\n id: Schema.Finite,\n lastDeployTime: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n creator: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n region: Schema.Literals([\n \"aws-us-east-1\",\n \"aws-eu-west-1\",\n \"aws-ap-southeast-2\",\n \"aws-ca-central-1\",\n ]),\n isDefault: Schema.Boolean,\n reference: Schema.String,\n dashboardEditConfirmation: Schema.Boolean.pipe(\n Schema.NullOr,\n Schema.optionalKey,\n ),\n deploymentUrl: Schema.String,\n expiresAt: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n class: Schema.String,\n sendLogsToClient: Schema.Boolean.pipe(Schema.NullOr, Schema.optionalKey),\n }),\n Schema.Struct({\n ...deploymentFields,\n kind: Schema.Literal(\"local\"),\n creator: Schema.Finite,\n port: Schema.Finite,\n deviceName: Schema.String,\n isActive: Schema.Boolean,\n }),\n]) satisfies Schema.Schema<Deployment>;\n\nconst DeployKeySchema = Schema.Struct({\n id: Schema.Finite,\n name: Schema.String,\n creationTime: Schema.Finite,\n lastUsedTime: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n expiresAt: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n creator: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n managedBy: Schema.Union([\n Schema.Literal(\"vercel\"),\n Schema.Struct({ oauthApp: Schema.String }),\n ]).pipe(Schema.NullOr, Schema.optionalKey),\n allowedActions: Schema.Array(Schema.String),\n}) satisfies Schema.Schema<DeployKey>;\n\nconst ProjectsPageSchema = Schema.Struct({\n items: Schema.Array(ProjectSchema),\n pagination: Schema.Struct({\n hasMore: Schema.Boolean,\n nextCursor: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n }),\n});\n\nconst make = Effect.fn(\"ConvexClient.make\")(function* (options?: {\n readonly token?: Redacted.Redacted<string>;\n readonly mode?: ProviderMode;\n}) {\n const http = yield* HttpClient.HttpClient;\n const managementAuthorization = Effect.gen(function* () {\n const token =\n options?.token ??\n (yield* Config.Redacted(\"CONVEX_ACCESS_TOKEN\").pipe(\n Effect.mapError(() =>\n ConvexApiError.make({\n operation: \"configure\",\n code: \"InvalidConfiguration\",\n }),\n ),\n ));\n return Redacted.make(`Bearer ${Redacted.value(token)}`);\n });\n const baseUrl = \"https://api.convex.dev/v1\";\n\n const send = Effect.fn(\"ConvexClient.request\")(function* (\n operation: string,\n method: \"GET\" | \"POST\" | \"PATCH\",\n url: string,\n authorization: Redacted.Redacted<string>,\n body?: unknown,\n ) {\n let request = HttpClientRequest.make(method)(url).pipe(\n HttpClientRequest.setHeader(\n \"authorization\",\n Redacted.value(authorization),\n ),\n HttpClientRequest.acceptJson,\n );\n if (body !== undefined) {\n request = yield* HttpClientRequest.bodyJson(request, body).pipe(\n Effect.mapError(() =>\n ConvexApiError.make({ operation, code: \"InvalidRequest\" }),\n ),\n );\n }\n const response = yield* http.execute(request).pipe(\n Effect.provideService(FetchHttpClient.RequestInit, {\n redirect: \"manual\",\n }),\n Effect.mapError(() =>\n ConvexApiError.make({ operation, code: \"TransportError\" }),\n ),\n );\n if (response.status === 404) {\n return yield* ConvexNotFound.make({\n operation,\n status: 404,\n code: \"HttpError\",\n });\n }\n if (response.status === 409) {\n return yield* ConvexConflict.make({\n operation,\n status: 409,\n code: \"HttpError\",\n });\n }\n if (response.status < 200 || response.status >= 300) {\n return yield* ConvexApiError.make({\n operation,\n status: response.status,\n code: \"HttpError\",\n });\n }\n return response;\n });\n\n const decode = Effect.fn(\"ConvexClient.decode\")(function* <A>(\n operation: string,\n response: HttpClientResponse.HttpClientResponse,\n schema: Schema.Decoder<A>,\n ) {\n const invalidResponse = () =>\n ConvexApiError.make({\n operation,\n status: response.status,\n code: \"InvalidResponse\",\n });\n const body = yield* response.json.pipe(Effect.mapError(invalidResponse));\n return yield* Schema.decodeEffect(schema)(body).pipe(\n Effect.mapError(invalidResponse),\n );\n });\n\n const management = Effect.fn(\"ConvexClient.management\")(function* <A>(\n operation: string,\n method: \"GET\" | \"POST\" | \"PATCH\",\n path: string,\n schema: Schema.Decoder<A>,\n body?: unknown,\n ) {\n const managementAuthorizationValue = yield* managementAuthorization;\n const response = yield* send(\n operation,\n method,\n `${baseUrl}${path}`,\n managementAuthorizationValue,\n body,\n );\n return yield* decode(operation, response, schema);\n });\n\n const managementVoid = Effect.fn(\"ConvexClient.managementVoid\")(function* (\n operation: string,\n method: \"POST\" | \"PATCH\",\n path: string,\n body?: unknown,\n ) {\n const managementAuthorizationValue = yield* managementAuthorization;\n yield* send(\n operation,\n method,\n `${baseUrl}${path}`,\n managementAuthorizationValue,\n body,\n );\n });\n\n const deploymentUrl = Effect.fn(\"ConvexClient.deploymentUrl\")(function* (\n operation: string,\n url: string,\n ) {\n const invalidUrl = () =>\n ConvexApiError.make({ operation, code: \"InvalidRequest\" });\n if (options?.mode === \"local\") {\n if (!Loopback.isOrigin(url)) return yield* invalidUrl();\n return `${url}/api/v1`;\n }\n const parsed = yield* Effect.try({\n try: () => new URL(url),\n catch: invalidUrl,\n });\n if (\n parsed.protocol !== \"https:\" ||\n parsed.username !== \"\" ||\n parsed.password !== \"\" ||\n parsed.port !== \"\" ||\n parsed.search !== \"\" ||\n parsed.hash !== \"\" ||\n parsed.pathname !== \"/\" ||\n !/^[a-z0-9-]+(?:\\.(?:eu-west-1|ap-southeast-2|ca-central-1))?\\.convex\\.cloud$/.test(\n parsed.hostname,\n ) ||\n pipe(url, String.replace(/\\/$/, \"\")) !== parsed.origin\n ) {\n return yield* invalidUrl();\n }\n return `${parsed.origin}/api/v1`;\n });\n\n return {\n /**\n * Run a deployment function with admin authority, internal ones and ones\n * inside a component included.\n */\n runFunction: Effect.fn(\"ConvexClient.runFunction\")(function* (\n url: string,\n key: Redacted.Redacted<string>,\n functionPath: string,\n args: unknown,\n componentPath?: string,\n ) {\n const operation = \"runFunction\";\n const deploymentUrlResult = yield* deploymentUrl(operation, url);\n const origin = pipe(\n deploymentUrlResult,\n String.replace(/\\/api\\/v1$/, \"\"),\n );\n const request = yield* HttpClientRequest.post(\n `${origin}/api/function`,\n ).pipe(\n HttpClientRequest.setHeader(\n \"authorization\",\n `Convex ${Redacted.value(key)}`,\n ),\n HttpClientRequest.acceptJson,\n HttpClientRequest.bodyJson({\n path: functionPath,\n args,\n format: \"json\",\n ...(componentPath === undefined ? {} : { componentPath }),\n }),\n Effect.mapError(() =>\n ConvexApiError.make({ operation, code: \"InvalidRequest\" }),\n ),\n );\n const response = yield* http.execute(request).pipe(\n Effect.provideService(FetchHttpClient.RequestInit, {\n redirect: \"manual\",\n }),\n Effect.mapError(() =>\n ConvexApiError.make({ operation, code: \"TransportError\" }),\n ),\n );\n // Convex answers a function that threw with 560 and its message.\n if (response.status !== 200 && response.status !== 560)\n return yield* ConvexApiError.make({\n operation,\n status: response.status,\n code: \"HttpError\",\n });\n const result = yield* decode(operation, response, FunctionResponse);\n if (result.status === \"error\")\n return yield* ConvexFunctionError.make({\n functionPath,\n errorMessage: result.errorMessage,\n });\n return result.value;\n }),\n listProjects: Effect.fn(\"ConvexClient.listProjects\")(function* (\n teamId: number,\n ) {\n const projects: Project[] = [];\n const seenCursors = new Set<string>();\n let cursor: string | undefined;\n while (true) {\n const page = yield* management(\n \"listProjects\",\n \"GET\",\n `/teams/${teamId}/projects${cursor === undefined ? \"\" : `?cursor=${encodeURIComponent(cursor)}`}`,\n ProjectsPageSchema,\n );\n projects.push(...page.items);\n if (!page.pagination.hasMore) return projects;\n const nextCursor = page.pagination.nextCursor;\n if (\n nextCursor === undefined ||\n nextCursor === null ||\n nextCursor === \"\" ||\n seenCursors.has(nextCursor)\n ) {\n return yield* ConvexApiError.make({\n operation: \"listProjects\",\n code: \"InvalidPagination\",\n });\n }\n seenCursors.add(nextCursor);\n cursor = nextCursor;\n }\n }),\n getProject: Effect.fn(\"ConvexClient.getProject\")((projectId: number) =>\n management(\"getProject\", \"GET\", `/projects/${projectId}`, ProjectSchema),\n ),\n createProject: Effect.fn(\"ConvexClient.createProject\")(\n (teamId: number, input: CreateProjectInput) =>\n management(\n \"createProject\",\n \"POST\",\n `/teams/${teamId}/create_project`,\n CreatedProjectSchema,\n input,\n ),\n ),\n updateProject: Effect.fn(\"ConvexClient.updateProject\")(\n (projectId: number, input: UpdateProjectInput) =>\n management(\n \"updateProject\",\n \"PATCH\",\n `/projects/${projectId}`,\n ProjectSchema,\n input,\n ),\n ),\n deleteProject: Effect.fn(\"ConvexClient.deleteProject\")(\n (projectId: number) =>\n managementVoid(\n \"deleteProject\",\n \"POST\",\n `/projects/${projectId}/delete`,\n ),\n ),\n listDeployments: Effect.fn(\"ConvexClient.listDeployments\")(\n (projectId: number) =>\n management(\n \"listDeployments\",\n \"GET\",\n `/projects/${projectId}/list_deployments`,\n Schema.Array(DeploymentSchema),\n ),\n ),\n getDeployment: Effect.fn(\"ConvexClient.getDeployment\")((name: string) =>\n management(\n \"getDeployment\",\n \"GET\",\n `/deployments/${encodeURIComponent(name)}`,\n DeploymentSchema,\n ),\n ),\n createDeployment: Effect.fn(\"ConvexClient.createDeployment\")(\n (projectId: number, input: CreateDeploymentInput) =>\n management(\n \"createDeployment\",\n \"POST\",\n `/projects/${projectId}/create_deployment`,\n DeploymentSchema,\n input,\n ),\n ),\n updateDeployment: Effect.fn(\"ConvexClient.updateDeployment\")(\n (name: string, input: UpdateDeploymentInput) =>\n managementVoid(\n \"updateDeployment\",\n \"PATCH\",\n `/deployments/${encodeURIComponent(name)}`,\n input,\n ),\n ),\n deleteDeployment: Effect.fn(\"ConvexClient.deleteDeployment\")(\n (name: string) =>\n managementVoid(\n \"deleteDeployment\",\n \"POST\",\n `/deployments/${encodeURIComponent(name)}/delete`,\n ),\n ),\n createDeployKey: Effect.fn(\"ConvexClient.createDeployKey\")(function* (\n name: string,\n input: CreateDeployKeyInput,\n ): Effect.fn.Return<CreatedDeployKey, ConvexClientError> {\n const response = yield* management(\n \"createDeployKey\",\n \"POST\",\n `/deployments/${encodeURIComponent(name)}/create_deploy_key`,\n Schema.Struct({ deployKey: Schema.String }),\n input,\n );\n return { deployKey: Redacted.make(response.deployKey) };\n }),\n listDeployKeys: Effect.fn(\"ConvexClient.listDeployKeys\")((name: string) =>\n management(\n \"listDeployKeys\",\n \"GET\",\n `/deployments/${encodeURIComponent(name)}/list_deploy_keys`,\n Schema.Array(DeployKeySchema),\n ),\n ),\n deleteDeployKey: Effect.fn(\"ConvexClient.deleteDeployKey\")(\n (name: string, id: string | Redacted.Redacted<string>) =>\n managementVoid(\n \"deleteDeployKey\",\n \"POST\",\n `/deployments/${encodeURIComponent(name)}/delete_deploy_key`,\n {\n id: Redacted.isRedacted(id) ? Redacted.value(id) : id,\n } satisfies ManagementApi.PlatformDeleteDeployKeyArgs,\n ),\n ),\n listEnvironmentVariables: Effect.fn(\n \"ConvexClient.listEnvironmentVariables\",\n )(function* (\n url: string,\n key: Redacted.Redacted<string>,\n ): Effect.fn.Return<EnvironmentVariables, ConvexClientError> {\n const response = yield* send(\n \"listEnvironmentVariables\",\n \"GET\",\n `${yield* deploymentUrl(\"listEnvironmentVariables\", url)}/list_environment_variables`,\n Redacted.make(`Convex ${Redacted.value(key)}`),\n );\n const result = yield* decode(\n \"listEnvironmentVariables\",\n response,\n Schema.Struct({\n environmentVariables: Schema.Record(Schema.String, Schema.String),\n }),\n );\n return Rec.fromEntries(\n Array.map(\n Rec.toEntries(result.environmentVariables),\n ([name, value]) => [name, Redacted.make(value)],\n ),\n );\n }),\n updateEnvironmentVariables: Effect.fn(\n \"ConvexClient.updateEnvironmentVariables\",\n )(function* (\n url: string,\n key: Redacted.Redacted<string>,\n changes: readonly EnvironmentVariableChange[],\n ) {\n yield* send(\n \"updateEnvironmentVariables\",\n \"POST\",\n `${yield* deploymentUrl(\"updateEnvironmentVariables\", url)}/update_environment_variables`,\n Redacted.make(`Convex ${Redacted.value(key)}`),\n {\n changes: Array.map(changes, ({ name, value }) => ({\n name,\n ...(value === undefined\n ? {}\n : {\n value: Redacted.isRedacted(value)\n ? Redacted.value(value)\n : value,\n }),\n })),\n } satisfies {\n readonly changes: Readonly<\n DeploymentApi.UpdateEnvVarsRequest[\"changes\"]\n >;\n },\n );\n }),\n };\n});\n\nexport class ConvexClient extends Context.Service<\n ConvexClient,\n Effect.Success<ReturnType<typeof make>>\n>()(\"@confect/alchemy/ConvexClient\") {}\n\n/**\n * `mode: \"local\"` sends deployment requests only to a loopback backend over\n * HTTP; the default accepts only Convex cloud HTTPS origins.\n *\n * @stability unstable\n */\nexport const layer = (options?: {\n readonly token?: Redacted.Redacted<string>;\n readonly mode?: ProviderMode;\n}) =>\n Layer.effect(ConvexClient, make(options).pipe(Effect.map(ConvexClient.of)));\n"],"mappings":";;;;;;;;;;;;;;;AAmEA,MAAM,cAAc;CAClB,WAAW,OAAO;CAClB,QAAQ,OAAO,YAAY,OAAO,MAAM;CACxC,MAAM,OAAO,SAAS;EACpB;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACH;AAEA,IAAa,iBAAb,cAAo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CAAC,MAAM,WAAW,CAAC,MAAM,SAAS,KAAK,KAAK,CAAC,CAChD,CACF;EACF,CAAC;EACD,4BAA4B,OAAO,GACjC,yCACF,CAAC,CAAC,WACA,KACA,KACA,SACA;GACA,OAAO,KACL,8BACA,QACA,GAAG,OAAO,cAAc,8BAA8B,GAAG,EAAE,gCAC3D,SAAS,KAAK,UAAU,SAAS,MAAM,GAAG,GAAG,GAC7C,EACE,SAAS,MAAM,IAAI,UAAU,EAAE,MAAM,aAAa;IAChD;IACA,GAAI,UAAU,KAAA,IACV,CAAC,IACD,EACE,OAAO,SAAS,WAAW,KAAK,IAC5B,SAAS,MAAM,KAAK,IACpB,MACN;GACN,EAAE,EACJ,CAKF;EACF,CAAC;CACH;AACF,CAAC;AAED,IAAa,eAAb,cAAkC,QAAQ,QAGxC,CAAC,CAAC,+BAA+B,CAAC,CAAC,CAAC;;;;;;;AAQtC,MAAa,SAAS,YAIpB,MAAM,OAAO,cAAc,KAAK,OAAO,CAAC,CAAC,KAAK,OAAO,IAAI,aAAa,EAAE,CAAC,CAAC"}
1
+ {"version":3,"file":"ConvexClient.js","names":["Loopback.isOrigin"],"sources":["../src/ConvexClient.ts"],"sourcesContent":["import type * as DeploymentApi from \"@convex-dev/platform/deploymentApi\";\nimport type * as ManagementApi from \"@convex-dev/platform/managementApi\";\nimport type { ProviderMode } from \"alchemy/ProviderMode\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\nimport * as FetchHttpClient from \"effect/http/FetchHttpClient\";\nimport * as HttpClient from \"effect/http/HttpClient\";\nimport * as HttpClientRequest from \"effect/http/HttpClientRequest\";\nimport type * as HttpClientResponse from \"effect/http/HttpClientResponse\";\nimport * as Loopback from \"./internal/Loopback.js\";\nimport * as String from \"effect/String\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Rec from \"effect/Record\";\n\nexport type Project = ManagementApi.ProjectResponse;\nexport type CreatedProject = ManagementApi.PlatformCreateProjectResponse;\nexport type Deployment = ManagementApi.PlatformDeploymentResponse;\nexport type DeployKey = Omit<\n ManagementApi.PlatformDeployKeyResponse,\n \"allowedActions\"\n> & {\n readonly allowedActions: readonly string[];\n};\nexport type CreateProjectInput = Pick<\n ManagementApi.PlatformCreateProjectArgs,\n \"projectName\"\n>;\nexport type UpdateProjectInput = Pick<\n ManagementApi.PlatformUpdateProjectArgs,\n \"name\"\n>;\nexport type CreateDeploymentInput = Pick<\n ManagementApi.PlatformCreateDeploymentArgs,\n \"type\" | \"region\" | \"class\" | \"expiresAt\"\n> & { readonly reference: string };\nexport type UpdateDeploymentInput = Pick<\n ManagementApi.PlatformUpdateDeploymentArgs,\n \"reference\" | \"expiresAt\" | \"sendLogsToClient\" | \"class\"\n>;\nexport type CreateDeployKeyInput = ManagementApi.PlatformCreateDeployKeyArgs;\nexport type CreatedDeployKey = {\n readonly deployKey: Redacted.Redacted<\n ManagementApi.PlatformCreateDeployKeyResponse[\"deployKey\"]\n >;\n};\nexport type EnvironmentVariableChange = Omit<\n DeploymentApi.UpdateEnvVarRequest,\n \"value\"\n> & {\n readonly value?:\n | Exclude<DeploymentApi.UpdateEnvVarRequest[\"value\"], undefined>\n | Redacted.Redacted<string>;\n};\nexport type EnvironmentVariables = Readonly<\n Record<\n string,\n Redacted.Redacted<\n DeploymentApi.ListEnvVarsResponse[\"environmentVariables\"][string]\n >\n >\n>;\n\nconst errorFields = {\n operation: Schema.String,\n status: Schema.optionalKey(Schema.Finite),\n code: Schema.Literals([\n \"HttpError\",\n \"TransportError\",\n \"InvalidResponse\",\n \"InvalidRequest\",\n \"InvalidPagination\",\n \"InvalidConfiguration\",\n ]),\n};\n\nexport class ConvexApiError extends Schema.TaggedError<\n ConvexApiError,\n { readonly brand: unique symbol }\n>()(\"ConvexApiError\", errorFields) {}\n\nexport class ConvexNotFound extends Schema.TaggedError<\n ConvexNotFound,\n { readonly brand: unique symbol }\n>()(\"ConvexNotFound\", errorFields) {}\n\nexport class ConvexConflict extends Schema.TaggedError<\n ConvexConflict,\n { readonly brand: unique symbol }\n>()(\"ConvexConflict\", errorFields) {}\n\n/**\n * A function the deployment ran failed, with the message Convex reports.\n */\nexport class ConvexFunctionError extends Schema.TaggedError<\n ConvexFunctionError,\n { readonly brand: unique symbol }\n>()(\"ConvexFunctionError\", {\n functionPath: Schema.String,\n errorMessage: Schema.String,\n}) {}\n\nconst FunctionResponse = Schema.Union([\n Schema.Struct({ status: Schema.Literal(\"success\"), value: Schema.Unknown }),\n Schema.Struct({\n status: Schema.Literal(\"error\"),\n errorMessage: Schema.String,\n }),\n]);\n\nexport type ConvexClientError =\n | ConvexApiError\n | ConvexNotFound\n | ConvexConflict;\n\nconst ProjectSchema = Schema.Struct({\n id: Schema.Finite,\n name: Schema.String,\n slug: Schema.String,\n teamId: Schema.Finite,\n teamSlug: Schema.String,\n createTime: Schema.Finite,\n prodDeploymentName: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n devDeploymentName: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n}) satisfies Schema.Schema<Project>;\n\nconst CreatedProjectSchema = Schema.Struct({\n id: Schema.Finite,\n projectId: Schema.Finite,\n slug: Schema.String,\n deploymentName: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n deploymentUrl: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n}) satisfies Schema.Schema<CreatedProject>;\n\nconst deploymentFields = {\n name: Schema.String,\n createTime: Schema.Finite,\n deploymentType: Schema.Literals([\"dev\", \"prod\", \"preview\", \"custom\"]),\n projectId: Schema.Finite,\n previewIdentifier: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n};\n\nconst DeploymentSchema = Schema.Union([\n Schema.Struct({\n ...deploymentFields,\n kind: Schema.Literal(\"cloud\"),\n id: Schema.Finite,\n lastDeployTime: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n creator: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n region: Schema.Literals([\n \"aws-us-east-1\",\n \"aws-eu-west-1\",\n \"aws-ap-southeast-2\",\n \"aws-ca-central-1\",\n ]),\n isDefault: Schema.Boolean,\n reference: Schema.String,\n dashboardEditConfirmation: Schema.Boolean.pipe(\n Schema.NullOr,\n Schema.optionalKey,\n ),\n deploymentUrl: Schema.String,\n expiresAt: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n class: Schema.String,\n sendLogsToClient: Schema.Boolean.pipe(Schema.NullOr, Schema.optionalKey),\n }),\n Schema.Struct({\n ...deploymentFields,\n kind: Schema.Literal(\"local\"),\n creator: Schema.Finite,\n port: Schema.Finite,\n deviceName: Schema.String,\n isActive: Schema.Boolean,\n }),\n]) satisfies Schema.Schema<Deployment>;\n\nconst DeployKeySchema = Schema.Struct({\n id: Schema.Finite,\n name: Schema.String,\n creationTime: Schema.Finite,\n lastUsedTime: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n expiresAt: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n creator: Schema.Finite.pipe(Schema.NullOr, Schema.optionalKey),\n managedBy: Schema.Union([\n Schema.Literal(\"vercel\"),\n Schema.Struct({ oauthApp: Schema.String }),\n ]).pipe(Schema.NullOr, Schema.optionalKey),\n allowedActions: Schema.Array(Schema.String),\n}) satisfies Schema.Schema<DeployKey>;\n\nconst ProjectsPageSchema = Schema.Struct({\n items: Schema.Array(ProjectSchema),\n pagination: Schema.Struct({\n hasMore: Schema.Boolean,\n nextCursor: Schema.String.pipe(Schema.NullOr, Schema.optionalKey),\n }),\n});\n\nconst make = Effect.fn(\"ConvexClient.make\")(function* (options?: {\n readonly token?: Redacted.Redacted<string>;\n readonly mode?: ProviderMode;\n}) {\n const http = yield* HttpClient.HttpClient;\n const managementAuthorization = Effect.gen(function* () {\n const token =\n options?.token ??\n (yield* Config.Redacted(\"CONVEX_ACCESS_TOKEN\").pipe(\n Effect.mapError(() =>\n ConvexApiError.make({\n operation: \"configure\",\n code: \"InvalidConfiguration\",\n }),\n ),\n ));\n return Redacted.make(`Bearer ${Redacted.value(token)}`);\n });\n const baseUrl = \"https://api.convex.dev/v1\";\n\n const send = Effect.fn(\"ConvexClient.request\")(function* (\n operation: string,\n method: \"GET\" | \"POST\" | \"PATCH\",\n url: string,\n authorization: Redacted.Redacted<string>,\n body?: unknown,\n ) {\n let request = HttpClientRequest.make(method)(url).pipe(\n HttpClientRequest.setHeader(\n \"authorization\",\n Redacted.value(authorization),\n ),\n HttpClientRequest.acceptJson,\n );\n if (body !== undefined) {\n request = yield* HttpClientRequest.bodyJson(request, body).pipe(\n Effect.mapError(() =>\n ConvexApiError.make({ operation, code: \"InvalidRequest\" }),\n ),\n );\n }\n const response = yield* http.execute(request).pipe(\n Effect.provideService(FetchHttpClient.RequestInit, {\n redirect: \"manual\",\n }),\n Effect.mapError(() =>\n ConvexApiError.make({ operation, code: \"TransportError\" }),\n ),\n );\n if (response.status === 404) {\n return yield* ConvexNotFound.make({\n operation,\n status: 404,\n code: \"HttpError\",\n });\n }\n if (response.status === 409) {\n return yield* ConvexConflict.make({\n operation,\n status: 409,\n code: \"HttpError\",\n });\n }\n if (response.status < 200 || response.status >= 300) {\n return yield* ConvexApiError.make({\n operation,\n status: response.status,\n code: \"HttpError\",\n });\n }\n return response;\n });\n\n const decode = Effect.fn(\"ConvexClient.decode\")(function* <A>(\n operation: string,\n response: HttpClientResponse.HttpClientResponse,\n schema: Schema.Decoder<A>,\n ) {\n const invalidResponse = () =>\n ConvexApiError.make({\n operation,\n status: response.status,\n code: \"InvalidResponse\",\n });\n const body = yield* response.json.pipe(Effect.mapError(invalidResponse));\n return yield* Schema.decodeEffect(schema)(body).pipe(\n Effect.mapError(invalidResponse),\n );\n });\n\n const management = Effect.fn(\"ConvexClient.management\")(function* <A>(\n operation: string,\n method: \"GET\" | \"POST\" | \"PATCH\",\n path: string,\n schema: Schema.Decoder<A>,\n body?: unknown,\n ) {\n const managementAuthorizationValue = yield* managementAuthorization;\n const response = yield* send(\n operation,\n method,\n `${baseUrl}${path}`,\n managementAuthorizationValue,\n body,\n );\n return yield* decode(operation, response, schema);\n });\n\n const managementVoid = Effect.fn(\"ConvexClient.managementVoid\")(function* (\n operation: string,\n method: \"POST\" | \"PATCH\",\n path: string,\n body?: unknown,\n ) {\n const managementAuthorizationValue = yield* managementAuthorization;\n yield* send(\n operation,\n method,\n `${baseUrl}${path}`,\n managementAuthorizationValue,\n body,\n );\n });\n\n const deploymentUrl = Effect.fn(\"ConvexClient.deploymentUrl\")(function* (\n operation: string,\n url: string,\n ) {\n const invalidUrl = () =>\n ConvexApiError.make({ operation, code: \"InvalidRequest\" });\n if (options?.mode === \"local\") {\n if (!Loopback.isOrigin(url)) return yield* invalidUrl();\n return `${url}/api/v1`;\n }\n const parsed = yield* Effect.try({\n try: () => new URL(url),\n catch: invalidUrl,\n });\n if (\n parsed.protocol !== \"https:\" ||\n parsed.username !== \"\" ||\n parsed.password !== \"\" ||\n parsed.port !== \"\" ||\n parsed.search !== \"\" ||\n parsed.hash !== \"\" ||\n parsed.pathname !== \"/\" ||\n !/^[a-z0-9-]+(?:\\.(?:eu-west-1|ap-southeast-2|ca-central-1))?\\.convex\\.cloud$/.test(\n parsed.hostname,\n ) ||\n pipe(url, String.replace(/\\/$/, \"\")) !== parsed.origin\n ) {\n return yield* invalidUrl();\n }\n return `${parsed.origin}/api/v1`;\n });\n\n return {\n /**\n * Run a deployment function with admin authority, internal ones and ones\n * inside a component included.\n */\n runFunction: Effect.fn(\"ConvexClient.runFunction\")(function* (\n url: string,\n key: Redacted.Redacted<string>,\n functionPath: string,\n args: unknown,\n componentPath?: string,\n ) {\n const operation = \"runFunction\";\n const deploymentUrlResult = yield* deploymentUrl(operation, url);\n const origin = pipe(\n deploymentUrlResult,\n String.replace(/\\/api\\/v1$/, \"\"),\n );\n const request = yield* HttpClientRequest.post(\n `${origin}/api/function`,\n ).pipe(\n HttpClientRequest.setHeader(\n \"authorization\",\n `Convex ${Redacted.value(key)}`,\n ),\n HttpClientRequest.acceptJson,\n HttpClientRequest.bodyJson({\n path: functionPath,\n args,\n format: \"json\",\n ...(componentPath === undefined ? {} : { componentPath }),\n }),\n Effect.mapError(() =>\n ConvexApiError.make({ operation, code: \"InvalidRequest\" }),\n ),\n );\n const response = yield* http.execute(request).pipe(\n Effect.provideService(FetchHttpClient.RequestInit, {\n redirect: \"manual\",\n }),\n Effect.mapError(() =>\n ConvexApiError.make({ operation, code: \"TransportError\" }),\n ),\n );\n // Convex answers a function that threw with 560 and its message.\n if (response.status !== 200 && response.status !== 560)\n return yield* ConvexApiError.make({\n operation,\n status: response.status,\n code: \"HttpError\",\n });\n const result = yield* decode(operation, response, FunctionResponse);\n if (result.status === \"error\")\n return yield* ConvexFunctionError.make({\n functionPath,\n errorMessage: result.errorMessage,\n });\n return result.value;\n }),\n listProjects: Effect.fn(\"ConvexClient.listProjects\")(function* (\n teamId: number,\n ) {\n const projects: Project[] = [];\n const seenCursors = new Set<string>();\n let cursor: string | undefined;\n while (true) {\n const page = yield* management(\n \"listProjects\",\n \"GET\",\n `/teams/${teamId}/projects${cursor === undefined ? \"\" : `?cursor=${encodeURIComponent(cursor)}`}`,\n ProjectsPageSchema,\n );\n projects.push(...page.items);\n if (!page.pagination.hasMore) return projects;\n const nextCursor = page.pagination.nextCursor;\n if (\n nextCursor === undefined ||\n nextCursor === null ||\n nextCursor === \"\" ||\n seenCursors.has(nextCursor)\n ) {\n return yield* ConvexApiError.make({\n operation: \"listProjects\",\n code: \"InvalidPagination\",\n });\n }\n seenCursors.add(nextCursor);\n cursor = nextCursor;\n }\n }),\n getProject: Effect.fn(\"ConvexClient.getProject\")((projectId: number) =>\n management(\"getProject\", \"GET\", `/projects/${projectId}`, ProjectSchema),\n ),\n createProject: Effect.fn(\"ConvexClient.createProject\")(\n (teamId: number, input: CreateProjectInput) =>\n management(\n \"createProject\",\n \"POST\",\n `/teams/${teamId}/create_project`,\n CreatedProjectSchema,\n input,\n ),\n ),\n updateProject: Effect.fn(\"ConvexClient.updateProject\")(\n (projectId: number, input: UpdateProjectInput) =>\n management(\n \"updateProject\",\n \"PATCH\",\n `/projects/${projectId}`,\n ProjectSchema,\n input,\n ),\n ),\n deleteProject: Effect.fn(\"ConvexClient.deleteProject\")(\n (projectId: number) =>\n managementVoid(\n \"deleteProject\",\n \"POST\",\n `/projects/${projectId}/delete`,\n ),\n ),\n listDeployments: Effect.fn(\"ConvexClient.listDeployments\")(\n (projectId: number) =>\n management(\n \"listDeployments\",\n \"GET\",\n `/projects/${projectId}/list_deployments`,\n Schema.Array(DeploymentSchema),\n ),\n ),\n getDeployment: Effect.fn(\"ConvexClient.getDeployment\")((name: string) =>\n management(\n \"getDeployment\",\n \"GET\",\n `/deployments/${encodeURIComponent(name)}`,\n DeploymentSchema,\n ),\n ),\n createDeployment: Effect.fn(\"ConvexClient.createDeployment\")(\n (projectId: number, input: CreateDeploymentInput) =>\n management(\n \"createDeployment\",\n \"POST\",\n `/projects/${projectId}/create_deployment`,\n DeploymentSchema,\n input,\n ),\n ),\n updateDeployment: Effect.fn(\"ConvexClient.updateDeployment\")(\n (name: string, input: UpdateDeploymentInput) =>\n managementVoid(\n \"updateDeployment\",\n \"PATCH\",\n `/deployments/${encodeURIComponent(name)}`,\n input,\n ),\n ),\n deleteDeployment: Effect.fn(\"ConvexClient.deleteDeployment\")(\n (name: string) =>\n managementVoid(\n \"deleteDeployment\",\n \"POST\",\n `/deployments/${encodeURIComponent(name)}/delete`,\n ),\n ),\n createDeployKey: Effect.fn(\"ConvexClient.createDeployKey\")(function* (\n name: string,\n input: CreateDeployKeyInput,\n ): Effect.fn.Return<CreatedDeployKey, ConvexClientError> {\n const response = yield* management(\n \"createDeployKey\",\n \"POST\",\n `/deployments/${encodeURIComponent(name)}/create_deploy_key`,\n Schema.Struct({ deployKey: Schema.String }),\n input,\n );\n return { deployKey: Redacted.make(response.deployKey) };\n }),\n listDeployKeys: Effect.fn(\"ConvexClient.listDeployKeys\")((name: string) =>\n management(\n \"listDeployKeys\",\n \"GET\",\n `/deployments/${encodeURIComponent(name)}/list_deploy_keys`,\n Schema.Array(DeployKeySchema),\n ),\n ),\n deleteDeployKey: Effect.fn(\"ConvexClient.deleteDeployKey\")(\n (name: string, id: string | Redacted.Redacted<string>) =>\n managementVoid(\n \"deleteDeployKey\",\n \"POST\",\n `/deployments/${encodeURIComponent(name)}/delete_deploy_key`,\n {\n id: Redacted.isRedacted(id) ? Redacted.value(id) : id,\n } satisfies ManagementApi.PlatformDeleteDeployKeyArgs,\n ),\n ),\n listEnvironmentVariables: Effect.fn(\n \"ConvexClient.listEnvironmentVariables\",\n )(function* (\n url: string,\n key: Redacted.Redacted<string>,\n ): Effect.fn.Return<EnvironmentVariables, ConvexClientError> {\n const response = yield* send(\n \"listEnvironmentVariables\",\n \"GET\",\n `${yield* deploymentUrl(\"listEnvironmentVariables\", url)}/list_environment_variables`,\n Redacted.make(`Convex ${Redacted.value(key)}`),\n );\n const result = yield* decode(\n \"listEnvironmentVariables\",\n response,\n Schema.Struct({\n environmentVariables: Schema.Record(Schema.String, Schema.String),\n }),\n );\n return Rec.fromEntries(\n Array.map(\n Rec.toEntries(result.environmentVariables),\n ([name, value]) => [name, Redacted.make(value)],\n ),\n );\n }),\n updateEnvironmentVariables: Effect.fn(\n \"ConvexClient.updateEnvironmentVariables\",\n )(function* (\n url: string,\n key: Redacted.Redacted<string>,\n changes: readonly EnvironmentVariableChange[],\n ) {\n yield* send(\n \"updateEnvironmentVariables\",\n \"POST\",\n `${yield* deploymentUrl(\"updateEnvironmentVariables\", url)}/update_environment_variables`,\n Redacted.make(`Convex ${Redacted.value(key)}`),\n {\n changes: Array.map(changes, ({ name, value }) => ({\n name,\n ...(value === undefined\n ? {}\n : {\n value: Redacted.isRedacted(value)\n ? Redacted.value(value)\n : value,\n }),\n })),\n } satisfies {\n readonly changes: Readonly<\n DeploymentApi.UpdateEnvVarsRequest[\"changes\"]\n >;\n },\n );\n }),\n };\n});\n\nexport class ConvexClient extends Context.Service<\n ConvexClient,\n Effect.Success<ReturnType<typeof make>>\n>()(\"@confect/alchemy/ConvexClient\") {}\n\n/**\n * `mode: \"local\"` sends deployment requests only to a loopback backend over\n * HTTP; the default accepts only Convex cloud HTTPS origins.\n *\n * @stability unstable\n */\nexport const layer = (options?: {\n readonly token?: Redacted.Redacted<string>;\n readonly mode?: ProviderMode;\n}) =>\n Layer.effect(ConvexClient, make(options).pipe(Effect.map(ConvexClient.of)));\n"],"mappings":";;;;;;;;;;;;;;;AAmEA,MAAM,cAAc;CAClB,WAAW,OAAO;CAClB,QAAQ,OAAO,YAAY,OAAO,MAAM;CACxC,MAAM,OAAO,SAAS;EACpB;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACH;AAEA,IAAa,iBAAb,cAAoC,OAAO,YAGzC,CAAC,CAAC,kBAAkB,WAAW,CAAC,CAAC,CAAC;AAEpC,IAAa,iBAAb,cAAoC,OAAO,YAGzC,CAAC,CAAC,kBAAkB,WAAW,CAAC,CAAC,CAAC;AAEpC,IAAa,iBAAb,cAAoC,OAAO,YAGzC,CAAC,CAAC,kBAAkB,WAAW,CAAC,CAAC,CAAC;;;;AAKpC,IAAa,sBAAb,cAAyC,OAAO,YAG9C,CAAC,CAAC,uBAAuB;CACzB,cAAc,OAAO;CACrB,cAAc,OAAO;AACvB,CAAC,CAAC,CAAC,CAAC;AAEJ,MAAM,mBAAmB,OAAO,MAAM,CACpC,OAAO,OAAO;CAAE,QAAQ,OAAO,QAAQ,SAAS;CAAG,OAAO,OAAO;AAAQ,CAAC,GAC1E,OAAO,OAAO;CACZ,QAAQ,OAAO,QAAQ,OAAO;CAC9B,cAAc,OAAO;AACvB,CAAC,CACH,CAAC;AAOD,MAAM,gBAAgB,OAAO,OAAO;CAClC,IAAI,OAAO;CACX,MAAM,OAAO;CACb,MAAM,OAAO;CACb,QAAQ,OAAO;CACf,UAAU,OA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import type { CreateDeploymentType, RegionName } from "@convex-dev/platform/managementApi";
1
+ import type { CreateDeploymentType, DeploymentClass, RegionName } from "@convex-dev/platform/managementApi";
2
2
  import { OwnedBySomeoneElse } from "alchemy/AdoptPolicy";
3
3
  import * as Provider from "alchemy/Provider";
4
4
  import { Resource } from "alchemy/Resource";
@@ -12,6 +12,12 @@ export interface DeploymentProps {
12
12
  readonly type: CreateDeploymentType;
13
13
  readonly reference?: string;
14
14
  readonly region?: RegionName;
15
+ readonly class?: DeploymentClass;
16
+ /**
17
+ * Safe integer milliseconds since the Unix epoch. Omit to preserve the
18
+ * current cloud expiry; only null clears it.
19
+ */
20
+ readonly expiresAt?: number | null;
15
21
  }
16
22
  export interface DeploymentAttributes {
17
23
  readonly projectId: number;
@@ -23,6 +29,14 @@ export interface DeploymentAttributes {
23
29
  * Always set in the cloud; a local deployment echoes the requested region.
24
30
  */
25
31
  readonly region?: RegionName;
32
+ /**
33
+ * Always set in the cloud; local deployments do not have a cloud class.
34
+ */
35
+ readonly class?: string;
36
+ /**
37
+ * Cloud expiry in milliseconds since the Unix epoch, or null when unset.
38
+ */
39
+ readonly expiresAt?: number | null;
26
40
  }
27
41
  export type Deployment = Resource<"Convex.Deployment", DeploymentProps, DeploymentAttributes, never, Providers>;
28
42
  export declare const Deployment: import("alchemy").ResourceClass<Deployment>;
@@ -51,6 +65,14 @@ declare const AmbiguousDeployment_base: Schema.Class<AmbiguousDeployment, Schema
51
65
  }>;
52
66
  export declare class AmbiguousDeployment extends AmbiguousDeployment_base {
53
67
  }
68
+ declare const InvalidDeploymentExpiry_base: Schema.Class<InvalidDeploymentExpiry, Schema.TaggedStruct<"InvalidDeploymentExpiry", {
69
+ readonly requested: Schema.String;
70
+ }>, import("effect/Cause").YieldableError & {
71
+ readonly brand: unique symbol;
72
+ }>;
73
+ export declare class InvalidDeploymentExpiry extends InvalidDeploymentExpiry_base {
74
+ get message(): string;
75
+ }
54
76
  export declare const provider: Effect.Effect<{
55
77
  diff: (args_0: {
56
78
  id: string;
@@ -63,7 +85,7 @@ export declare const provider: Effect.Effect<{
63
85
  output: DeploymentAttributes | undefined;
64
86
  }) => Effect.Effect<{
65
87
  action: "update";
66
- } | undefined, import("./ConvexClient.js").ConvexApiError | import("./ConvexClient.js").ConvexConflict | DeploymentIdentityChange | UnsupportedLocalDeployment, never>;
88
+ } | undefined, import("./ConvexClient.js").ConvexApiError | import("./ConvexClient.js").ConvexConflict | DeploymentIdentityChange | InvalidDeploymentExpiry | UnsupportedLocalDeployment, never>;
67
89
  read: (args_0: {
68
90
  id: string;
69
91
  fqn: string;
@@ -78,6 +100,8 @@ export declare const provider: Effect.Effect<{
78
100
  type: "custom" | "dev" | "preview" | "prod";
79
101
  url: string;
80
102
  region: "aws-ap-southeast-2" | "aws-ca-central-1" | "aws-eu-west-1" | "aws-us-east-1";
103
+ class: string;
104
+ expiresAt: number | null;
81
105
  } | undefined, AmbiguousDeployment | import("./ConvexClient.js").ConvexApiError | import("./ConvexClient.js").ConvexConflict | import("./ConvexClient.js").ConvexNotFound | UnsupportedLocalDeployment, never>;
82
106
  reconcile: (args_0: {
83
107
  id: string;
@@ -95,7 +119,9 @@ export declare const provider: Effect.Effect<{
95
119
  type: "custom" | "dev" | "preview" | "prod";
96
120
  url: string;
97
121
  region: "aws-ap-southeast-2" | "aws-ca-central-1" | "aws-eu-west-1" | "aws-us-east-1";
98
- }, AmbiguousDeployment | import("./ConvexClient.js").ConvexApiError | import("./ConvexClient.js").ConvexConflict | import("./ConvexClient.js").ConvexNotFound | DeploymentIdentityChange | import("./internal/Lifecycle.js").LifecycleStateError | OwnedBySomeoneElse | import("alchemy/State/State").StateStoreError | UnsupportedLocalDeployment, never>;
122
+ class: string;
123
+ expiresAt: number | null;
124
+ }, AmbiguousDeployment | import("./ConvexClient.js").ConvexApiError | import("./ConvexClient.js").ConvexConflict | import("./ConvexClient.js").ConvexNotFound | DeploymentIdentityChange | InvalidDeploymentExpiry | import("./internal/Lifecycle.js").LifecycleStateError | OwnedBySomeoneElse | import("alchemy/State/State").StateStoreError | UnsupportedLocalDeployment, never>;
99
125
  delete: (args_0: {
100
126
  id: string;
101
127
  fqn: string;
@@ -1 +1 @@
1
- {"version":3,"file":"Deployment.d.ts","sources":["../src/Deployment.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oBAAoB,EAEpB,UAAU,EACX,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAW,MAAM,qBAAqB,CAAC;AAGlE,OAAO,KAAK,QAAQ,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,UAAU,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAExC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAMhD,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,oBAAoB,CAAC;IACpC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,CAAC,EAAE,UAAU,CAAC;CAC9B;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,EAAE,oBAAoB,CAAC;IACpC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,UAAU,CAAC;CAC9B;AAED,MAAM,MAAM,UAAU,GAAG,QAAQ,CAC/B,mBAAmB,E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AAEF,eAAO,MAAM,KAAK,kFAAwC,CAAC"}
@@ -25,6 +25,14 @@ var AmbiguousDeployment = class extends Schema.TaggedError()("AmbiguousDeploymen
25
25
  projectId: Schema.Finite,
26
26
  reference: Schema.String
27
27
  }) {};
28
+ var InvalidDeploymentExpiry = class extends Schema.TaggedError()("InvalidDeploymentExpiry", { requested: Schema.String }) {
29
+ get message() {
30
+ return "Deployment expiresAt must be a safe integer timestamp in milliseconds, or null to clear the expiry.";
31
+ }
32
+ };
33
+ const validateExpiry = Effect.fn("Deployment.validateExpiry")(function* ({ expiresAt }) {
34
+ if (expiresAt != null && !Number.isSafeInteger(expiresAt)) return yield* InvalidDeploymentExpiry.make({ requested: String(expiresAt) });
35
+ });
28
36
  const provider = Effect.gen(function* () {
29
37
  const client = yield* ConvexClient;
30
38
  const attributes = Effect.fn("Deployment.attributes")(function* (deployment) {
@@ -35,7 +43,9 @@ const provider = Effect.gen(function* () {
35
43
  reference: deployment.reference,
36
44
  type: deployment.deploymentType,
37
45
  url: deployment.deploymentUrl,
38
- region: deployment.region
46
+ region: deployment.region,
47
+ class: deployment.class,
48
+ expiresAt: deployment.expiresAt ?? null
39
49
  };
40
50
  });
41
51
  const find = Effect.fn("Deployment.find")(function* (projectId, reference) {
@@ -61,13 +71,16 @@ const provider = Effect.gen(function* () {
61
71
  });
62
72
  return {
63
73
  diff: Effect.fn("Deployment.diff")(function* ({ news, output }) {
64
- if (!isResolved(news) || output === void 0) return;
74
+ if (!isResolved(news)) return;
75
+ yield* validateExpiry(news);
76
+ if (output === void 0) return;
77
+ const expiresAt = news.expiresAt;
65
78
  yield* validate(output, news);
66
79
  const deployment = yield* client.getDeployment(output.name).pipe(Effect.catchTag("ConvexNotFound", () => Effect.void));
67
80
  if (deployment === void 0) return { action: "update" };
68
81
  const current = yield* attributes(deployment);
69
82
  yield* validate(current, news);
70
- if ((news.reference ?? output.reference) !== current.reference) return { action: "update" };
83
+ if ((news.reference ?? output.reference) !== current.reference || news.class !== void 0 && news.class !== current.class || expiresAt !== void 0 && expiresAt !== (current.expiresAt ?? null)) return { action: "update" };
71
84
  }),
72
85
  read: Effect.fn("Deployment.read")(function* ({ fqn, instanceId, olds, output }) {
73
86
  if (output !== void 0) {
@@ -79,10 +92,12 @@ const provider = Effect.gen(function* () {
79
92
  return deployment !== void 0 ? yield* Effect.map(attributes(deployment), Unowned) : void 0;
80
93
  }),
81
94
  reconcile: Effect.fn("Deployment.reconcile")(function* ({ fqn, instanceId, news, output }) {
95
+ yield* validateExpiry(news);
82
96
  if (output === void 0) yield* checkpointCreate(fqn, instanceId, news);
83
97
  if (output !== void 0) yield* validate(output, news);
84
98
  let deployment = output !== void 0 ? yield* client.getDeployment(output.name).pipe(Effect.catchTag("ConvexNotFound", () => Effect.void)) : void 0;
85
99
  const reference = news.reference ?? output?.reference ?? (yield* resourceName("deployment", fqn, instanceId));
100
+ const expiresAt = news.expiresAt;
86
101
  if (deployment === void 0) {
87
102
  const existing = yield* find(news.projectId, reference);
88
103
  if (existing !== void 0 && !(yield* shouldAdopt(fqn))) return yield* new OwnedBySomeoneElse({
@@ -98,19 +113,27 @@ const provider = Effect.gen(function* () {
98
113
  } else deployment = yield* client.createDeployment(news.projectId, {
99
114
  type: news.type,
100
115
  reference,
101
- ...news.region === void 0 ? {} : { region: news.region }
116
+ ...news.region === void 0 ? {} : { region: news.region },
117
+ ...news.class === void 0 ? {} : { class: news.class },
118
+ ...expiresAt === void 0 ? {} : { expiresAt }
102
119
  });
103
120
  }
104
121
  const current = yield* attributes(deployment);
105
122
  yield* validate(current, news);
106
- if (current.reference !== reference) {
107
- const existing = yield* find(news.projectId, reference);
108
- if (existing !== void 0 && existing.name !== current.name) return yield* new OwnedBySomeoneElse({
109
- message: "The requested deployment reference is already in use.",
110
- resourceType: Deployment.Type,
111
- physicalName: reference
123
+ if (current.reference !== reference || news.class !== void 0 && news.class !== current.class || expiresAt !== void 0 && expiresAt !== (current.expiresAt ?? null)) {
124
+ if (current.reference !== reference) {
125
+ const existing = yield* find(news.projectId, reference);
126
+ if (existing !== void 0 && existing.name !== current.name) return yield* new OwnedBySomeoneElse({
127
+ message: "The requested deployment reference is already in use.",
128
+ resourceType: Deployment.Type,
129
+ physicalName: reference
130
+ });
131
+ }
132
+ yield* client.updateDeployment(current.name, {
133
+ reference,
134
+ ...news.class === void 0 || news.class === current.class ? {} : { class: news.class },
135
+ ...expiresAt === void 0 || expiresAt === (current.expiresAt ?? null) ? {} : { expiresAt }
112
136
  });
113
- yield* client.updateDeployment(current.name, { reference });
114
137
  deployment = yield* client.getDeployment(current.name);
115
138
  }
116
139
  return yield* attributes(deployment);
@@ -134,9 +157,10 @@ const localLayer = LocalProvider.make(Deployment, new URL(`./internal/LocalSidec
134
157
  const directory = yield* dataDirectories;
135
158
  return {
136
159
  resolveConfig: Effect.fn("Deployment.localConfig")(function* ({ fqn, instanceId, news }) {
160
+ const { class: _class, expiresAt: _expiresAt, ...props } = news;
137
161
  return {
138
162
  name: yield* resourceName("deployment", fqn, instanceId),
139
- props: news
163
+ props
140
164
  };
141
165
  }),
142
166
  start: Effect.fn("Deployment.localStart")(function* ({ config, invalidate }) {
@@ -158,6 +182,6 @@ const localLayer = LocalProvider.make(Deployment, new URL(`./internal/LocalSidec
158
182
  };
159
183
  }));
160
184
  const layer = Provider.effect(Deployment, provider);
161
- export { AmbiguousDeployment, Deployment, DeploymentIdentityChange, UnsupportedLocalDeployment, layer, localLayer, provider };
185
+ export { AmbiguousDeployment, Deployment, DeploymentIdentityChange, InvalidDeploymentExpiry, UnsupportedLocalDeployment, layer, localLayer, provider };
162
186
 
163
187
  //# sourceMappingURL=Deployment.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Deployment.js","names":[],"sources":["../src/Deployment.ts"],"sourcesContent":["import type {\n CreateDeploymentType,\n PlatformDeploymentResponse,\n RegionName,\n} from \"@convex-dev/platform/managementApi\";\nimport { OwnedBySomeoneElse, Unowned } from \"alchemy/AdoptPolicy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as LocalProvider from \"alchemy/Local/LocalProvider\";\nimport * as Provider from \"alchemy/Provider\";\nimport { Resource } from \"alchemy/Resource\";\nimport { moduleExtension } from \"alchemy/Util/Node\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Schema from \"effect/Schema\";\n\nimport { ConvexClient } from \"./ConvexClient.js\";\nimport type { Providers } from \"./Providers.js\";\nimport { resourceName } from \"./internal/ResourceIdentity.js\";\nimport { checkpointCreate, shouldAdopt } from \"./internal/Lifecycle.js\";\nimport { boot, dataDirectories, remove } from \"./internal/LocalBackend.js\";\nimport * as Array from \"effect/Array\";\n\nexport interface DeploymentProps {\n readonly projectId: number;\n readonly type: CreateDeploymentType;\n readonly reference?: string;\n readonly region?: RegionName;\n}\n\nexport interface DeploymentAttributes {\n readonly projectId: number;\n readonly name: string;\n readonly reference: string;\n readonly type: CreateDeploymentType;\n readonly url: string;\n /**\n * Always set in the cloud; a local deployment echoes the requested region.\n */\n readonly region?: RegionName;\n}\n\nexport type Deployment = Resource<\n \"Convex.Deployment\",\n DeploymentProps,\n DeploymentAttributes,\n never,\n Providers\n>;\nexport const Deployment = Resource<Deployment>(\"Convex.Deployment\", {\n defaultRemovalPolicy: \"retain\",\n});\n\nexport class DeploymentIdentityChange extends Schema.TaggedError<\n DeploymentIdentityChange,\n { readonly brand: unique symbol }\n>()(\"DeploymentIdentityChange\", {\n deploymentName: Schema.String,\n field: Schema.String,\n current: Schema.String,\n requested: Schema.String,\n}) {}\n\nexport class UnsupportedLocalDeployment extends Schema.TaggedError<\n UnsupportedLocalDeployment,\n { readonly brand: unique symbol }\n>()(\"UnsupportedLocalDeployment\", { deploymentName: Schema.String }) {}\n\nexport class AmbiguousDeployment extends Schema.TaggedError<\n AmbiguousDeployment,\n { readonly brand: unique symbol }\n>()(\"AmbiguousDeployment\", {\n projectId: Schema.Finite,\n reference: Schema.String,\n}) {}\n\nexport const provider = Effect.gen(function* () {\n const client = yield* ConvexClient;\n const attributes = Effect.fn(\"Deployment.attributes\")(function* (\n deployment: PlatformDeploymentResponse,\n ) {\n if (deployment.kind !== \"cloud\")\n return yield* UnsupportedLocalDeployment.make({\n deploymentName: deployment.name,\n });\n return {\n projectId: deployment.projectId,\n name: deployment.name,\n reference: deployment.reference,\n type: deployment.deploymentType,\n url: deployment.deploymentUrl,\n region: deployment.region,\n } satisfies DeploymentAttributes;\n });\n const find = Effect.fn(\"Deployment.find\")(function* (\n projectId: number,\n reference: string,\n ) {\n const deployments = yield* client.listDeployments(projectId);\n const matches = Array.filter(\n deployments,\n (deployment) =>\n deployment.kind === \"cloud\" && deployment.reference === reference,\n );\n if (matches.length > 1)\n return yield* AmbiguousDeployment.make({ projectId, reference });\n return matches[0];\n });\n const validate = Effect.fn(\"Deployment.validate\")(function* (\n current: DeploymentAttributes,\n news: DeploymentProps,\n ) {\n for (const field of [\"projectId\", \"type\", \"region\"] as const) {\n if (news[field] !== undefined && current[field] !== news[field])\n return yield* DeploymentIdentityChange.make({\n deploymentName: current.name,\n field,\n current: String(current[field]),\n requested: String(news[field]),\n });\n }\n });\n return {\n diff: Effect.fn(\"Deployment.diff\")(function* ({ news, output }) {\n if (!isResolved(news) || output === undefined) return;\n yield* validate(output, news);\n const deployment = yield* client\n .getDeployment(output.name)\n .pipe(Effect.catchTag(\"ConvexNotFound\", () => Effect.void));\n if (deployment === undefined) return { action: \"update\" };\n const current = yield* attributes(deployment);\n yield* validate(current, news);\n if ((news.reference ?? output.reference) !== current.reference)\n return { action: \"update\" };\n }),\n read: Effect.fn(\"Deployment.read\")(function* ({\n fqn,\n instanceId,\n olds,\n output,\n }) {\n if (output !== undefined) {\n const deployment = yield* client\n .getDeployment(output.name)\n .pipe(Effect.catchTag(\"ConvexNotFound\", () => Effect.void));\n return deployment !== undefined\n ? yield* attributes(deployment)\n : undefined;\n }\n if (olds.projectId === undefined) return;\n const deployment = yield* find(\n olds.projectId,\n olds.reference ?? (yield* resourceName(\"deployment\", fqn, instanceId)),\n );\n return deployment !== undefined\n ? yield* Effect.map(attributes(deployment), Unowned)\n : undefined;\n }),\n reconcile: Effect.fn(\"Deployment.reconcile\")(function* ({\n fqn,\n instanceId,\n news,\n output,\n }) {\n if (output === undefined) yield* checkpointCreate(fqn, instanceId, news);\n if (output !== undefined) yield* validate(output, news);\n let deployment =\n output !== undefined\n ? yield* client\n .getDeployment(output.name)\n .pipe(Effect.catchTag(\"ConvexNotFound\", () => Effect.void))\n : undefined;\n const reference =\n news.reference ??\n output?.reference ??\n (yield* resourceName(\"deployment\", fqn, instanceId));\n if (deployment === undefined) {\n const existing = yield* find(news.projectId, reference);\n if (existing !== undefined && !(yield* shouldAdopt(fqn)))\n return yield* new OwnedBySomeoneElse({\n message: \"An existing deployment requires explicit adoption.\",\n resourceType: Deployment.Type,\n physicalName: reference,\n });\n if (existing !== undefined) {\n const adopted = yield* attributes(existing);\n yield* validate(adopted, news);\n yield* checkpointCreate(fqn, instanceId, news, adopted);\n deployment = existing;\n } else {\n deployment = yield* client.createDeployment(news.projectId, {\n type: news.type,\n reference,\n ...(news.region === undefined ? {} : { region: news.region }),\n });\n }\n }\n const current = yield* attributes(deployment);\n yield* validate(current, news);\n if (current.reference !== reference) {\n const existing = yield* find(news.projectId, reference);\n if (existing !== undefined && existing.name !== current.name)\n return yield* new OwnedBySomeoneElse({\n message: \"The requested deployment reference is already in use.\",\n resourceType: Deployment.Type,\n physicalName: reference,\n });\n yield* client.updateDeployment(current.name, {\n reference,\n });\n deployment = yield* client.getDeployment(current.name);\n }\n return yield* attributes(deployment);\n }),\n delete: Effect.fn(\"Deployment.delete\")(function* ({ output }) {\n yield* client\n .deleteDeployment(output.name)\n .pipe(Effect.catchTag(\"ConvexNotFound\", () => Effect.void));\n }),\n } satisfies Provider.ProviderServiceInput<Deployment>;\n});\n\ninterface LocalConfig {\n readonly name: string;\n readonly props: DeploymentProps;\n}\n\n/**\n * Under `alchemy dev` a deployment is a local Convex backend this provider\n * owns. Alchemy's dev sidecar hosts it, so the backend keeps running across\n * reloads of the stack and stops when the dev session ends. Its data lives in\n * `.alchemy/convex/<stack>/<stage>/<name>` and is removed only when the\n * deployment is destroyed.\n *\n * @stability unstable\n */\nexport const localLayer = LocalProvider.make(\n Deployment,\n new URL(\n `./internal/LocalSidecar${moduleExtension(import.meta.url)}`,\n import.meta.url,\n ).href,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const directory = yield* dataDirectories;\n return {\n resolveConfig: Effect.fn(\"Deployment.localConfig\")(function* ({\n fqn,\n instanceId,\n news,\n }) {\n return {\n name: yield* resourceName(\"deployment\", fqn, instanceId),\n props: news,\n } satisfies LocalConfig;\n }),\n start: Effect.fn(\"Deployment.localStart\")(function* ({\n config,\n invalidate,\n }) {\n const backend = yield* boot(config.name, directory(config.name));\n yield* backend.exited.pipe(\n Effect.andThen(invalidate),\n Effect.forkScoped,\n );\n return {\n projectId: config.props.projectId,\n name: config.name,\n reference: config.props.reference ?? config.name,\n type: config.props.type,\n url: backend.url,\n ...(config.props.region === undefined\n ? {}\n : { region: config.props.region }),\n } satisfies DeploymentAttributes;\n }),\n stop: Effect.fn(\"Deployment.localStop\")(function* ({ fqn, instanceId }) {\n const name = yield* resourceName(\"deployment\", fqn, instanceId);\n yield* remove(name, directory(name)).pipe(\n Effect.provideService(FileSystem.FileSystem, fs),\n );\n }),\n } satisfies LocalProvider.LocalProviderSpec<\n Deployment,\n LocalConfig,\n Effect.Services<ReturnType<typeof boot>>\n >;\n }),\n);\n\nexport const layer = Provider.effect(Deployment, provider);\n"],"mappings":";;;;;;;;;;;;;;;AAgDA,MAAa,aAAa,SAAqB,qBAAqB,EAClE,sBAAsB,SACxB,CAAC;AAED,IAAa,2BAAb,cAA8C,OAAO,YAGnD,CAAC,CAAC,4BAA4B;CAC9B,gBAAgB,OAAO;CACvB,OAAO,OAAO;CACd,SAAS,OAAO;CAChB,WAAW,OAAO;AACpB,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,6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AC9D,CAAC;CACH;AACF,CAAC;;;;;;;;;;AAgBD,MAAa,aAAa,cAAc,KACtC,YACA,IAAI,IACF,0BAA0B,gBAAgB,YAAY,GAAG,KACzD,YAAY,GACd,CAAC,CAAC,MACF,OAAO,IAAI,aAAa;CACtB,MAAM,KAAK,OAAO,WAAW;CAC7B,MAAM,YAAY,OAAO;CACzB,OAAO;EACL,eAAe,OAAO,GAAG,wBAAwB,CAAC,CAAC,WAAW,EAC5D,KACA,YACA,QACC;GACD,OAAO;IACL,MAAM,OAAO,aAAa,cAAc,KAAK,UAAU;IACvD,OAAO;GACT;EACF,CAAC;EACD,OAAO,OAAO,GAAG,uBAAuB,CAAC,CAAC,WAAW,EACnD,QACA,cACC;GACD,MAAM,UAAU,OAAO,KAAK,OAAO,MAAM,UAAU,OAAO,IAAI,CAAC;GAC/D,OAAO,QAAQ,OAAO,KACpB,OAAO,QAAQ,UAAU,GACzB,OAAO,UACT;GACA,OAAO;IACL,WAAW,OAAO,MAAM;IACxB,MAAM,OAAO;IACb,WAAW,OAAO,MAAM,aAAa,OAAO;IAC5C,MAAM,OAAO,MAAM;IACnB,KAAK,QAAQ;IACb,GAAI,OAAO,MAAM,WAAW,KAAA,IACxB,CAAC,IACD,EAAE,QAAQ,OAAO,MAAM,OAAO;GACpC;EACF,CAAC;EACD,MAAM,OAAO,GAAG,sBAAsB,CAAC,CAAC,WAAW,EAAE,KAAK,cAAc;GACtE,MAAM,OAAO,OAAO,aAAa,cAAc,KAAK,UAAU;GAC9D,OAAO,OAAO,MAAM,UAAU,IAAI,CAAC,CAAC,CAAC,KACnC,OAAO,eAAe,WAAW,YAAY,EAAE,CACjD;EACF,CAAC;CACH;AAKF,CAAC,CACH;AAEA,MAAa,QAAQ,SAAS,OAAO,YAAY,QAAQ"}
1
+ {"version":3,"file":"Deployment.js","names":[],"sources":["../src/Deployment.ts"],"sourcesContent":["import type {\n CreateDeploymentType,\n DeploymentClass,\n PlatformDeploymentResponse,\n RegionName,\n} from \"@convex-dev/platform/managementApi\";\nimport { OwnedBySomeoneElse, Unowned } from \"alchemy/AdoptPolicy\";\nimport { isResolved } from \"alchemy/Diff\";\nimport * as LocalProvider from \"alchemy/Local/LocalProvider\";\nimport * as Provider from \"alchemy/Provider\";\nimport { Resource } from \"alchemy/Resource\";\nimport { moduleExtension } from \"alchemy/Util/Node\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Schema from \"effect/Schema\";\n\nimport { ConvexClient } from \"./ConvexClient.js\";\nimport type { Providers } from \"./Providers.js\";\nimport { resourceName } from \"./internal/ResourceIdentity.js\";\nimport { checkpointCreate, shouldAdopt } from \"./internal/Lifecycle.js\";\nimport { boot, dataDirectories, remove } from \"./internal/LocalBackend.js\";\nimport * as Array from \"effect/Array\";\n\nexport interface DeploymentProps {\n readonly projectId: number;\n readonly type: CreateDeploymentType;\n readonly reference?: string;\n readonly region?: RegionName;\n readonly class?: DeploymentClass;\n /**\n * Safe integer milliseconds since the Unix epoch. Omit to preserve the\n * current cloud expiry; only null clears it.\n */\n readonly expiresAt?: number | null;\n}\n\nexport interface DeploymentAttributes {\n readonly projectId: number;\n readonly name: string;\n readonly reference: string;\n readonly type: CreateDeploymentType;\n readonly url: string;\n /**\n * Always set in the cloud; a local deployment echoes the requested region.\n */\n readonly region?: RegionName;\n /**\n * Always set in the cloud; local deployments do not have a cloud class.\n */\n readonly class?: string;\n /**\n * Cloud expiry in milliseconds since the Unix epoch, or null when unset.\n */\n readonly expiresAt?: number | null;\n}\n\nexport type Deployment = Resource<\n \"Convex.Deployment\",\n DeploymentProps,\n DeploymentAttributes,\n never,\n Providers\n>;\nexport const Deployment = Resource<Deployment>(\"Convex.Deployment\", {\n defaultRemovalPolicy: \"retain\",\n});\n\nexport class DeploymentIdentityChange extends Schema.TaggedError<\n DeploymentIdentityChange,\n { readonly brand: unique symbol }\n>()(\"DeploymentIdentityChange\", {\n deploymentName: Schema.String,\n field: Schema.String,\n current: Schema.String,\n requested: Schema.String,\n}) {}\n\nexport class UnsupportedLocalDeployment extends Schema.TaggedError<\n UnsupportedLocalDeployment,\n { readonly brand: unique symbol }\n>()(\"UnsupportedLocalDeployment\", { deploymentName: Schema.String }) {}\n\nexport class AmbiguousDeployment extends Schema.TaggedError<\n AmbiguousDeployment,\n { readonly brand: unique symbol }\n>()(\"AmbiguousDeployment\", {\n projectId: Schema.Finite,\n reference: Schema.String,\n}) {}\n\nexport class InvalidDeploymentExpiry extends Schema.TaggedError<\n InvalidDeploymentExpiry,\n { readonly brand: unique symbol }\n>()(\"InvalidDeploymentExpiry\", {\n requested: Schema.String,\n}) {\n override get message() {\n return \"Deployment expiresAt must be a safe integer timestamp in milliseconds, or null to clear the expiry.\";\n }\n}\n\nconst validateExpiry = Effect.fn(\"Deployment.validateExpiry\")(function* ({\n expiresAt,\n}: DeploymentProps) {\n if (expiresAt != null && !Number.isSafeInteger(expiresAt))\n return yield* InvalidDeploymentExpiry.make({\n requested: String(expiresAt),\n });\n});\n\nexport const provider = Effect.gen(function* () {\n const client = yield* ConvexClient;\n const attributes = Effect.fn(\"Deployment.attributes\")(function* (\n deployment: PlatformDeploymentResponse,\n ) {\n if (deployment.kind !== \"cloud\")\n return yield* UnsupportedLocalDeployment.make({\n deploymentName: deployment.name,\n });\n return {\n projectId: deployment.projectId,\n name: deployment.name,\n reference: deployment.reference,\n type: deployment.deploymentType,\n url: deployment.deploymentUrl,\n region: deployment.region,\n class: deployment.class,\n expiresAt: deployment.expiresAt ?? null,\n } satisfies DeploymentAttributes;\n });\n const find = Effect.fn(\"Deployment.find\")(function* (\n projectId: number,\n reference: string,\n ) {\n const deployments = yield* client.listDeployments(projectId);\n const matches = Array.filter(\n deployments,\n (deployment) =>\n deployment.kind === \"cloud\" && deployment.reference === reference,\n );\n if (matches.length > 1)\n return yield* AmbiguousDeployment.make({ projectId, reference });\n return matches[0];\n });\n const validate = Effect.fn(\"Deployment.validate\")(function* (\n current: DeploymentAttributes,\n news: DeploymentProps,\n ) {\n for (const field of [\"projectId\", \"type\", \"region\"] as const) {\n if (news[field] !== undefined && current[field] !== news[field])\n return yield* DeploymentIdentityChange.make({\n deploymentName: current.name,\n field,\n current: String(current[field]),\n requested: String(news[field]),\n });\n }\n });\n return {\n diff: Effect.fn(\"Deployment.diff\")(function* ({ news, output }) {\n if (!isResolved(news)) return;\n yield* validateExpiry(news);\n if (output === undefined) return;\n const expiresAt = news.expiresAt;\n yield* validate(output, news);\n const deployment = yield* client\n .getDeployment(output.name)\n .pipe(Effect.catchTag(\"ConvexNotFound\", () => Effect.void));\n if (deployment === undefined) return { action: \"update\" };\n const current = yield* attributes(deployment);\n yield* validate(current, news);\n if (\n (news.reference ?? output.reference) !== current.reference ||\n (news.class !== undefined && news.class !== current.class) ||\n (expiresAt !== undefined && expiresAt !== (current.expiresAt ?? null))\n )\n return { action: \"update\" };\n }),\n read: Effect.fn(\"Deployment.read\")(function* ({\n fqn,\n instanceId,\n olds,\n output,\n }) {\n if (output !== undefined) {\n const deployment = yield* client\n .getDeployment(output.name)\n .pipe(Effect.catchTag(\"ConvexNotFound\", () => Effect.void));\n return deployment !== undefined\n ? yield* attributes(deployment)\n : undefined;\n }\n if (olds.projectId === undefined) return;\n const deployment = yield* find(\n olds.projectId,\n olds.reference ?? (yield* resourceName(\"deployment\", fqn, instanceId)),\n );\n return deployment !== undefined\n ? yield* Effect.map(attributes(deployment), Unowned)\n : undefined;\n }),\n reconcile: Effect.fn(\"Deployment.reconcile\")(function* ({\n fqn,\n instanceId,\n news,\n output,\n }) {\n yield* validateExpiry(news);\n if (output === undefined) yield* checkpointCreate(fqn, instanceId, news);\n if (output !== undefined) yield* validate(output, news);\n let deployment =\n output !== undefined\n ? yield* client\n .getDeployment(output.name)\n .pipe(Effect.catchTag(\"ConvexNotFound\", () => Effect.void))\n : undefined;\n const reference =\n news.reference ??\n output?.reference ??\n (yield* resourceName(\"deployment\", fqn, instanceId));\n const expiresAt = news.expiresAt;\n if (deployment === undefined) {\n const existing = yield* find(news.projectId, reference);\n if (existing !== undefined && !(yield* shouldAdopt(fqn)))\n return yield* new OwnedBySomeoneElse({\n message: \"An existing deployment requires explicit adoption.\",\n resourceType: Deployment.Type,\n physicalName: reference,\n });\n if (existing !== undefined) {\n const adopted = yield* attributes(existing);\n yield* validate(adopted, news);\n yield* checkpointCreate(fqn, instanceId, news, adopted);\n deployment = existing;\n } else {\n deployment = yield* client.createDeployment(news.projectId, {\n type: news.type,\n reference,\n ...(news.region === undefined ? {} : { region: news.region }),\n ...(news.class === undefined ? {} : { class: news.class }),\n ...(expiresAt === undefined ? {} : { expiresAt }),\n });\n }\n }\n const current = yield* attributes(deployment);\n yield* validate(current, news);\n if (\n current.reference !== reference ||\n (news.class !== undefined && news.class !== current.class) ||\n (expiresAt !== undefined && expiresAt !== (current.expiresAt ?? null))\n ) {\n if (current.reference !== reference) {\n const existing = yield* find(news.projectId, reference);\n if (existing !== undefined && existing.name !== current.name)\n return yield* new OwnedBySomeoneElse({\n message: \"The requested deployment reference is already in use.\",\n resourceType: Deployment.Type,\n physicalName: reference,\n });\n }\n yield* client.updateDeployment(current.name, {\n reference,\n ...(news.class === undefined || news.class === current.class\n ? {}\n : { class: news.class }),\n ...(expiresAt === undefined ||\n expiresAt === (current.expiresAt ?? null)\n ? {}\n : { expiresAt }),\n });\n deployment = yield* client.getDeployment(current.name);\n }\n return yield* attributes(deployment);\n }),\n delete: Effect.fn(\"Deployment.delete\")(function* ({ output }) {\n yield* client\n .deleteDeployment(output.name)\n .pipe(Effect.catchTag(\"ConvexNotFound\", () => Effect.void));\n }),\n } satisfies Provider.ProviderServiceInput<Deployment>;\n});\n\ninterface LocalConfig {\n readonly name: string;\n readonly props: Omit<DeploymentProps, \"class\" | \"expiresAt\">;\n}\n\n/**\n * Under `alchemy dev` a deployment is a local Convex backend this provider\n * owns. Alchemy's dev sidecar hosts it, so the backend keeps running across\n * reloads of the stack and stops when the dev session ends. Its data lives in\n * `.alchemy/convex/<stack>/<stage>/<name>` and is removed only when the\n * deployment is destroyed.\n *\n * @stability unstable\n */\nexport const localLayer = LocalProvider.make(\n Deployment,\n new URL(\n `./internal/LocalSidecar${moduleExtension(import.meta.url)}`,\n import.meta.url,\n ).href,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const directory = yield* dataDirectories;\n return {\n resolveConfig: Effect.fn(\"Deployment.localConfig\")(function* ({\n fqn,\n instanceId,\n news,\n }) {\n const { class: _class, expiresAt: _expiresAt, ...props } = news;\n return {\n name: yield* resourceName(\"deployment\", fqn, instanceId),\n props,\n } satisfies LocalConfig;\n }),\n start: Effect.fn(\"Deployment.localStart\")(function* ({\n config,\n invalidate,\n }) {\n const backend = yield* boot(config.name, directory(config.name));\n yield* backend.exited.pipe(\n Effect.andThen(invalidate),\n Effect.forkScoped,\n );\n return {\n projectId: config.props.projectId,\n name: config.name,\n reference: config.props.reference ?? config.name,\n type: config.props.type,\n url: backend.url,\n ...(config.props.region === undefined\n ? {}\n : { region: config.props.region }),\n } satisfies DeploymentAttributes;\n }),\n stop: Effect.fn(\"Deployment.localStop\")(function* ({ fqn, instanceId }) {\n const name = yield* resourceName(\"deployment\", fqn, instanceId);\n yield* remove(name, directory(name)).pipe(\n Effect.provideService(FileSystem.FileSystem, fs),\n );\n }),\n } satisfies LocalProvider.LocalProviderSpec<\n Deployment,\n LocalConfig,\n Effect.Services<ReturnType<typeof boot>>\n >;\n }),\n);\n\nexport const layer = Provider.effect(Deployment, provider);\n"],"mappings":";;;;;;;;;;;;;;;AA+DA,MAAa,aAAa,SAAqB,qBAAqB,EAClE,sBAAsB,SACxB,CAAC;AAED,IAAa,2BAAb,cAA8C,OAAO,YAGnD,CAAC,CAAC,4BAA4B;CAC9B,gBAAgB,OAAO;CACvB,OAAO,OAAO;CACd,SAAS,OAAO;CAChB,WAAW,OAAO;AACpB,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,6BAAb,cAAgD,OAAO,YAGrD,CAAC,CAAC,8BAA8B,EAAE,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CAAC,WAAW,EAC5D,KACA,YACA,QACC;GACD,MAAM,EAAE,OAAO,QAAQ,WAAW,YAAY,GAAG,UAAU;GAC3D,OAAO;IACL,MAAM,OAAO,aAAa,cAAc,KAAK,UAAU;IACvD;GACF;EACF,CAAC;EACD,OAAO,OAAO,GAAG,uBAAuB,CAAC,CAAC,WAAW,EACnD,QACA,cACC;GACD,MAAM,UAAU,OAAO,KAAK,OAAO,MAAM,UAAU,OAAO,IAAI,CAAC;GAC/D,OAAO,QAAQ,OAAO,KACpB,OAAO,QAAQ,UAAU,GACzB,OAAO,UACT;GACA,OAAO;IACL,WAAW,OAAO,MAAM;IACxB,MAAM,OAAO;IACb,WAAW,OAAO,MAAM,aAAa,OAAO;IAC5C,MAAM,OAAO,MAAM;IACnB,KAAK,QAAQ;IACb,GAAI,OAAO,MAAM,WAAW,KAAA,IACxB,CAAC,IACD,EAAE,QAAQ,OAAO,MAAM,OAAO;GACpC;EACF,CAAC;EACD,MAAM,OAAO,GAAG,sBAAsB,CAAC,CAAC,WAAW,EAAE,KAAK,cAAc;GACtE,MAAM,OAAO,OAAO,aAAa,cAAc,KAAK,UAAU;GAC9D,OAAO,OAAO,MAAM,UAAU,IAAI,CAAC,CAAC,CAAC,KACnC,OAAO,eAAe,WAAW,YAAY,EAAE,CACjD;EACF,CAAC;CACH;AAKF,CAAC,CACH;AAEA,MAAa,QAAQ,SAAS,OAAO,YAAY,QAAQ"}
@@ -29,10 +29,14 @@ declare const CommandError_base: Schema.Class<CommandError, Schema.TaggedStruct<
29
29
  readonly operation: Schema.Literals<readonly ["prepare", "deploy"]>;
30
30
  readonly reason: Schema.Literals<readonly ["configuration", "spawn", "exit"]>;
31
31
  readonly exitCode: Schema.optionalKey<Schema.Finite>;
32
+ readonly signal: Schema.optionalKey<Schema.String>;
33
+ readonly stdout: Schema.optionalKey<Schema.String>;
34
+ readonly stderr: Schema.optionalKey<Schema.String>;
32
35
  }>, import("effect/Cause").YieldableError & {
33
36
  readonly brand: unique symbol;
34
37
  }>;
35
38
  export declare class CommandError extends CommandError_base {
39
+ get message(): string;
36
40
  }
37
41
  declare const CommandRunner_base: Context.ServiceClass<CommandRunner, "@confect/alchemy/internal/CommandRunner", {
38
42
  readonly prepare: (command: PrepareCommand, cwd?: string) => Effect.Effect<void, CommandError>;
@@ -1 +1 @@
1
- {"version":3,"file":"CommandRunner.d.ts","sources":["../../src/internal/CommandRunner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAC;AAC1C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AACxC,OAAO,KAAK,UAAU,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AACtC,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAC5C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AACxC,OAAO,EAAgB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAEnE,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;CACtC;AAED;;;GAGG;AACH,MAAM,MAAM,UAAU,GAClB;IACE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;CAC/C,GACD;IACE,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAC5B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAA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,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;CAC/C,GACD;IACE,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAC5B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;CAC9C,CAAC;;;;;;;;;oBASc,OAAO,MAAM;;AAFjC,qBAAa,YAAa,SAAQ,iBAUhC;IACA,IAAa,OAAO,IAAI,MAAM,CAQ7B;CACF;;sBAKqB,CAChB,OAAO,EAAE,cAAc,EACvB,GAAG,CAAC,EAAE,MAAM,KACT,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC;qBACrB,CACf,MAAM,EAAE,UAAU,EAClB,GAAG,CAAC,EAAE,MAAM,KACT,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC;;AAV1C,qBAAa,aAAc,SAAQ,kBAYW;CAAG;AAEjD;;;GAGG;AACH,eAAO,MAAM,kBAAkB;;;;;;;EAa7B,CAAC;AAuIH;;GAEG;AACH,eAAO,MAAM,KAAK,gHAqMjB,CAAC"}
@@ -6,7 +6,14 @@ import * as Config from "effect/Config";
6
6
  import * as Context from "effect/Context";
7
7
  import * as Redacted from "effect/Redacted";
8
8
  import * as Schema from "effect/Schema";
9
+ import * as Str from "effect/String";
10
+ import * as Arr from "effect/Array";
11
+ import * as Result from "effect/Result";
12
+ import * as Deferred from "effect/Deferred";
13
+ import * as Stream from "effect/Stream";
9
14
  import { ChildProcess, ChildProcessSpawner } from "effect/process";
15
+ import { Buffer } from "node:buffer";
16
+ import { stripVTControlCharacters } from "node:util";
10
17
  // src/internal/CommandRunner.ts
11
18
  const selection = (target) => target._tag === "Cloud" ? `CONVEX_DEPLOY_KEY=${Redacted.value(target.deployKey)}\n` : `CONVEX_SELF_HOSTED_URL=${target.url}\nCONVEX_SELF_HOSTED_ADMIN_KEY=${Redacted.value(target.adminKey)}\n`;
12
19
  var CommandError = class extends Schema.TaggedError()("CommandError", {
@@ -16,8 +23,16 @@ var CommandError = class extends Schema.TaggedError()("CommandError", {
16
23
  "spawn",
17
24
  "exit"
18
25
  ]),
19
- exitCode: Schema.optionalKey(Schema.Finite)
20
- }) {};
26
+ exitCode: Schema.optionalKey(Schema.Finite),
27
+ signal: Schema.optionalKey(Schema.String),
28
+ stdout: Schema.optionalKey(Schema.String),
29
+ stderr: Schema.optionalKey(Schema.String)
30
+ }) {
31
+ get message() {
32
+ const status = this.signal === void 0 ? this.exitCode === void 0 ? this.reason : `exit code ${this.exitCode}` : `signal ${this.signal}`;
33
+ return `${this.operation} command failed (${status})${this.stdout === void 0 ? "" : `\nstdout:\n${this.stdout}`}${this.stderr === void 0 ? "" : `\nstderr:\n${this.stderr}`}`;
34
+ }
35
+ };
21
36
  var CommandRunner = class extends Context.Service()("@confect/alchemy/internal/CommandRunner") {};
22
37
  /**
23
38
  * The ambient variables a child process needs to run on every platform; the
@@ -50,6 +65,39 @@ const packageBin = Effect.fn("CommandRunner.packageBin")(function* (fs, path, cw
50
65
  directory = parent;
51
66
  }
52
67
  });
68
+ const outputTailSize = 8192;
69
+ const redaction = "<REDACTED>";
70
+ const minimumCredentialLength = 8;
71
+ const outputTail = (stream, secrets) => {
72
+ const credentials = Arr.flatMap(Arr.filter(secrets, (value) => value.length >= minimumCredentialLength), (value) => {
73
+ const bytes = Buffer.from(value);
74
+ return [value, ...Arr.flatMap(["base64", "base64url"], (encoding) => [Str.replace(/=+$/, "")(bytes.toString(encoding)), ...Arr.map([
75
+ 0,
76
+ 1,
77
+ 2
78
+ ], (offset) => Str.slice(Math.ceil(offset * 8 / 6), Math.floor((offset + bytes.length) * 8 / 6))(Buffer.concat([Buffer.alloc(offset), bytes]).toString(encoding)))])];
79
+ });
80
+ const percentEncoded = Arr.map(Arr.filter(secrets, (value) => value.length >= minimumCredentialLength), (value) => Arr.join(Arr.map(Str.split(/(%[0-9A-F]{2})/)(encodeURIComponent(value)), (part) => Str.startsWith("%")(part) ? Arr.join(Arr.map(Str.split("")(part), (char) => /[A-F]/.test(char) ? `[${char}${Str.toLowerCase(char)}]` : char), "") : Str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")(part)), ""));
81
+ return stream.pipe(Stream.decodeText(), Stream.runFold(() => ({
82
+ text: "",
83
+ truncated: false
84
+ }), (tail, chunk) => {
85
+ const text = tail.text + chunk;
86
+ return {
87
+ text: Str.slice(-8192)(text),
88
+ truncated: tail.truncated || text.length > outputTailSize
89
+ };
90
+ }), Effect.map(({ text, truncated }) => {
91
+ text = stripVTControlCharacters(text);
92
+ if (truncated) text = Str.replace(/^\S*/, "")(text);
93
+ const pattern = new RegExp(Arr.join([
94
+ "(?:prod|dev|preview|project|custom):[^\\s|]+\\|[^\\s\\\\\"'&)]+",
95
+ ...percentEncoded,
96
+ ...Arr.map(credentials, (value) => Str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")(value))
97
+ ], "|"), "g");
98
+ return Str.slice(-8192)(Str.replace(pattern, redaction)(text));
99
+ }));
100
+ };
53
101
  /**
54
102
  * @internal
55
103
  */
@@ -57,7 +105,45 @@ const layer = Layer.effect(CommandRunner, Effect.gen(function* () {
57
105
  const fs = yield* FileSystem.FileSystem;
58
106
  const path = yield* Path.Path;
59
107
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
60
- const run = Effect.fn("CommandRunner.run")(function* (operation, command, args, cwd, env) {
108
+ const run = Effect.fn("CommandRunner.run")(function* (operation, command, args, cwd, env, credentials = []) {
109
+ if (operation === "deploy") return yield* Effect.scoped(Effect.gen(function* () {
110
+ const child = yield* spawner.spawn(ChildProcess.make(command, args, {
111
+ cwd,
112
+ env,
113
+ extendEnv: false,
114
+ stdin: "ignore",
115
+ stdout: "pipe",
116
+ stderr: "pipe"
117
+ }));
118
+ const exited = yield* Deferred.make();
119
+ const drainDeadline = Deferred.await(exited).pipe(Effect.andThen(Effect.sleep("1 second")));
120
+ const [code, stdout, stderr] = yield* Effect.all([
121
+ child.exitCode.pipe(Effect.result, Effect.tap(() => Deferred.succeed(exited, void 0))),
122
+ outputTail(child.stdout.pipe(Stream.interruptWhen(drainDeadline)), credentials),
123
+ outputTail(child.stderr.pipe(Stream.interruptWhen(drainDeadline)), credentials)
124
+ ], { concurrency: "unbounded" });
125
+ if (Result.isFailure(code)) {
126
+ const cause = code.failure.cause;
127
+ const signal = cause instanceof Error ? /^Process interrupted due to receipt of signal: '(SIG[A-Z0-9]+)'$/.exec(cause.message)?.[1] : void 0;
128
+ return yield* CommandError.make({
129
+ operation,
130
+ reason: "exit",
131
+ ...signal === void 0 ? {} : { signal },
132
+ stdout,
133
+ stderr
134
+ });
135
+ }
136
+ if (code.success !== 0) return yield* CommandError.make({
137
+ operation,
138
+ reason: "exit",
139
+ exitCode: Number(code.success),
140
+ stdout,
141
+ stderr
142
+ });
143
+ })).pipe(Effect.mapError((error) => Schema.is(CommandError)(error) ? error : CommandError.make({
144
+ operation,
145
+ reason: "spawn"
146
+ })));
61
147
  const code = yield* spawner.exitCode(ChildProcess.make(command, args, {
62
148
  cwd,
63
149
  env,
@@ -115,7 +201,7 @@ const layer = Layer.effect(CommandRunner, Effect.gen(function* () {
115
201
  USERPROFILE: temp,
116
202
  LOCALAPPDATA: temp,
117
203
  XDG_CONFIG_HOME: temp
118
- });
204
+ }, [Redacted.value(target._tag === "Cloud" ? target.deployKey : target.adminKey)]);
119
205
  }).pipe(Effect.mapError((error) => Schema.is(CommandError)(error) ? error : CommandError.make({
120
206
  operation: "deploy",
121
207
  reason: "configuration"
@@ -1 +1 @@
1
- {"version":3,"file":"CommandRunner.js","names":[],"sources":["../../src/internal/CommandRunner.ts"],"sourcesContent":["import * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\n\nexport interface PrepareCommand {\n readonly command: string;\n readonly args: ReadonlyArray<string>;\n}\n\n/**\n * Where a push goes: a cloud deployment through its deploy key, or a local\n * backend through the CLI's self-hosted target and its admin key.\n */\nexport type PushTarget =\n | {\n readonly _tag: \"Cloud\";\n readonly deploymentName: string;\n readonly deployKey: Redacted.Redacted<string>;\n }\n | {\n readonly _tag: \"SelfHosted\";\n readonly deploymentName: string;\n readonly url: string;\n readonly adminKey: Redacted.Redacted<string>;\n };\n\nconst selection = (target: PushTarget) =>\n target._tag === \"Cloud\"\n ? `CONVEX_DEPLOY_KEY=${Redacted.value(target.deployKey)}\\n`\n : `CONVEX_SELF_HOSTED_URL=${target.url}\\nCONVEX_SELF_HOSTED_ADMIN_KEY=${Redacted.value(target.adminKey)}\\n`;\n\nexport class CommandError extends Schema.TaggedError<\n CommandError,\n { readonly brand: unique symbol }\n>()(\"CommandError\", {\n operation: Schema.Literals([\"prepare\", \"deploy\"]),\n reason: Schema.Literals([\"configuration\", \"spawn\", \"exit\"]),\n exitCode: Schema.optionalKey(Schema.Finite),\n}) {}\n\nexport class CommandRunner extends Context.Service<\n CommandRunner,\n {\n readonly prepare: (\n command: PrepareCommand,\n cwd?: string,\n ) => Effect.Effect<void, CommandError>;\n readonly deploy: (\n target: PushTarget,\n cwd?: string,\n ) => Effect.Effect<void, CommandError>;\n }\n>()(\"@confect/alchemy/internal/CommandRunner\") {}\n\n/**\n * The ambient variables a child process needs to run on every platform; the\n * rest of the parent environment, credentials included, is withheld.\n */\nexport const processEnvironment = Config.all({\n PATH: Config.String(\"PATH\").pipe(\n Config.orElse(() => Config.String(\"Path\")),\n Config.withDefault(\"\"),\n ),\n HOME: Config.String(\"HOME\").pipe(Config.withDefault(\"\")),\n USERPROFILE: Config.String(\"USERPROFILE\").pipe(Config.withDefault(\"\")),\n SystemRoot: Config.String(\"SystemRoot\").pipe(\n Config.orElse(() => Config.String(\"SYSTEMROOT\")),\n Config.withDefault(\"\"),\n ),\n TMPDIR: Config.String(\"TMPDIR\").pipe(Config.withDefault(\"\")),\n TEMP: Config.String(\"TEMP\").pipe(Config.withDefault(\"\")),\n});\n\nconst packageBin = Effect.fn(\"CommandRunner.packageBin\")(function* (\n fs: FileSystem.FileSystem,\n path: Path.Path,\n cwd: string,\n packageName: string,\n binName: string,\n) {\n const invalid = () =>\n CommandError.make({\n operation: packageName === \"convex\" ? \"deploy\" : \"prepare\",\n reason: \"configuration\",\n });\n let directory = cwd;\n while (true) {\n const manifestPath = path.join(\n directory,\n \"node_modules\",\n packageName,\n \"package.json\",\n );\n if (yield* fs.exists(manifestPath).pipe(Effect.mapError(invalid))) {\n const manifest = yield* fs.readFileString(manifestPath).pipe(\n Effect.flatMap(\n Schema.decodeEffect(\n Schema.fromJsonString(\n Schema.Struct({\n bin: Schema.Union([\n Schema.String,\n Schema.Record(Schema.String, Schema.String),\n ]),\n }),\n ),\n ),\n ),\n Effect.mapError(invalid),\n );\n const relative =\n typeof manifest.bin === \"string\" ? manifest.bin : manifest.bin[binName];\n if (relative === undefined || relative === \"\") return yield* invalid();\n return path.resolve(path.dirname(manifestPath), relative);\n }\n const parent = path.dirname(directory);\n if (parent === directory) return yield* invalid();\n directory = parent;\n }\n});\n\n/**\n * @internal\n */\nexport const layer = Layer.effect(\n CommandRunner,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const run = Effect.fn(\"CommandRunner.run\")(function* (\n operation: \"prepare\" | \"deploy\",\n command: string,\n args: ReadonlyArray<string>,\n cwd: string,\n env: Record<string, string | undefined>,\n ) {\n const code = yield* spawner\n .exitCode(\n ChildProcess.make(command, args, {\n cwd,\n env,\n extendEnv: false,\n stdin: \"ignore\",\n stdout: \"ignore\",\n stderr: \"ignore\",\n }),\n )\n .pipe(\n Effect.mapError(() =>\n CommandError.make({ operation, reason: \"spawn\" }),\n ),\n );\n if (code !== 0)\n return yield* CommandError.make({\n operation,\n reason: \"exit\",\n exitCode: Number(code),\n });\n });\n const environment = processEnvironment.pipe(\n Effect.map((env) => ({ ...env, CI: \"true\", DO_NOT_TRACK: \"1\" })),\n );\n return CommandRunner.of({\n prepare: Effect.fn(\"CommandRunner.prepare\")(function* (\n command,\n cwd = process.cwd(),\n ) {\n const directory = path.resolve(cwd);\n const env = yield* environment.pipe(\n Effect.mapError(() =>\n CommandError.make({\n operation: \"prepare\",\n reason: \"configuration\",\n }),\n ),\n );\n if (command.command === \"confect\") {\n const bin = yield* packageBin(\n fs,\n path,\n directory,\n \"@confect/cli\",\n \"confect\",\n );\n yield* run(\n \"prepare\",\n process.execPath,\n [bin, ...command.args],\n directory,\n env,\n );\n } else {\n yield* run(\"prepare\", command.command, command.args, directory, env);\n }\n }),\n deploy: Effect.fn(\"CommandRunner.deploy\")(function* (\n target,\n cwd = process.cwd(),\n ) {\n const directory = path.resolve(cwd);\n const bin = yield* packageBin(fs, path, directory, \"convex\", \"convex\");\n const env = yield* environment.pipe(\n Effect.mapError(() =>\n CommandError.make({\n operation: \"deploy\",\n reason: \"configuration\",\n }),\n ),\n );\n yield* Effect.scoped(\n Effect.gen(function* () {\n const temp = yield* fs.makeTempDirectoryScoped({\n prefix: \"confect-deploy-\",\n });\n const envFile = path.join(temp, \"deployment.env\");\n yield* fs.writeFileString(envFile, selection(target), {\n mode: 0o600,\n });\n yield* run(\n \"deploy\",\n process.execPath,\n [bin, \"deploy\", \"--yes\", \"--env-file\", envFile],\n directory,\n {\n ...env,\n HOME: temp,\n USERPROFILE: temp,\n LOCALAPPDATA: temp,\n XDG_CONFIG_HOME: temp,\n },\n );\n }).pipe(\n Effect.mapError((error) =>\n Schema.is(CommandError)(error)\n ? error\n : CommandError.make({\n operation: \"deploy\",\n reason: \"configuration\",\n }),\n ),\n ),\n );\n }),\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AAG;KACH,MAAM;KACN,aAAa;KACb,cAAc;KACd,iBAAiB;IACnB,CACF;GACF,CAAC,CAAC,CAAC,KACD,OAAO,UAAU,UACf,OAAO,GAAG,YAAY,CAAC,CAAC,KAAK,IACzB,QACA,aAAa,KAAK;IAChB,WAAW;IACX,QAAQ;GACV,CAAC,CACP,CACF,CACF;EACF,CAAC;CACH,CAAC;AACH,CAAC,CACH"}
1
+ {"version":3,"file":"CommandRunner.js","names":[],"sources":["../../src/internal/CommandRunner.ts"],"sourcesContent":["import * as Arr from \"effect/Array\";\nimport * as Str from \"effect/String\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\nimport { Buffer } from \"node:buffer\";\nimport { stripVTControlCharacters } from \"node:util\";\n\nexport interface PrepareCommand {\n readonly command: string;\n readonly args: ReadonlyArray<string>;\n}\n\n/**\n * Where a push goes: a cloud deployment through its deploy key, or a local\n * backend through the CLI's self-hosted target and its admin key.\n */\nexport type PushTarget =\n | {\n readonly _tag: \"Cloud\";\n readonly deploymentName: string;\n readonly deployKey: Redacted.Redacted<string>;\n }\n | {\n readonly _tag: \"SelfHosted\";\n readonly deploymentName: string;\n readonly url: string;\n readonly adminKey: Redacted.Redacted<string>;\n };\n\nconst selection = (target: PushTarget) =>\n target._tag === \"Cloud\"\n ? `CONVEX_DEPLOY_KEY=${Redacted.value(target.deployKey)}\\n`\n : `CONVEX_SELF_HOSTED_URL=${target.url}\\nCONVEX_SELF_HOSTED_ADMIN_KEY=${Redacted.value(target.adminKey)}\\n`;\n\nexport class CommandError extends Schema.TaggedError<\n CommandError,\n { readonly brand: unique symbol }\n>()(\"CommandError\", {\n operation: Schema.Literals([\"prepare\", \"deploy\"]),\n reason: Schema.Literals([\"configuration\", \"spawn\", \"exit\"]),\n exitCode: Schema.optionalKey(Schema.Finite),\n signal: Schema.optionalKey(Schema.String),\n stdout: Schema.optionalKey(Schema.String),\n stderr: Schema.optionalKey(Schema.String),\n}) {\n override get message(): string {\n const status =\n this.signal === undefined\n ? this.exitCode === undefined\n ? this.reason\n : `exit code ${this.exitCode}`\n : `signal ${this.signal}`;\n return `${this.operation} command failed (${status})${this.stdout === undefined ? \"\" : `\\nstdout:\\n${this.stdout}`}${this.stderr === undefined ? \"\" : `\\nstderr:\\n${this.stderr}`}`;\n }\n}\n\nexport class CommandRunner extends Context.Service<\n CommandRunner,\n {\n readonly prepare: (\n command: PrepareCommand,\n cwd?: string,\n ) => Effect.Effect<void, CommandError>;\n readonly deploy: (\n target: PushTarget,\n cwd?: string,\n ) => Effect.Effect<void, CommandError>;\n }\n>()(\"@confect/alchemy/internal/CommandRunner\") {}\n\n/**\n * The ambient variables a child process needs to run on every platform; the\n * rest of the parent environment, credentials included, is withheld.\n */\nexport const processEnvironment = Config.all({\n PATH: Config.String(\"PATH\").pipe(\n Config.orElse(() => Config.String(\"Path\")),\n Config.withDefault(\"\"),\n ),\n HOME: Config.String(\"HOME\").pipe(Config.withDefault(\"\")),\n USERPROFILE: Config.String(\"USERPROFILE\").pipe(Config.withDefault(\"\")),\n SystemRoot: Config.String(\"SystemRoot\").pipe(\n Config.orElse(() => Config.String(\"SYSTEMROOT\")),\n Config.withDefault(\"\"),\n ),\n TMPDIR: Config.String(\"TMPDIR\").pipe(Config.withDefault(\"\")),\n TEMP: Config.String(\"TEMP\").pipe(Config.withDefault(\"\")),\n});\n\nconst packageBin = Effect.fn(\"CommandRunner.packageBin\")(function* (\n fs: FileSystem.FileSystem,\n path: Path.Path,\n cwd: string,\n packageName: string,\n binName: string,\n) {\n const invalid = () =>\n CommandError.make({\n operation: packageName === \"convex\" ? \"deploy\" : \"prepare\",\n reason: \"configuration\",\n });\n let directory = cwd;\n while (true) {\n const manifestPath = path.join(\n directory,\n \"node_modules\",\n packageName,\n \"package.json\",\n );\n if (yield* fs.exists(manifestPath).pipe(Effect.mapError(invalid))) {\n const manifest = yield* fs.readFileString(manifestPath).pipe(\n Effect.flatMap(\n Schema.decodeEffect(\n Schema.fromJsonString(\n Schema.Struct({\n bin: Schema.Union([\n Schema.String,\n Schema.Record(Schema.String, Schema.String),\n ]),\n }),\n ),\n ),\n ),\n Effect.mapError(invalid),\n );\n const relative =\n typeof manifest.bin === \"string\" ? manifest.bin : manifest.bin[binName];\n if (relative === undefined || relative === \"\") return yield* invalid();\n return path.resolve(path.dirname(manifestPath), relative);\n }\n const parent = path.dirname(directory);\n if (parent === directory) return yield* invalid();\n directory = parent;\n }\n});\n\nconst outputTailSize = 8192;\nconst redaction = \"<REDACTED>\";\n// Short needles match common diagnostic text rather than useful credentials.\nconst minimumCredentialLength = 8;\n\nconst outputTail = <E>(\n stream: Stream.Stream<Uint8Array, E>,\n secrets: ReadonlyArray<string>,\n) => {\n const credentials = Arr.flatMap(\n Arr.filter(secrets, (value) => value.length >= minimumCredentialLength),\n (value: string) => {\n const bytes = Buffer.from(value);\n const base64 = Arr.flatMap(\n [\"base64\", \"base64url\"] as const,\n (encoding) => [\n Str.replace(/=+$/, \"\")(bytes.toString(encoding)),\n ...Arr.map([0, 1, 2], (offset) =>\n // The first and last partial sextets depend on bytes outside the key.\n Str.slice(\n Math.ceil((offset * 8) / 6),\n Math.floor(((offset + bytes.length) * 8) / 6),\n )(Buffer.concat([Buffer.alloc(offset), bytes]).toString(encoding)),\n ),\n ],\n );\n return [value, ...base64];\n },\n );\n const percentEncoded = Arr.map(\n Arr.filter(secrets, (value) => value.length >= minimumCredentialLength),\n (value) =>\n Arr.join(\n Arr.map(\n Str.split(/(%[0-9A-F]{2})/)(encodeURIComponent(value)),\n (part) =>\n Str.startsWith(\"%\")(part)\n ? Arr.join(\n Arr.map(Str.split(\"\")(part), (char) =>\n /[A-F]/.test(char)\n ? `[${char}${Str.toLowerCase(char)}]`\n : char,\n ),\n \"\",\n )\n : Str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")(part),\n ),\n \"\",\n ),\n );\n return stream.pipe(\n Stream.decodeText(),\n Stream.runFold(\n () => ({ text: \"\", truncated: false }),\n (tail, chunk) => {\n const text = tail.text + chunk;\n return {\n text: Str.slice(-outputTailSize)(text),\n truncated: tail.truncated || text.length > outputTailSize,\n };\n },\n ),\n Effect.map(({ text, truncated }) => {\n text = stripVTControlCharacters(text);\n if (truncated) {\n // A clipped token may be an unrecognised deploy key. Drop it whole.\n text = Str.replace(/^\\S*/, \"\")(text);\n }\n const pattern = new RegExp(\n Arr.join(\n [\n \"(?:prod|dev|preview|project|custom):[^\\\\s|]+\\\\|[^\\\\s\\\\\\\\\\\"'&)]+\",\n ...percentEncoded,\n ...Arr.map(credentials, (value) =>\n Str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")(value),\n ),\n ],\n \"|\",\n ),\n \"g\",\n );\n return Str.slice(-outputTailSize)(Str.replace(pattern, redaction)(text));\n }),\n );\n};\n\n/**\n * @internal\n */\nexport const layer = Layer.effect(\n CommandRunner,\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n const run = Effect.fn(\"CommandRunner.run\")(function* (\n operation: \"prepare\" | \"deploy\",\n command: string,\n args: ReadonlyArray<string>,\n cwd: string,\n env: Record<string, string | undefined>,\n credentials: ReadonlyArray<string> = [],\n ) {\n if (operation === \"deploy\") {\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const child = yield* spawner.spawn(\n ChildProcess.make(command, args, {\n cwd,\n env,\n extendEnv: false,\n stdin: \"ignore\",\n stdout: \"pipe\",\n stderr: \"pipe\",\n }),\n );\n const exited = yield* Deferred.make<void>();\n // Descendants can inherit pipes and keep them open after the CLI exits.\n const drainDeadline = Deferred.await(exited).pipe(\n Effect.andThen(Effect.sleep(\"1 second\")),\n );\n const [code, stdout, stderr] = yield* Effect.all(\n [\n child.exitCode.pipe(\n Effect.result,\n Effect.tap(() => Deferred.succeed(exited, undefined)),\n ),\n outputTail(\n child.stdout.pipe(Stream.interruptWhen(drainDeadline)),\n credentials,\n ),\n outputTail(\n child.stderr.pipe(Stream.interruptWhen(drainDeadline)),\n credentials,\n ),\n ],\n { concurrency: \"unbounded\" },\n );\n if (Result.isFailure(code)) {\n // The spawner exposes a terminating signal only in its cause message.\n const cause = code.failure.cause;\n const signal =\n cause instanceof Error\n ? /^Process interrupted due to receipt of signal: '(SIG[A-Z0-9]+)'$/.exec(\n cause.message,\n )?.[1]\n : undefined;\n return yield* CommandError.make({\n operation,\n reason: \"exit\",\n ...(signal === undefined ? {} : { signal }),\n stdout,\n stderr,\n });\n }\n if (code.success !== 0)\n return yield* CommandError.make({\n operation,\n reason: \"exit\",\n exitCode: Number(code.success),\n stdout,\n stderr,\n });\n }),\n ).pipe(\n Effect.mapError((error) =>\n Schema.is(CommandError)(error)\n ? error\n : CommandError.make({ operation, reason: \"spawn\" }),\n ),\n );\n }\n const code = yield* spawner\n .exitCode(\n ChildProcess.make(command, args, {\n cwd,\n env,\n extendEnv: false,\n stdin: \"ignore\",\n stdout: \"ignore\",\n stderr: \"ignore\",\n }),\n )\n .pipe(\n Effect.mapError(() =>\n CommandError.make({ operation, reason: \"spawn\" }),\n ),\n );\n if (code !== 0)\n return yield* CommandError.make({\n operation,\n reason: \"exit\",\n exitCode: Number(code),\n });\n });\n const environment = processEnvironment.pipe(\n Effect.map((env) => ({ ...env, CI: \"true\", DO_NOT_TRACK: \"1\" })),\n );\n return CommandRunner.of({\n prepare: Effect.fn(\"CommandRunner.prepare\")(function* (\n command,\n cwd = process.cwd(),\n ) {\n const directory = path.resolve(cwd);\n const env = yield* environment.pipe(\n Effect.mapError(() =>\n CommandError.make({\n operation: \"prepare\",\n reason: \"configuration\",\n }),\n ),\n );\n if (command.command === \"confect\") {\n const bin = yield* packageBin(\n fs,\n path,\n directory,\n \"@confect/cli\",\n \"confect\",\n );\n yield* run(\n \"prepare\",\n process.execPath,\n [bin, ...command.args],\n directory,\n env,\n );\n } else {\n yield* run(\"prepare\", command.command, command.args, directory, env);\n }\n }),\n deploy: Effect.fn(\"CommandRunner.deploy\")(function* (\n target,\n cwd = process.cwd(),\n ) {\n const directory = path.resolve(cwd);\n const bin = yield* packageBin(fs, path, directory, \"convex\", \"convex\");\n const env = yield* environment.pipe(\n Effect.mapError(() =>\n CommandError.make({\n operation: \"deploy\",\n reason: \"configuration\",\n }),\n ),\n );\n yield* Effect.scoped(\n Effect.gen(function* () {\n const temp = yield* fs.makeTempDirectoryScoped({\n prefix: \"confect-deploy-\",\n });\n const envFile = path.join(temp, \"deployment.env\");\n yield* fs.writeFileString(envFile, selection(target), {\n mode: 0o600,\n });\n yield* run(\n \"deploy\",\n process.execPath,\n [bin, \"deploy\", \"--yes\", \"--env-file\", envFile],\n directory,\n {\n ...env,\n HOME: temp,\n USERPROFILE: temp,\n LOCALAPPDATA: temp,\n XDG_CONFIG_HOME: temp,\n },\n [\n Redacted.value(\n target._tag === \"Cloud\" ? target.deployKey : target.adminKey,\n ),\n ],\n );\n }).pipe(\n Effect.mapError((error) =>\n Schema.is(CommandError)(error)\n ? error\n : CommandError.make({\n operation: \"deploy\",\n reason: \"configuration\",\n }),\n ),\n ),\n );\n }),\n });\n }),\n);\n"],"mappings":";;;;;;;;;;;;;;;;;AAuCA,MAAM,aAAa,WACjB,OAAO,SAAS,UACZ,qBAAqB,SAAS,MAAM,OAAO,SAAS,EAAE,MACtD,0BAA0B,OAAO,IAAI,iCAAiC,SAAS,MAAM,OAAO,QAAQ,EAAE;AAE5G,IAAa,eAAb,cAAkC,OAAO,YAGvC,CAAC,CAAC,gBAAgB;CAClB,WAAW,OAAO,SAAS,CAAC,WAAW,QAAQ,CA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,QAAQ,OAAO,GAAG,sBAAsB,CAAC,CAAC,WACxC,QACA,MAAM,QAAQ,IAAI,GAClB;GACA,MAAM,YAAY,KAAK,QAAQ,GAAG;GAClC,MAAM,MAAM,OAAO,WAAW,IAAI,MAAM,WAAW,UAAU,QAAQ;GACrE,MAAM,MAAM,OAAO,YAAY,KAC7B,OAAO,eACL,aAAa,KAAK;IAChB,WAAW;IACX,QAAQ;GACV,CAAC,CACH,CACF;GACA,OAAO,OAAO,OACZ,OAAO,IAAI,aAAa;IACtB,MAAM,OAAO,OAAO,GAAG,wBAAwB,EAC7C,QAAQ,kBACV,CAAC;IACD,MAAM,UAAU,KAAK,KAAK,MAAM,gBAAgB;IAChD,OAAO,GAAG,gBAAgB,SAAS,UAAU,MAAM,GAAG,EACpD,MAAM,IACR,CAAC;IACD,OAAO,IACL,UACA,QAAQ,UACR;KAAC;KAAK;KAAU;KAAS;KAAc;IAAO,GAC9C,WACA;KACE,GAAG;KACH,MAAM;KACN,aAAa;KACb,cAAc;KACd,iBAAiB;IACnB,GACA,CACE,SAAS,MACP,OAAO,SAAS,UAAU,OAAO,YAAY,OAAO,QACtD,CACF,CACF;GACF,CAAC,CAAC,CAAC,KACD,OAAO,UAAU,UACf,OAAO,GAAG,YAAY,CAAC,CAAC,KAAK,IACzB,QACA,aAAa,KAAK;IAChB,WAAW;IACX,QAAQ;GACV,CAAC,CACP,CACF,CACF;EACF,CAAC;CACH,CAAC;AACH,CAAC,CACH"}
@@ -14,6 +14,8 @@ import * as Option from "effect/Option";
14
14
  import * as Str from "effect/String";
15
15
  import { pipe } from "effect/Function";
16
16
  import * as Array from "effect/Array";
17
+ import * as Deferred from "effect/Deferred";
18
+ import * as Stream from "effect/Stream";
17
19
  import { ChildProcess, ChildProcessSpawner } from "effect/process";
18
20
  import * as SecureRandom from "effect/crypto/SecureRandom";
19
21
  import * as Scope from "effect/Scope";
@@ -21,10 +23,8 @@ import * as Schedule from "effect/Schedule";
21
23
  import { dotAlchemyDirectory } from "alchemy/AlchemyContext";
22
24
  import { Stack } from "alchemy/Stack";
23
25
  import { createServer } from "node:net";
24
- import * as Deferred from "effect/Deferred";
25
26
  import * as Exit from "effect/Exit";
26
27
  import * as Semaphore from "effect/Semaphore";
27
- import * as Stream from "effect/Stream";
28
28
  // src/internal/LocalBackend.ts
29
29
  /**
30
30
  * The backend release a new local deployment runs. An existing data directory
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@gaganref/confect-alchemy",
3
- "version": "10.6.0-fork.2",
3
+ "version": "10.6.0-fork.20",
4
4
  "dependencies": {
5
5
  "@convex-dev/platform": "^0.1.10"
6
6
  },
7
7
  "peerDependencies": {
8
- "@confect/cli": "npm:@gaganref/confect-cli@10.6.0-fork.2",
9
- "@confect/core": "npm:@gaganref/confect-core@10.6.0-fork.2",
10
- "alchemy": "2.0.0-beta.86",
8
+ "@confect/cli": "npm:@gaganref/confect-cli@10.6.0-fork.20",
9
+ "@confect/core": "npm:@gaganref/confect-core@10.6.0-fork.20",
10
+ "alchemy": ">=2.0.0-beta.85 <2.0.0",
11
11
  "convex": "^1.32.0",
12
12
  "effect": "~4.1.4"
13
13
  },
@@ -36,11 +36,11 @@ export type UpdateProjectInput = Pick<
36
36
  >;
37
37
  export type CreateDeploymentInput = Pick<
38
38
  ManagementApi.PlatformCreateDeploymentArgs,
39
- "type" | "region" | "class"
39
+ "type" | "region" | "class" | "expiresAt"
40
40
  > & { readonly reference: string };
41
41
  export type UpdateDeploymentInput = Pick<
42
42
  ManagementApi.PlatformUpdateDeploymentArgs,
43
- "reference" | "expiresAt" | "sendLogsToClient"
43
+ "reference" | "expiresAt" | "sendLogsToClient" | "class"
44
44
  >;
45
45
  export type CreateDeployKeyInput = ManagementApi.PlatformCreateDeployKeyArgs;
46
46
  export type CreatedDeployKey = {
package/src/Deployment.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type {
2
2
  CreateDeploymentType,
3
+ DeploymentClass,
3
4
  PlatformDeploymentResponse,
4
5
  RegionName,
5
6
  } from "@convex-dev/platform/managementApi";
@@ -25,6 +26,12 @@ export interface DeploymentProps {
25
26
  readonly type: CreateDeploymentType;
26
27
  readonly reference?: string;
27
28
  readonly region?: RegionName;
29
+ readonly class?: DeploymentClass;
30
+ /**
31
+ * Safe integer milliseconds since the Unix epoch. Omit to preserve the
32
+ * current cloud expiry; only null clears it.
33
+ */
34
+ readonly expiresAt?: number | null;
28
35
  }
29
36
 
30
37
  export interface DeploymentAttributes {
@@ -37,6 +44,14 @@ export interface DeploymentAttributes {
37
44
  * Always set in the cloud; a local deployment echoes the requested region.
38
45
  */
39
46
  readonly region?: RegionName;
47
+ /**
48
+ * Always set in the cloud; local deployments do not have a cloud class.
49
+ */
50
+ readonly class?: string;
51
+ /**
52
+ * Cloud expiry in milliseconds since the Unix epoch, or null when unset.
53
+ */
54
+ readonly expiresAt?: number | null;
40
55
  }
41
56
 
42
57
  export type Deployment = Resource<
@@ -73,6 +88,26 @@ export class AmbiguousDeployment extends Schema.TaggedError<
73
88
  reference: Schema.String,
74
89
  }) {}
75
90
 
91
+ export class InvalidDeploymentExpiry extends Schema.TaggedError<
92
+ InvalidDeploymentExpiry,
93
+ { readonly brand: unique symbol }
94
+ >()("InvalidDeploymentExpiry", {
95
+ requested: Schema.String,
96
+ }) {
97
+ override get message() {
98
+ return "Deployment expiresAt must be a safe integer timestamp in milliseconds, or null to clear the expiry.";
99
+ }
100
+ }
101
+
102
+ const validateExpiry = Effect.fn("Deployment.validateExpiry")(function* ({
103
+ expiresAt,
104
+ }: DeploymentProps) {
105
+ if (expiresAt != null && !Number.isSafeInteger(expiresAt))
106
+ return yield* InvalidDeploymentExpiry.make({
107
+ requested: String(expiresAt),
108
+ });
109
+ });
110
+
76
111
  export const provider = Effect.gen(function* () {
77
112
  const client = yield* ConvexClient;
78
113
  const attributes = Effect.fn("Deployment.attributes")(function* (
@@ -89,6 +124,8 @@ export const provider = Effect.gen(function* () {
89
124
  type: deployment.deploymentType,
90
125
  url: deployment.deploymentUrl,
91
126
  region: deployment.region,
127
+ class: deployment.class,
128
+ expiresAt: deployment.expiresAt ?? null,
92
129
  } satisfies DeploymentAttributes;
93
130
  });
94
131
  const find = Effect.fn("Deployment.find")(function* (
@@ -121,7 +158,10 @@ export const provider = Effect.gen(function* () {
121
158
  });
122
159
  return {
123
160
  diff: Effect.fn("Deployment.diff")(function* ({ news, output }) {
124
- if (!isResolved(news) || output === undefined) return;
161
+ if (!isResolved(news)) return;
162
+ yield* validateExpiry(news);
163
+ if (output === undefined) return;
164
+ const expiresAt = news.expiresAt;
125
165
  yield* validate(output, news);
126
166
  const deployment = yield* client
127
167
  .getDeployment(output.name)
@@ -129,7 +169,11 @@ export const provider = Effect.gen(function* () {
129
169
  if (deployment === undefined) return { action: "update" };
130
170
  const current = yield* attributes(deployment);
131
171
  yield* validate(current, news);
132
- if ((news.reference ?? output.reference) !== current.reference)
172
+ if (
173
+ (news.reference ?? output.reference) !== current.reference ||
174
+ (news.class !== undefined && news.class !== current.class) ||
175
+ (expiresAt !== undefined && expiresAt !== (current.expiresAt ?? null))
176
+ )
133
177
  return { action: "update" };
134
178
  }),
135
179
  read: Effect.fn("Deployment.read")(function* ({
@@ -161,6 +205,7 @@ export const provider = Effect.gen(function* () {
161
205
  news,
162
206
  output,
163
207
  }) {
208
+ yield* validateExpiry(news);
164
209
  if (output === undefined) yield* checkpointCreate(fqn, instanceId, news);
165
210
  if (output !== undefined) yield* validate(output, news);
166
211
  let deployment =
@@ -173,6 +218,7 @@ export const provider = Effect.gen(function* () {
173
218
  news.reference ??
174
219
  output?.reference ??
175
220
  (yield* resourceName("deployment", fqn, instanceId));
221
+ const expiresAt = news.expiresAt;
176
222
  if (deployment === undefined) {
177
223
  const existing = yield* find(news.projectId, reference);
178
224
  if (existing !== undefined && !(yield* shouldAdopt(fqn)))
@@ -191,21 +237,36 @@ export const provider = Effect.gen(function* () {
191
237
  type: news.type,
192
238
  reference,
193
239
  ...(news.region === undefined ? {} : { region: news.region }),
240
+ ...(news.class === undefined ? {} : { class: news.class }),
241
+ ...(expiresAt === undefined ? {} : { expiresAt }),
194
242
  });
195
243
  }
196
244
  }
197
245
  const current = yield* attributes(deployment);
198
246
  yield* validate(current, news);
199
- if (current.reference !== reference) {
200
- const existing = yield* find(news.projectId, reference);
201
- if (existing !== undefined && existing.name !== current.name)
202
- return yield* new OwnedBySomeoneElse({
203
- message: "The requested deployment reference is already in use.",
204
- resourceType: Deployment.Type,
205
- physicalName: reference,
206
- });
247
+ if (
248
+ current.reference !== reference ||
249
+ (news.class !== undefined && news.class !== current.class) ||
250
+ (expiresAt !== undefined && expiresAt !== (current.expiresAt ?? null))
251
+ ) {
252
+ if (current.reference !== reference) {
253
+ const existing = yield* find(news.projectId, reference);
254
+ if (existing !== undefined && existing.name !== current.name)
255
+ return yield* new OwnedBySomeoneElse({
256
+ message: "The requested deployment reference is already in use.",
257
+ resourceType: Deployment.Type,
258
+ physicalName: reference,
259
+ });
260
+ }
207
261
  yield* client.updateDeployment(current.name, {
208
262
  reference,
263
+ ...(news.class === undefined || news.class === current.class
264
+ ? {}
265
+ : { class: news.class }),
266
+ ...(expiresAt === undefined ||
267
+ expiresAt === (current.expiresAt ?? null)
268
+ ? {}
269
+ : { expiresAt }),
209
270
  });
210
271
  deployment = yield* client.getDeployment(current.name);
211
272
  }
@@ -221,7 +282,7 @@ export const provider = Effect.gen(function* () {
221
282
 
222
283
  interface LocalConfig {
223
284
  readonly name: string;
224
- readonly props: DeploymentProps;
285
+ readonly props: Omit<DeploymentProps, "class" | "expiresAt">;
225
286
  }
226
287
 
227
288
  /**
@@ -248,9 +309,10 @@ export const localLayer = LocalProvider.make(
248
309
  instanceId,
249
310
  news,
250
311
  }) {
312
+ const { class: _class, expiresAt: _expiresAt, ...props } = news;
251
313
  return {
252
314
  name: yield* resourceName("deployment", fqn, instanceId),
253
- props: news,
315
+ props,
254
316
  } satisfies LocalConfig;
255
317
  }),
256
318
  start: Effect.fn("Deployment.localStart")(function* ({
@@ -1,12 +1,19 @@
1
+ import * as Arr from "effect/Array";
2
+ import * as Str from "effect/String";
1
3
  import * as Config from "effect/Config";
2
4
  import * as Context from "effect/Context";
5
+ import * as Deferred from "effect/Deferred";
3
6
  import * as Effect from "effect/Effect";
4
7
  import * as FileSystem from "effect/FileSystem";
5
8
  import * as Layer from "effect/Layer";
6
9
  import * as Path from "effect/Path";
7
10
  import * as Redacted from "effect/Redacted";
11
+ import * as Result from "effect/Result";
8
12
  import * as Schema from "effect/Schema";
13
+ import * as Stream from "effect/Stream";
9
14
  import { ChildProcess, ChildProcessSpawner } from "effect/process";
15
+ import { Buffer } from "node:buffer";
16
+ import { stripVTControlCharacters } from "node:util";
10
17
 
11
18
  export interface PrepareCommand {
12
19
  readonly command: string;
@@ -42,7 +49,20 @@ export class CommandError extends Schema.TaggedError<
42
49
  operation: Schema.Literals(["prepare", "deploy"]),
43
50
  reason: Schema.Literals(["configuration", "spawn", "exit"]),
44
51
  exitCode: Schema.optionalKey(Schema.Finite),
45
- }) {}
52
+ signal: Schema.optionalKey(Schema.String),
53
+ stdout: Schema.optionalKey(Schema.String),
54
+ stderr: Schema.optionalKey(Schema.String),
55
+ }) {
56
+ override get message(): string {
57
+ const status =
58
+ this.signal === undefined
59
+ ? this.exitCode === undefined
60
+ ? this.reason
61
+ : `exit code ${this.exitCode}`
62
+ : `signal ${this.signal}`;
63
+ return `${this.operation} command failed (${status})${this.stdout === undefined ? "" : `\nstdout:\n${this.stdout}`}${this.stderr === undefined ? "" : `\nstderr:\n${this.stderr}`}`;
64
+ }
65
+ }
46
66
 
47
67
  export class CommandRunner extends Context.Service<
48
68
  CommandRunner,
@@ -124,6 +144,92 @@ const packageBin = Effect.fn("CommandRunner.packageBin")(function* (
124
144
  }
125
145
  });
126
146
 
147
+ const outputTailSize = 8192;
148
+ const redaction = "<REDACTED>";
149
+ // Short needles match common diagnostic text rather than useful credentials.
150
+ const minimumCredentialLength = 8;
151
+
152
+ const outputTail = <E>(
153
+ stream: Stream.Stream<Uint8Array, E>,
154
+ secrets: ReadonlyArray<string>,
155
+ ) => {
156
+ const credentials = Arr.flatMap(
157
+ Arr.filter(secrets, (value) => value.length >= minimumCredentialLength),
158
+ (value: string) => {
159
+ const bytes = Buffer.from(value);
160
+ const base64 = Arr.flatMap(
161
+ ["base64", "base64url"] as const,
162
+ (encoding) => [
163
+ Str.replace(/=+$/, "")(bytes.toString(encoding)),
164
+ ...Arr.map([0, 1, 2], (offset) =>
165
+ // The first and last partial sextets depend on bytes outside the key.
166
+ Str.slice(
167
+ Math.ceil((offset * 8) / 6),
168
+ Math.floor(((offset + bytes.length) * 8) / 6),
169
+ )(Buffer.concat([Buffer.alloc(offset), bytes]).toString(encoding)),
170
+ ),
171
+ ],
172
+ );
173
+ return [value, ...base64];
174
+ },
175
+ );
176
+ const percentEncoded = Arr.map(
177
+ Arr.filter(secrets, (value) => value.length >= minimumCredentialLength),
178
+ (value) =>
179
+ Arr.join(
180
+ Arr.map(
181
+ Str.split(/(%[0-9A-F]{2})/)(encodeURIComponent(value)),
182
+ (part) =>
183
+ Str.startsWith("%")(part)
184
+ ? Arr.join(
185
+ Arr.map(Str.split("")(part), (char) =>
186
+ /[A-F]/.test(char)
187
+ ? `[${char}${Str.toLowerCase(char)}]`
188
+ : char,
189
+ ),
190
+ "",
191
+ )
192
+ : Str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")(part),
193
+ ),
194
+ "",
195
+ ),
196
+ );
197
+ return stream.pipe(
198
+ Stream.decodeText(),
199
+ Stream.runFold(
200
+ () => ({ text: "", truncated: false }),
201
+ (tail, chunk) => {
202
+ const text = tail.text + chunk;
203
+ return {
204
+ text: Str.slice(-outputTailSize)(text),
205
+ truncated: tail.truncated || text.length > outputTailSize,
206
+ };
207
+ },
208
+ ),
209
+ Effect.map(({ text, truncated }) => {
210
+ text = stripVTControlCharacters(text);
211
+ if (truncated) {
212
+ // A clipped token may be an unrecognised deploy key. Drop it whole.
213
+ text = Str.replace(/^\S*/, "")(text);
214
+ }
215
+ const pattern = new RegExp(
216
+ Arr.join(
217
+ [
218
+ "(?:prod|dev|preview|project|custom):[^\\s|]+\\|[^\\s\\\\\"'&)]+",
219
+ ...percentEncoded,
220
+ ...Arr.map(credentials, (value) =>
221
+ Str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")(value),
222
+ ),
223
+ ],
224
+ "|",
225
+ ),
226
+ "g",
227
+ );
228
+ return Str.slice(-outputTailSize)(Str.replace(pattern, redaction)(text));
229
+ }),
230
+ );
231
+ };
232
+
127
233
  /**
128
234
  * @internal
129
235
  */
@@ -139,7 +245,77 @@ export const layer = Layer.effect(
139
245
  args: ReadonlyArray<string>,
140
246
  cwd: string,
141
247
  env: Record<string, string | undefined>,
248
+ credentials: ReadonlyArray<string> = [],
142
249
  ) {
250
+ if (operation === "deploy") {
251
+ return yield* Effect.scoped(
252
+ Effect.gen(function* () {
253
+ const child = yield* spawner.spawn(
254
+ ChildProcess.make(command, args, {
255
+ cwd,
256
+ env,
257
+ extendEnv: false,
258
+ stdin: "ignore",
259
+ stdout: "pipe",
260
+ stderr: "pipe",
261
+ }),
262
+ );
263
+ const exited = yield* Deferred.make<void>();
264
+ // Descendants can inherit pipes and keep them open after the CLI exits.
265
+ const drainDeadline = Deferred.await(exited).pipe(
266
+ Effect.andThen(Effect.sleep("1 second")),
267
+ );
268
+ const [code, stdout, stderr] = yield* Effect.all(
269
+ [
270
+ child.exitCode.pipe(
271
+ Effect.result,
272
+ Effect.tap(() => Deferred.succeed(exited, undefined)),
273
+ ),
274
+ outputTail(
275
+ child.stdout.pipe(Stream.interruptWhen(drainDeadline)),
276
+ credentials,
277
+ ),
278
+ outputTail(
279
+ child.stderr.pipe(Stream.interruptWhen(drainDeadline)),
280
+ credentials,
281
+ ),
282
+ ],
283
+ { concurrency: "unbounded" },
284
+ );
285
+ if (Result.isFailure(code)) {
286
+ // The spawner exposes a terminating signal only in its cause message.
287
+ const cause = code.failure.cause;
288
+ const signal =
289
+ cause instanceof Error
290
+ ? /^Process interrupted due to receipt of signal: '(SIG[A-Z0-9]+)'$/.exec(
291
+ cause.message,
292
+ )?.[1]
293
+ : undefined;
294
+ return yield* CommandError.make({
295
+ operation,
296
+ reason: "exit",
297
+ ...(signal === undefined ? {} : { signal }),
298
+ stdout,
299
+ stderr,
300
+ });
301
+ }
302
+ if (code.success !== 0)
303
+ return yield* CommandError.make({
304
+ operation,
305
+ reason: "exit",
306
+ exitCode: Number(code.success),
307
+ stdout,
308
+ stderr,
309
+ });
310
+ }),
311
+ ).pipe(
312
+ Effect.mapError((error) =>
313
+ Schema.is(CommandError)(error)
314
+ ? error
315
+ : CommandError.make({ operation, reason: "spawn" }),
316
+ ),
317
+ );
318
+ }
143
319
  const code = yield* spawner
144
320
  .exitCode(
145
321
  ChildProcess.make(command, args, {
@@ -234,6 +410,11 @@ export const layer = Layer.effect(
234
410
  LOCALAPPDATA: temp,
235
411
  XDG_CONFIG_HOME: temp,
236
412
  },
413
+ [
414
+ Redacted.value(
415
+ target._tag === "Cloud" ? target.deployKey : target.adminKey,
416
+ ),
417
+ ],
237
418
  );
238
419
  }).pipe(
239
420
  Effect.mapError((error) =>