@livestore/utils-dev 0.4.0-dev.2 → 0.4.0-dev.5

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.
@@ -1 +1 @@
1
- {"version":3,"file":"Vitest.js","sourceRoot":"","sources":["../../src/node-vitest/Vitest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAA;AAE3C,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAA;AACxC,OAAO,EAAc,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAA+B,MAAM,yBAAyB,CAAA;AACpH,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAE7C,cAAc,gBAAgB,CAAA;AAE9B,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,IAAI,SAAS,CAAC,GAAG,EAAE,KAAK,SAAS,CAAC,CAAA;AAEpG,MAAM,CAAC,MAAM,eAAe,GAC1B,CAAyB,SAAoC,EAAE,EAAE,CACjE,CAAC,WAA+B,EAAE,EAAE,CAClC,WAAW,CAAC,WAAW,EAAE,SAAS,CAAC,CAAA;AASvC,MAAM,CAAC,MAAM,WAAW,GACtB,CACE,WAA+B,EAC/B,EACE,MAAM,EACN,SAAS,EACT,OAAO,GAAG,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EACjC,SAAS,GAAG,KAAK,MAMf,EAAE,EACN,EAAE,CACJ,CACE,IAAmE,EACH,EAAE;IAClE,MAAM,QAAQ,GAAG,GAAG,WAAW,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,IAAI,WAAW,CAAC,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,IAAI,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAA;IACxG,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Q,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,GAAG;YAC1C,KAAK,EAAE,GAAG,QAAQ,kCAAkC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG;SAChF,CAAC,EACN,eAAe,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EACpD,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,EAC7B,MAAM,CAAC,MAAM,EAAE,qFAAqF;IACpG,MAAM,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC,CACzB,CAAA;AACV,CAAC,CAAA"}
package/package.json CHANGED
@@ -1,24 +1,24 @@
1
1
  {
2
2
  "name": "@livestore/utils-dev",
3
- "version": "0.4.0-dev.2",
3
+ "version": "0.4.0-dev.5",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
- "./src/node-vitest/polyfill.ts"
6
+ "./src/node-vitest/global.ts"
7
7
  ],
8
8
  "exports": {
9
9
  "./node": "./dist/node/mod.js",
10
10
  "./node-vitest": "./dist/node-vitest/mod.js"
11
11
  },
12
12
  "dependencies": {
13
- "@effect/opentelemetry": "0.56.1",
14
- "@effect/vitest": "0.25.0",
13
+ "@effect/opentelemetry": "0.56.4",
14
+ "@effect/vitest": "0.25.1",
15
15
  "@opentelemetry/api": "1.9.0",
16
16
  "@opentelemetry/exporter-metrics-otlp-http": "0.203.0",
17
17
  "@opentelemetry/exporter-trace-otlp-http": "0.203.0",
18
18
  "@opentelemetry/sdk-metrics": "2.0.1",
19
19
  "@opentelemetry/sdk-trace-base": "2.0.1",
20
20
  "@opentelemetry/sdk-trace-node": "2.0.1",
21
- "@livestore/utils": "0.4.0-dev.2"
21
+ "@livestore/utils": "0.4.0-dev.5"
22
22
  },
23
23
  "devDependencies": {},
24
24
  "files": [
@@ -31,7 +31,7 @@
31
31
  "publishConfig": {
32
32
  "access": "public",
33
33
  "sideEffects": [
34
- "./dist/node-vitest/polyfill.js"
34
+ "./dist/node-vitest/global.js"
35
35
  ]
36
36
  },
37
37
  "scripts": {
@@ -0,0 +1,99 @@
1
+ import { isNotUndefined, shouldNeverHappen } from '@livestore/utils'
2
+ import { Command, type CommandExecutor, Effect, identity, type PlatformError, Schema } from '@livestore/utils/effect'
3
+
4
+ export const cmd: (
5
+ commandInput: string | (string | undefined)[],
6
+ options?:
7
+ | {
8
+ cwd?: string
9
+ stderr?: 'inherit' | 'pipe'
10
+ stdout?: 'inherit' | 'pipe'
11
+ shell?: boolean
12
+ env?: Record<string, string | undefined>
13
+ }
14
+ | undefined,
15
+ ) => Effect.Effect<CommandExecutor.ExitCode, PlatformError.PlatformError | CmdError, CommandExecutor.CommandExecutor> =
16
+ Effect.fn('cmd')(function* (commandInput, options) {
17
+ const cwd = options?.cwd ?? process.env.WORKSPACE_ROOT ?? shouldNeverHappen('WORKSPACE_ROOT is not set')
18
+ const [command, ...args] = Array.isArray(commandInput)
19
+ ? commandInput.filter(isNotUndefined)
20
+ : commandInput.split(' ')
21
+
22
+ const debugEnvStr = Object.entries(options?.env ?? {})
23
+ .map(([key, value]) => `${key}='${value}' `)
24
+ .join('')
25
+ const subshellStr = options?.shell ? ' (in subshell)' : ''
26
+ const commandDebugStr = debugEnvStr + [command, ...args].join(' ')
27
+
28
+ yield* Effect.logDebug(`Running '${commandDebugStr}' in '${cwd}'${subshellStr}`)
29
+ yield* Effect.annotateCurrentSpan({ 'span.label': commandDebugStr, cwd, command, args })
30
+
31
+ return yield* Command.make(command!, ...args).pipe(
32
+ // TODO don't forward abort signal to the command
33
+ Command.stdin('inherit'), // Forward stdin to the command
34
+ // inherit = Stream stdout to process.stdout, pipe = Stream stdout to process.stderr
35
+ Command.stdout(options?.stdout ?? 'inherit'),
36
+ // inherit = Stream stderr to process.stderr, pipe = Stream stderr to process.stdout
37
+ Command.stderr(options?.stderr ?? 'inherit'),
38
+ Command.workingDirectory(cwd),
39
+ options?.shell ? Command.runInShell(true) : identity,
40
+ Command.env(options?.env ?? {}),
41
+ Command.exitCode,
42
+ Effect.tap((exitCode) =>
43
+ exitCode === 0
44
+ ? Effect.void
45
+ : Effect.fail(
46
+ CmdError.make({
47
+ command: command!,
48
+ args,
49
+ cwd,
50
+ env: options?.env ?? {},
51
+ stderr: options?.stderr ?? 'inherit',
52
+ }),
53
+ ),
54
+ ),
55
+ )
56
+ })
57
+
58
+ export const cmdText: (
59
+ commandInput: string | (string | undefined)[],
60
+ options?: {
61
+ cwd?: string
62
+ stderr?: 'inherit' | 'pipe'
63
+ runInShell?: boolean
64
+ env?: Record<string, string | undefined>
65
+ },
66
+ ) => Effect.Effect<string, PlatformError.PlatformError, CommandExecutor.CommandExecutor> = Effect.fn('cmdText')(
67
+ function* (commandInput, options) {
68
+ const cwd = options?.cwd ?? process.env.WORKSPACE_ROOT ?? shouldNeverHappen('WORKSPACE_ROOT is not set')
69
+ const [command, ...args] = Array.isArray(commandInput)
70
+ ? commandInput.filter(isNotUndefined)
71
+ : commandInput.split(' ')
72
+ const debugEnvStr = Object.entries(options?.env ?? {})
73
+ .map(([key, value]) => `${key}='${value}' `)
74
+ .join('')
75
+
76
+ const commandDebugStr = debugEnvStr + [command, ...args].join(' ')
77
+ const subshellStr = options?.runInShell ? ' (in subshell)' : ''
78
+
79
+ yield* Effect.logDebug(`Running '${commandDebugStr}' in '${cwd}'${subshellStr}`)
80
+ yield* Effect.annotateCurrentSpan({ 'span.label': commandDebugStr, command, cwd })
81
+
82
+ return yield* Command.make(command!, ...args).pipe(
83
+ // inherit = Stream stderr to process.stderr, pipe = Stream stderr to process.stdout
84
+ Command.stderr(options?.stderr ?? 'inherit'),
85
+ Command.workingDirectory(cwd),
86
+ options?.runInShell ? Command.runInShell(true) : identity,
87
+ Command.env(options?.env ?? {}),
88
+ Command.string,
89
+ )
90
+ },
91
+ )
92
+
93
+ export class CmdError extends Schema.TaggedError<CmdError>()('CmdError', {
94
+ command: Schema.String,
95
+ args: Schema.Array(Schema.String),
96
+ cwd: Schema.String,
97
+ env: Schema.Record({ key: Schema.String, value: Schema.String.pipe(Schema.UndefinedOr) }),
98
+ stderr: Schema.Literal('inherit', 'pipe'),
99
+ }) {}
package/src/node/mod.ts CHANGED
@@ -1,19 +1,9 @@
1
1
  import { performance } from 'node:perf_hooks'
2
2
 
3
3
  import * as OtelNodeSdk from '@effect/opentelemetry/NodeSdk'
4
- import { IS_BUN, isNonEmptyString, isNotUndefined, shouldNeverHappen } from '@livestore/utils'
5
- import type { CommandExecutor, PlatformError, Tracer } from '@livestore/utils/effect'
6
- import {
7
- Command,
8
- Config,
9
- Effect,
10
- FiberRef,
11
- identity,
12
- Layer,
13
- LogLevel,
14
- OtelTracer,
15
- Schema,
16
- } from '@livestore/utils/effect'
4
+ import { IS_BUN, isNonEmptyString } from '@livestore/utils'
5
+ import type { Tracer } from '@livestore/utils/effect'
6
+ import { Config, Effect, FiberRef, Layer, LogLevel, OtelTracer } from '@livestore/utils/effect'
17
7
  import { OtelLiveDummy } from '@livestore/utils/node'
18
8
  import * as otel from '@opentelemetry/api'
19
9
  import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
@@ -23,8 +13,10 @@ import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'
23
13
 
24
14
  export { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
25
15
  export { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
26
-
16
+ export * from './cmd.ts'
27
17
  export * as FileLogger from './FileLogger.ts'
18
+ export * from './vitest-docker-compose-setup.ts'
19
+ export * from './vitest-wrangler-setup.ts'
28
20
 
29
21
  export const OtelLiveHttp = ({
30
22
  serviceName,
@@ -169,100 +161,3 @@ export const getTracingBackendUrl = (span: otel.Span) =>
169
161
  // TODO make dynamic via env var
170
162
  return `${grafanaEndpoint}/explore?${searchParams.toString()}`
171
163
  })
172
-
173
- export const cmd: (
174
- commandInput: string | (string | undefined)[],
175
- options?:
176
- | {
177
- cwd?: string
178
- stderr?: 'inherit' | 'pipe'
179
- stdout?: 'inherit' | 'pipe'
180
- shell?: boolean
181
- env?: Record<string, string | undefined>
182
- }
183
- | undefined,
184
- ) => Effect.Effect<CommandExecutor.ExitCode, PlatformError.PlatformError | CmdError, CommandExecutor.CommandExecutor> =
185
- Effect.fn('cmd')(function* (commandInput, options) {
186
- const cwd = options?.cwd ?? process.env.WORKSPACE_ROOT ?? shouldNeverHappen('WORKSPACE_ROOT is not set')
187
- const [command, ...args] = Array.isArray(commandInput)
188
- ? commandInput.filter(isNotUndefined)
189
- : commandInput.split(' ')
190
-
191
- const debugEnvStr = Object.entries(options?.env ?? {})
192
- .map(([key, value]) => `${key}='${value}' `)
193
- .join('')
194
- const subshellStr = options?.shell ? ' (in subshell)' : ''
195
- const commandDebugStr = debugEnvStr + [command, ...args].join(' ')
196
-
197
- yield* Effect.logDebug(`Running '${commandDebugStr}' in '${cwd}'${subshellStr}`)
198
- yield* Effect.annotateCurrentSpan({ 'span.label': commandDebugStr, cwd, command, args })
199
-
200
- return yield* Command.make(command!, ...args).pipe(
201
- // TODO don't forward abort signal to the command
202
- Command.stdin('inherit'), // Forward stdin to the command
203
- // inherit = Stream stdout to process.stdout, pipe = Stream stdout to process.stderr
204
- Command.stdout(options?.stdout ?? 'inherit'),
205
- // inherit = Stream stderr to process.stderr, pipe = Stream stderr to process.stdout
206
- Command.stderr(options?.stderr ?? 'inherit'),
207
- Command.workingDirectory(cwd),
208
- options?.shell ? Command.runInShell(true) : identity,
209
- Command.env(options?.env ?? {}),
210
- Command.exitCode,
211
- Effect.tap((exitCode) =>
212
- exitCode === 0
213
- ? Effect.void
214
- : Effect.fail(
215
- CmdError.make({
216
- command: command!,
217
- args,
218
- cwd,
219
- env: options?.env ?? {},
220
- stderr: options?.stderr ?? 'inherit',
221
- }),
222
- ),
223
- ),
224
- )
225
- })
226
-
227
- export const cmdText: (
228
- commandInput: string | (string | undefined)[],
229
- options?: {
230
- cwd?: string
231
- stderr?: 'inherit' | 'pipe'
232
- runInShell?: boolean
233
- env?: Record<string, string | undefined>
234
- },
235
- ) => Effect.Effect<string, PlatformError.PlatformError, CommandExecutor.CommandExecutor> = Effect.fn('cmdText')(
236
- function* (commandInput, options) {
237
- const cwd = options?.cwd ?? process.env.WORKSPACE_ROOT ?? shouldNeverHappen('WORKSPACE_ROOT is not set')
238
- const [command, ...args] = Array.isArray(commandInput)
239
- ? commandInput.filter(isNotUndefined)
240
- : commandInput.split(' ')
241
- const debugEnvStr = Object.entries(options?.env ?? {})
242
- .map(([key, value]) => `${key}='${value}' `)
243
- .join('')
244
-
245
- const commandDebugStr = debugEnvStr + [command, ...args].join(' ')
246
- const subshellStr = options?.runInShell ? ' (in subshell)' : ''
247
-
248
- yield* Effect.logDebug(`Running '${commandDebugStr}' in '${cwd}'${subshellStr}`)
249
- yield* Effect.annotateCurrentSpan({ 'span.label': commandDebugStr, command, cwd })
250
-
251
- return yield* Command.make(command!, ...args).pipe(
252
- // inherit = Stream stderr to process.stderr, pipe = Stream stderr to process.stdout
253
- Command.stderr(options?.stderr ?? 'inherit'),
254
- Command.workingDirectory(cwd),
255
- options?.runInShell ? Command.runInShell(true) : identity,
256
- Command.env(options?.env ?? {}),
257
- Command.string,
258
- )
259
- },
260
- )
261
-
262
- export class CmdError extends Schema.TaggedError<CmdError>()('CmdError', {
263
- command: Schema.String,
264
- args: Schema.Array(Schema.String),
265
- cwd: Schema.String,
266
- env: Schema.Record({ key: Schema.String, value: Schema.String.pipe(Schema.UndefinedOr) }),
267
- stderr: Schema.Literal('inherit', 'pipe'),
268
- }) {}
@@ -0,0 +1,182 @@
1
+ import { spawn } from 'node:child_process'
2
+ import path from 'node:path'
3
+ import { Effect, UnknownError } from '@livestore/utils/effect'
4
+ import { cmd } from './cmd.ts'
5
+
6
+ export const startDockerComposeServices = (args: StartDockerComposeServicesArgs) =>
7
+ Effect.tryPromise({
8
+ try: () => startDockerComposeServicesPromise(args),
9
+ catch: (error) => UnknownError.make({ cause: new Error(`Failed to start Docker Compose: ${error}`) }),
10
+ }).pipe(Effect.withSpan('startDockerComposeServices'))
11
+
12
+ type StartDockerComposeServicesArgs = {
13
+ composeFilePath?: string
14
+ cwd: string
15
+ serviceName?: string
16
+ waitForLog?: string
17
+ env?: Record<string, string>
18
+ healthCheck?: {
19
+ url: string // URL template with ${port} placeholder
20
+ expectedStatus?: number // default 200
21
+ maxAttempts?: number // default 30
22
+ delayMs?: number // default 1000
23
+ }
24
+ /** @default false */
25
+ forwardLogs?: boolean
26
+ }
27
+
28
+ export const pullDockerComposeImages = ({
29
+ cwd,
30
+ composeFilePath,
31
+ }: Pick<StartDockerComposeServicesArgs, 'composeFilePath' | 'cwd'>) =>
32
+ Effect.gen(function* () {
33
+ const resolvedComposeFilePath = path.resolve(composeFilePath ?? path.join(cwd, 'docker-compose.yml'))
34
+ yield* cmd(['docker', 'compose', '-f', resolvedComposeFilePath, 'pull'], { cwd })
35
+ }).pipe(Effect.withSpan('pullDockerComposeImages'))
36
+
37
+ /**
38
+ * Starts Docker Compose services for testing with automatic cleanup.
39
+ * Automatically allocates a free port and passes it as EXPOSED_PORT environment variable.
40
+ *
41
+ * @param composeFilePath - Path to docker-compose.yml file (defaults to `${cwd}/docker-compose.yml`)
42
+ * @param cwd - Working directory for Docker Compose commands
43
+ * @param env - Environment variables to pass to the Docker Compose commands (useful for passing ports)
44
+ * @param serviceName - Optional specific service to start (omit to start all)
45
+ * @param waitForLog - Log pattern to wait for before considering services ready
46
+ * @param healthCheck - Health check configuration for waiting until service is ready
47
+ */
48
+ // TODO refactor implementation with Effect
49
+ // TODO add test for this
50
+ export const startDockerComposeServicesPromise = async ({
51
+ composeFilePath,
52
+ cwd,
53
+ serviceName,
54
+ waitForLog,
55
+ healthCheck,
56
+ env,
57
+ forwardLogs = false,
58
+ }: StartDockerComposeServicesArgs) => {
59
+ let dockerComposeProcess: ReturnType<typeof spawn> | undefined
60
+
61
+ const setup = async () => {
62
+ const resolvedComposeFilePath = path.resolve(composeFilePath ?? path.join(cwd, 'docker-compose.yml'))
63
+
64
+ // Build the docker compose command arguments
65
+ const composeArgs = ['compose', '-f', resolvedComposeFilePath, 'up']
66
+
67
+ // Add service name if specified
68
+ if (serviceName) {
69
+ composeArgs.push(serviceName)
70
+ }
71
+
72
+ dockerComposeProcess = spawn('docker', composeArgs, {
73
+ stdio: ['ignore', 'pipe', 'pipe'],
74
+ cwd,
75
+ env: { ...process.env, ...env },
76
+ })
77
+
78
+ dockerComposeProcess.stdout?.setEncoding('utf8')
79
+ dockerComposeProcess.stderr?.setEncoding('utf8')
80
+
81
+ if (forwardLogs) {
82
+ dockerComposeProcess.stdout?.on('data', (data: string) => {
83
+ console.log(data)
84
+ })
85
+
86
+ dockerComposeProcess.stderr?.on('data', (data: string) => {
87
+ console.error(data)
88
+ })
89
+ }
90
+
91
+ // Wait for the service to be ready
92
+ if (healthCheck) {
93
+ // Use health check approach
94
+ const maxAttempts = healthCheck.maxAttempts ?? 30
95
+ const delayMs = healthCheck.delayMs ?? 1000
96
+ const expectedStatus = healthCheck.expectedStatus ?? 200
97
+ const healthUrl = healthCheck.url
98
+
99
+ console.log(`Waiting for health check at ${healthUrl}...`)
100
+
101
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
102
+ try {
103
+ const response = await fetch(healthUrl)
104
+ if (response.status === expectedStatus) {
105
+ console.log(`Health check passed after ${attempt} attempts`)
106
+ break
107
+ }
108
+ console.log(`Health check attempt ${attempt}/${maxAttempts}: status ${response.status}`)
109
+ } catch (error) {
110
+ console.log(
111
+ `Health check attempt ${attempt}/${maxAttempts}: ${error instanceof Error ? error.message : 'failed'}`,
112
+ )
113
+ }
114
+
115
+ if (attempt === maxAttempts) {
116
+ throw new Error(`Health check failed after ${maxAttempts} attempts at ${healthUrl}`)
117
+ }
118
+
119
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
120
+ }
121
+ } else if (waitForLog) {
122
+ // Fallback to log-based waiting
123
+ await new Promise<void>((resolve) => {
124
+ const onData = (data: string) => {
125
+ if (data.includes(waitForLog)) {
126
+ dockerComposeProcess?.stdout?.off('data', onData)
127
+ resolve()
128
+ }
129
+ }
130
+ dockerComposeProcess?.stdout?.on('data', onData)
131
+ dockerComposeProcess?.stderr?.on('data', onData)
132
+ })
133
+ } else {
134
+ // No wait condition, just give it a moment to start
135
+ await new Promise((resolve) => setTimeout(resolve, 2000))
136
+ }
137
+
138
+ console.log(`Docker Compose services ready${serviceName ? ` (${serviceName})` : ''}`)
139
+ }
140
+
141
+ const stopDockerComposeServices = async () => {
142
+ if (dockerComposeProcess) {
143
+ console.log('Stopping Docker Compose services...')
144
+
145
+ const resolvedComposeFilePath = path.resolve(composeFilePath ?? path.join(cwd, 'docker-compose.yml'))
146
+
147
+ // Use docker compose down to properly stop and clean up
148
+ const downProcess = spawn('docker', ['compose', '-f', resolvedComposeFilePath, 'down'], {
149
+ stdio: 'inherit',
150
+ cwd,
151
+ })
152
+
153
+ await new Promise<void>((resolve) => {
154
+ downProcess.on('close', () => {
155
+ resolve()
156
+ })
157
+ })
158
+
159
+ dockerComposeProcess.kill('SIGTERM')
160
+ dockerComposeProcess = undefined
161
+ }
162
+ }
163
+
164
+ process.on('exit', () => {
165
+ stopDockerComposeServices()
166
+ })
167
+ process.on('SIGINT', () => {
168
+ stopDockerComposeServices()
169
+ })
170
+ process.on('SIGTERM', () => {
171
+ stopDockerComposeServices()
172
+ })
173
+
174
+ // try {
175
+ // const { afterAll } = await import('vitest')
176
+ // afterAll(async () => {
177
+ // await stopDockerComposeServices()
178
+ // })
179
+ // } catch {}
180
+
181
+ await setup()
182
+ }
@@ -0,0 +1,132 @@
1
+ import { spawn } from 'node:child_process'
2
+ import net from 'node:net'
3
+ import path from 'node:path'
4
+ import { Effect, UnknownError } from '@livestore/utils/effect'
5
+
6
+ export type StartWranglerDevServerArgs = {
7
+ wranglerConfigPath?: string
8
+ cwd: string
9
+ port?: number
10
+ }
11
+
12
+ export const startWranglerDevServer = (args: StartWranglerDevServerArgs) =>
13
+ Effect.tryPromise({
14
+ try: (abortSignal) => startWranglerDevServerPromise({ ...args, abortSignal }),
15
+ catch: (error) => UnknownError.make({ cause: new Error(`Failed to start Wrangler: ${error}`) }),
16
+ }).pipe(Effect.withSpan('startWranglerDevServer'))
17
+
18
+ // TODO refactor implementation with Effect
19
+ // TODO add test for this
20
+ // TODO allow for config to be passed in via code instead of `wrangler.toml` file
21
+ // TODO fix zombie workerd processes causing high CPU usage - see https://github.com/livestorejs/livestore/issues/568
22
+ /**
23
+ * Starts a Wrangler dev server for testing with automatic cleanup.
24
+ *
25
+ * @param wranglerConfigPath - Path to wrangler.toml file (defaults to `${cwd}/wrangler.toml`)
26
+ * @param cwd - Working directory for Wrangler commands
27
+ * @returns Object with allocated port for the dev server
28
+ */
29
+ export const startWranglerDevServerPromise = async ({
30
+ wranglerConfigPath,
31
+ abortSignal,
32
+ cwd,
33
+ port: inputPort,
34
+ }: {
35
+ wranglerConfigPath?: string
36
+ abortSignal?: AbortSignal
37
+ cwd: string
38
+ port?: number
39
+ }) => {
40
+ let wranglerProcess: ReturnType<typeof spawn> | undefined
41
+
42
+ const getFreePort = (): Promise<number> => {
43
+ return new Promise((resolve, reject) => {
44
+ const server = net.createServer()
45
+ server.listen(0, () => {
46
+ const port = (server.address() as net.AddressInfo)?.port
47
+ server.close(() => {
48
+ if (port) {
49
+ resolve(port)
50
+ } else {
51
+ reject(new Error('Could not get port'))
52
+ }
53
+ })
54
+ })
55
+ server.on('error', reject)
56
+ })
57
+ }
58
+
59
+ const setup = async () => {
60
+ const syncPort = inputPort ?? (await getFreePort())
61
+
62
+ const resolvedWranglerConfigPath = path.resolve(wranglerConfigPath ?? path.join(cwd, 'wrangler.toml'))
63
+
64
+ wranglerProcess = spawn(
65
+ 'bunx',
66
+ ['wrangler', 'dev', '--port', syncPort.toString(), '--config', resolvedWranglerConfigPath],
67
+ {
68
+ stdio: ['ignore', 'pipe', 'pipe'],
69
+ cwd,
70
+ env: {
71
+ ...process.env,
72
+ // NODE_OPTIONS: '--inspect --inspect-port=9233',
73
+ },
74
+ signal: abortSignal,
75
+ },
76
+ )
77
+
78
+ wranglerProcess.stdout?.setEncoding('utf8')
79
+ wranglerProcess.stderr?.setEncoding('utf8')
80
+
81
+ wranglerProcess.stdout?.on('data', (data: string) => {
82
+ // console.log(`[wrangler] ${data}`)
83
+ console.log(data)
84
+ })
85
+
86
+ wranglerProcess.stderr?.on('data', (data: string) => {
87
+ // console.error(`[wrangler] ${data}`)
88
+ console.error(data)
89
+ })
90
+
91
+ await new Promise<void>((resolve) => {
92
+ const onData = (data: string) => {
93
+ if (data.includes('Ready on')) {
94
+ wranglerProcess?.stdout?.off('data', onData)
95
+ resolve()
96
+ }
97
+ }
98
+ wranglerProcess?.stdout?.on('data', onData)
99
+ })
100
+
101
+ console.log(`Wrangler dev server ready on port ${syncPort}`)
102
+
103
+ // Wait longer for the Cloudflare Workers runtime to fully initialize
104
+ // console.log('Waiting for Cloudflare Workers runtime to fully initialize...')
105
+ // await new Promise(resolve => setTimeout(resolve, 10000))
106
+
107
+ return { port: syncPort }
108
+ }
109
+
110
+ const killWranglerProcess = () => {
111
+ if (wranglerProcess) {
112
+ console.log('Killing wrangler process...')
113
+ wranglerProcess.kill('SIGTERM')
114
+ wranglerProcess = undefined
115
+ }
116
+ }
117
+
118
+ process.on('exit', killWranglerProcess)
119
+ process.on('SIGINT', killWranglerProcess)
120
+ process.on('SIGTERM', killWranglerProcess)
121
+
122
+ try {
123
+ const { afterAll } = await import('vitest')
124
+ afterAll(() => {
125
+ killWranglerProcess()
126
+ })
127
+ } catch {}
128
+
129
+ const { port } = await setup()
130
+
131
+ return { port, kill: killWranglerProcess }
132
+ }
@@ -43,7 +43,11 @@ export const withTestCtx =
43
43
  const layer = makeLayer?.(testContext)
44
44
 
45
45
  const otelLayer =
46
- DEBUGGER_ACTIVE || forceOtel ? OtelLiveHttp({ serviceName: 'vitest-runner', skipLogUrl: false }) : OtelLiveDummy
46
+ DEBUGGER_ACTIVE || forceOtel
47
+ ? OtelLiveHttp({ rootSpanName: spanName, serviceName: 'vitest-runner', skipLogUrl: false })
48
+ : OtelLiveDummy
49
+
50
+ const combinedLayer = (layer ?? Layer.empty).pipe(Layer.provideMerge(otelLayer))
47
51
 
48
52
  return self.pipe(
49
53
  DEBUGGER_ACTIVE
@@ -53,10 +57,8 @@ export const withTestCtx =
53
57
  label: `${spanName} approaching timeout (timeout: ${Duration.format(timeout)})`,
54
58
  }),
55
59
  DEBUGGER_ACTIVE ? identity : Effect.timeout(timeout),
56
- Effect.provide(otelLayer),
57
- Effect.provide(layer ?? Layer.empty),
60
+ Effect.provide(combinedLayer),
58
61
  Effect.scoped, // We need to scope the effect manually here because otherwise the span is not closed
59
- Effect.withSpan(spanName),
60
62
  Effect.annotateLogs({ suffix }),
61
63
  ) as any
62
64
  }