@gaganref/confect-alchemy 10.6.0-fork.18 → 10.6.0-fork.19

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.
@@ -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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AAK,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 }),\n });\n }),\n);\n"],"mappings":";;;;;;;;;;AAgCA,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,CAAC;CAChD,QAAQ,OAAO,SAAS;EAAC;EAAiB;EAAS;CAAM,CAAC;CAC1D,UAAU,OAAO,YAAY,OAAO,MAAM;AAC5C,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,gBAAb,cAAmC,QAAQ,QAYzC,CAAC,CAAC,yCAAyC,CAAC,CAAC,CAAC;;;;;AAMhD,MAAa,qBAAqB,OAAO,IAAI;CAC3C,MAAM,OAAO,OAAO,MAAM,CAAC,CAAC,KAC1B,OAAO,aAAa,OAAO,OAAO,MAAM,CAAC,GACzC,OAAO,YAAY,EAAE,CACvB;CACA,MAAM,OAAO,OAAO,MAAM,CAAC,CAAC,KAAK,OAAO,YAAY,EAAE,CAAC;CACvD,aAAa,OAAO,OAAO,aAAa,CAA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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,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,CAAC;CAChD,QAAQ,OAAO,SAAS;EAAC;EAAiB;EAAS;CAAM,CAAC;CAC1D,UAAU,OAAO,YAAY,OAAO,MAAM;CAC1C,QAAQ,OAAO,YAAY,OAAO,MAAM;CACxC,QAAQ,OAAO,YAAY,OAAO,MAAM;CACxC,QAAQ,OAAO,YAAY,OAAO,MAAM;AAC1C,CAAC,CAAC,CAAC;CACD,IAAa,UAAkB;EAC7B,MAAM,SACJ,KAAK,WAAW,KAAA,IACZ,KAAK,aAAa,KAAA,IAChB,KAAK,SACL,aAAa,KAAK,aACpB,UAAU,KAAK;EACrB,OAAO,GAAG,KAAK,UAAU,mBAAmB,OAAO,GAAG,KAAK,WAAW,KAAA,IAAY,KAAK,cAAc,KAAK,WAAW,KAAK,WAAW,KAAA,IAAY,KAAK,cAAc,KAAK;CAC3K;AACF;AAEA,IAAa,gBAAb,cAAmC,QAAQ,QAYzC,CAAC,CAAC,yCAAyC,CAAC,CAAC,CAAC;;;;;AAMhD,MAAa,qBAAqB,OAAO,IAAI;CAC3C,MAAM,OAAO,OAAO,MAAM,CAAC,CAAC,KAC1B,OAAO,aAAa,OAAO,OAAO,MAAM,CAAC,GACzC,OAAO,YAAY,EAAE,CACvB;CACA,MA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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,12 +1,12 @@
1
1
  {
2
2
  "name": "@gaganref/confect-alchemy",
3
- "version": "10.6.0-fork.18",
3
+ "version": "10.6.0-fork.19",
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.18",
9
- "@confect/core": "npm:@gaganref/confect-core@10.6.0-fork.18",
8
+ "@confect/cli": "npm:@gaganref/confect-cli@10.6.0-fork.19",
9
+ "@confect/core": "npm:@gaganref/confect-core@10.6.0-fork.19",
10
10
  "alchemy": ">=2.0.0-beta.85 <2.0.0",
11
11
  "convex": "^1.32.0",
12
12
  "effect": "~4.1.4"
@@ -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) =>