@livestore/utils-dev 0.0.0-snapshot-9d8807d2c51c95b4df3556744702cea55dc7ded3 → 0.0.0-snapshot-764973e035e7322a3936e1c79f2e78820e04f73c

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.
Files changed (82) hide show
  1. package/dist/.tsbuildinfo.json +1 -1
  2. package/dist/node/DockerComposeService/DockerComposeService.d.ts +58 -0
  3. package/dist/node/DockerComposeService/DockerComposeService.d.ts.map +1 -0
  4. package/dist/node/DockerComposeService/DockerComposeService.js +144 -0
  5. package/dist/node/DockerComposeService/DockerComposeService.js.map +1 -0
  6. package/dist/node/DockerComposeService/DockerComposeService.test.d.ts +2 -0
  7. package/dist/node/DockerComposeService/DockerComposeService.test.d.ts.map +1 -0
  8. package/dist/node/DockerComposeService/DockerComposeService.test.js +64 -0
  9. package/dist/node/DockerComposeService/DockerComposeService.test.js.map +1 -0
  10. package/dist/node/FileLogger.d.ts +14 -0
  11. package/dist/node/FileLogger.d.ts.map +1 -0
  12. package/dist/node/FileLogger.js +151 -0
  13. package/dist/node/FileLogger.js.map +1 -0
  14. package/dist/node/cmd-log.d.ts +21 -0
  15. package/dist/node/cmd-log.d.ts.map +1 -0
  16. package/dist/node/cmd-log.js +50 -0
  17. package/dist/node/cmd-log.js.map +1 -0
  18. package/dist/node/cmd.d.ts +36 -0
  19. package/dist/node/cmd.d.ts.map +1 -0
  20. package/dist/node/cmd.js +234 -0
  21. package/dist/node/cmd.js.map +1 -0
  22. package/dist/node/cmd.test.d.ts +2 -0
  23. package/dist/node/cmd.test.d.ts.map +1 -0
  24. package/dist/node/cmd.test.js +101 -0
  25. package/dist/node/cmd.test.js.map +1 -0
  26. package/dist/node/mod.d.ts +5 -13
  27. package/dist/node/mod.d.ts.map +1 -1
  28. package/dist/node/mod.js +67 -42
  29. package/dist/node/mod.js.map +1 -1
  30. package/dist/node-vitest/Vitest.d.ts +52 -0
  31. package/dist/node-vitest/Vitest.d.ts.map +1 -0
  32. package/dist/node-vitest/Vitest.js +98 -0
  33. package/dist/node-vitest/Vitest.js.map +1 -0
  34. package/dist/node-vitest/Vitest.test.d.ts +2 -0
  35. package/dist/node-vitest/Vitest.test.d.ts.map +1 -0
  36. package/dist/node-vitest/Vitest.test.js +70 -0
  37. package/dist/node-vitest/Vitest.test.js.map +1 -0
  38. package/dist/node-vitest/global.d.ts +2 -0
  39. package/dist/node-vitest/global.d.ts.map +1 -0
  40. package/dist/node-vitest/{polyfill.js → global.js} +1 -1
  41. package/dist/node-vitest/global.js.map +1 -0
  42. package/dist/node-vitest/mod.d.ts +2 -1
  43. package/dist/node-vitest/mod.d.ts.map +1 -1
  44. package/dist/node-vitest/mod.js +2 -1
  45. package/dist/node-vitest/mod.js.map +1 -1
  46. package/dist/wrangler/WranglerDevServer.d.ts +52 -0
  47. package/dist/wrangler/WranglerDevServer.d.ts.map +1 -0
  48. package/dist/wrangler/WranglerDevServer.js +90 -0
  49. package/dist/wrangler/WranglerDevServer.js.map +1 -0
  50. package/dist/wrangler/WranglerDevServer.test.d.ts +2 -0
  51. package/dist/wrangler/WranglerDevServer.test.d.ts.map +1 -0
  52. package/dist/wrangler/WranglerDevServer.test.js +77 -0
  53. package/dist/wrangler/WranglerDevServer.test.js.map +1 -0
  54. package/dist/wrangler/fixtures/cf-worker.d.ts +8 -0
  55. package/dist/wrangler/fixtures/cf-worker.d.ts.map +1 -0
  56. package/dist/wrangler/fixtures/cf-worker.js +11 -0
  57. package/dist/wrangler/fixtures/cf-worker.js.map +1 -0
  58. package/dist/wrangler/mod.d.ts +2 -0
  59. package/dist/wrangler/mod.d.ts.map +1 -0
  60. package/dist/wrangler/mod.js +2 -0
  61. package/dist/wrangler/mod.js.map +1 -0
  62. package/package.json +16 -22
  63. package/src/node/DockerComposeService/DockerComposeService.test.ts +91 -0
  64. package/src/node/DockerComposeService/DockerComposeService.ts +328 -0
  65. package/src/node/DockerComposeService/test-fixtures/docker-compose.yml +4 -0
  66. package/src/node/FileLogger.ts +206 -0
  67. package/src/node/cmd-log.ts +92 -0
  68. package/src/node/cmd.test.ts +129 -0
  69. package/src/node/cmd.ts +419 -0
  70. package/src/node/mod.ts +81 -82
  71. package/src/node-vitest/Vitest.test.ts +112 -0
  72. package/src/node-vitest/Vitest.ts +238 -0
  73. package/src/node-vitest/mod.ts +3 -1
  74. package/src/wrangler/WranglerDevServer.test.ts +133 -0
  75. package/src/wrangler/WranglerDevServer.ts +180 -0
  76. package/src/wrangler/fixtures/cf-worker.ts +11 -0
  77. package/src/wrangler/fixtures/wrangler.toml +11 -0
  78. package/src/wrangler/mod.ts +6 -0
  79. package/dist/node-vitest/polyfill.d.ts +0 -2
  80. package/dist/node-vitest/polyfill.d.ts.map +0 -1
  81. package/dist/node-vitest/polyfill.js.map +0 -1
  82. /package/src/node-vitest/{polyfill.ts → global.ts} +0 -0
package/package.json CHANGED
@@ -1,34 +1,28 @@
1
1
  {
2
2
  "name": "@livestore/utils-dev",
3
- "version": "0.0.0-snapshot-9d8807d2c51c95b4df3556744702cea55dc7ded3",
3
+ "version": "0.0.0-snapshot-764973e035e7322a3936e1c79f2e78820e04f73c",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
- "./dist/node-vitest/polyfill.js"
6
+ "./src/node-vitest/global.ts",
7
+ "./dist/node-vitest/global.js"
7
8
  ],
8
9
  "exports": {
9
- "./node": {
10
- "types": "./dist/node/mod.d.ts",
11
- "default": "./dist/node/mod.js"
12
- },
13
- "./node-vitest": {
14
- "types": "./dist/node-vitest/mod.d.ts",
15
- "default": "./dist/node-vitest/mod.js"
16
- },
17
- "./node-vitest-polyfill": {
18
- "types": "./dist/node-vitest/polyfill.d.ts",
19
- "default": "./dist/node-vitest/polyfill.js"
20
- }
10
+ "./node": "./dist/node/mod.js",
11
+ "./node-vitest": "./dist/node-vitest/mod.js",
12
+ "./wrangler": "./dist/wrangler/mod.js"
21
13
  },
22
14
  "dependencies": {
23
- "@effect/opentelemetry": "0.48.4",
24
- "@effect/vitest": "0.22.2",
15
+ "@effect/opentelemetry": "0.58.0",
16
+ "@effect/vitest": "0.26.0",
17
+ "@iarna/toml": "2.2.5",
25
18
  "@opentelemetry/api": "1.9.0",
26
- "@opentelemetry/exporter-metrics-otlp-http": "0.200.0",
27
- "@opentelemetry/exporter-trace-otlp-http": "0.200.0",
28
- "@opentelemetry/sdk-metrics": "2.0.0",
29
- "@opentelemetry/sdk-trace-base": "2.0.0",
30
- "@opentelemetry/sdk-trace-node": "2.0.0",
31
- "@livestore/utils": "0.0.0-snapshot-9d8807d2c51c95b4df3556744702cea55dc7ded3"
19
+ "@opentelemetry/exporter-metrics-otlp-http": "0.203.0",
20
+ "@opentelemetry/exporter-trace-otlp-http": "0.203.0",
21
+ "@opentelemetry/sdk-metrics": "2.0.1",
22
+ "@opentelemetry/sdk-trace-base": "2.0.1",
23
+ "@opentelemetry/sdk-trace-node": "2.0.1",
24
+ "wrangler": "4.42.2",
25
+ "@livestore/utils": "0.0.0-snapshot-764973e035e7322a3936e1c79f2e78820e04f73c"
32
26
  },
33
27
  "devDependencies": {},
34
28
  "files": [
@@ -0,0 +1,91 @@
1
+ import path from 'node:path'
2
+ import { Duration, Effect, Layer, Stream } from '@livestore/utils/effect'
3
+ import { PlatformNode } from '@livestore/utils/node'
4
+ import { Vitest } from '@livestore/utils-dev/node-vitest'
5
+ import { expect } from 'vitest'
6
+ import { type DockerComposeArgs, DockerComposeService } from './DockerComposeService.ts'
7
+
8
+ const testTimeout = 30_000
9
+ const testFixturePath = path.join(import.meta.dirname, 'test-fixtures')
10
+
11
+ const DockerComposeTest = (args: Partial<DockerComposeArgs> = {}) =>
12
+ DockerComposeService.Default({
13
+ cwd: testFixturePath,
14
+ ...args,
15
+ })
16
+
17
+ Vitest.describe('DockerComposeService', { timeout: testTimeout }, () => {
18
+ Vitest.describe('Basic Operations', () => {
19
+ const withBasicTest = (args: Partial<DockerComposeArgs> = {}) =>
20
+ Vitest.makeWithTestCtx({
21
+ timeout: testTimeout,
22
+ makeLayer: () => DockerComposeTest(args).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
23
+ })
24
+
25
+ Vitest.scopedLive('can pull docker images', (test) =>
26
+ Effect.gen(function* () {
27
+ const dockerCompose = yield* DockerComposeService
28
+
29
+ // Test that pull operation works (should succeed for hello-world image)
30
+ yield* dockerCompose.pull
31
+ }).pipe(withBasicTest()(test)),
32
+ )
33
+
34
+ Vitest.scopedLive('can start and stop docker compose services', (test) =>
35
+ Effect.gen(function* () {
36
+ const dockerCompose = yield* DockerComposeService
37
+
38
+ // Start the service
39
+ yield* dockerCompose.start({ detached: true })
40
+
41
+ // Stop the service
42
+ yield* dockerCompose.stop
43
+ }).pipe(withBasicTest({ serviceName: 'hello-world' })(test)),
44
+ )
45
+
46
+ Vitest.scopedLive('can get logs from docker compose services', (test) =>
47
+ Effect.gen(function* () {
48
+ const dockerCompose = yield* DockerComposeService
49
+
50
+ // Start the service first
51
+ yield* dockerCompose.start({ detached: true })
52
+
53
+ // Get logs (should contain at least the "Hello from Docker!" message)
54
+ const firstLogLine = yield* dockerCompose.logs().pipe(Stream.runHead)
55
+
56
+ expect(firstLogLine._tag).toBe('Some')
57
+
58
+ // Stop the service
59
+ yield* dockerCompose.stop
60
+ }).pipe(withBasicTest({ serviceName: 'hello-world' })(test)),
61
+ )
62
+ })
63
+
64
+ Vitest.describe('Health Check Operations', () => {
65
+ const withHealthCheckTest = (args: Partial<DockerComposeArgs> = {}) =>
66
+ Vitest.makeWithTestCtx({
67
+ timeout: testTimeout,
68
+ makeLayer: () => DockerComposeTest(args).pipe(Layer.provide(PlatformNode.NodeContext.layer)),
69
+ })
70
+
71
+ Vitest.scopedLive('handles health check timeout gracefully', (test) =>
72
+ Effect.gen(function* () {
73
+ const dockerCompose = yield* DockerComposeService
74
+
75
+ // Test starting with a health check that will timeout (invalid URL)
76
+ const result = yield* dockerCompose
77
+ .start({
78
+ detached: true,
79
+ healthCheck: {
80
+ url: 'http://localhost:99999/nonexistent',
81
+ timeout: Duration.seconds(2),
82
+ },
83
+ })
84
+ .pipe(Effect.either)
85
+
86
+ // Should fail due to health check timeout
87
+ expect(result._tag).toBe('Left')
88
+ }).pipe(withHealthCheckTest({ serviceName: 'hello-world' })(test)),
89
+ )
90
+ })
91
+ })
@@ -0,0 +1,328 @@
1
+ import { omitUndefineds } from '@livestore/utils'
2
+ import {
3
+ Command,
4
+ type CommandExecutor,
5
+ Duration,
6
+ Effect,
7
+ Fiber,
8
+ type PlatformError,
9
+ Schedule,
10
+ Schema,
11
+ type Scope,
12
+ Stream,
13
+ } from '@livestore/utils/effect'
14
+
15
+ export class DockerComposeError extends Schema.TaggedError<DockerComposeError>()('DockerComposeError', {
16
+ cause: Schema.Defect,
17
+ note: Schema.String,
18
+ }) {}
19
+
20
+ export interface DockerComposeArgs {
21
+ readonly cwd: string
22
+ readonly serviceName?: string
23
+ }
24
+
25
+ export interface StartOptions {
26
+ readonly detached?: boolean
27
+ readonly env?: Record<string, string>
28
+ readonly healthCheck?: {
29
+ readonly url: string
30
+ readonly timeout?: Duration.Duration
31
+ readonly interval?: Duration.Duration
32
+ }
33
+ }
34
+
35
+ export interface LogsOptions {
36
+ readonly follow?: boolean
37
+ readonly tail?: number
38
+ readonly since?: string
39
+ }
40
+
41
+ export interface DockerComposeOperations {
42
+ readonly pull: Effect.Effect<void, DockerComposeError | PlatformError.PlatformError>
43
+ readonly start: (
44
+ options?: StartOptions,
45
+ ) => Effect.Effect<void, DockerComposeError | PlatformError.PlatformError, Scope.Scope>
46
+ readonly stop: Effect.Effect<void, DockerComposeError | PlatformError.PlatformError>
47
+ readonly down: (options?: {
48
+ readonly env?: Record<string, string>
49
+ readonly volumes?: boolean
50
+ readonly removeOrphans?: boolean
51
+ }) => Effect.Effect<void, DockerComposeError | PlatformError.PlatformError>
52
+ readonly logs: (
53
+ options?: LogsOptions,
54
+ ) => Stream.Stream<string, DockerComposeError | PlatformError.PlatformError, Scope.Scope>
55
+ }
56
+
57
+ export class DockerComposeService extends Effect.Service<DockerComposeService>()('DockerComposeService', {
58
+ scoped: (args: DockerComposeArgs) =>
59
+ Effect.gen(function* () {
60
+ const { cwd, serviceName } = args
61
+
62
+ const commandExecutorContext = yield* Effect.context<CommandExecutor.CommandExecutor>()
63
+
64
+ const pull = Effect.gen(function* () {
65
+ yield* Effect.log(`Pulling Docker Compose images in ${cwd}`)
66
+
67
+ // TODO (@IMax153) Refactor the effect command related code below as there is probably a much more elegant way to accomplish what we want here in a more effect idiomatic way.
68
+ const pullCommand = Command.make('docker', 'compose', 'pull').pipe(
69
+ Command.workingDirectory(cwd),
70
+ Command.stdout('pipe'),
71
+ Command.stderr('pipe'),
72
+ )
73
+
74
+ const process = yield* pullCommand.pipe(Command.start, Effect.provide(commandExecutorContext))
75
+
76
+ const stdoutFiber = yield* process.stdout.pipe(
77
+ Stream.decodeText('utf8'),
78
+ Stream.runFold('', (acc, chunk) => acc + chunk),
79
+ Effect.fork,
80
+ )
81
+
82
+ const stderrFiber = yield* process.stderr.pipe(
83
+ Stream.decodeText('utf8'),
84
+ Stream.runFold('', (acc, chunk) => acc + chunk),
85
+ Effect.fork,
86
+ )
87
+
88
+ const exitCode = yield* process.exitCode
89
+ const stdout = yield* Fiber.join(stdoutFiber)
90
+ const stderr = yield* Fiber.join(stderrFiber)
91
+
92
+ const exitCodeNumber = Number(exitCode)
93
+
94
+ if (exitCodeNumber !== 0) {
95
+ const stdoutLog = stdout.length > 0 ? stdout : '<empty stdout>'
96
+ const stderrLog = stderr.length > 0 ? stderr : '<empty stderr>'
97
+ const failureMessage = [
98
+ `Docker compose pull failed with exit code ${exitCodeNumber} in ${cwd}`,
99
+ `stdout:\n${stdoutLog}`,
100
+ `stderr:\n${stderrLog}`,
101
+ ].join('\n')
102
+
103
+ yield* Effect.logError(failureMessage)
104
+
105
+ return yield* new DockerComposeError({
106
+ cause: new Error(`Docker compose pull failed with exit code ${exitCodeNumber}`),
107
+ note: failureMessage,
108
+ })
109
+ }
110
+
111
+ yield* Effect.log(`Successfully pulled Docker Compose images`)
112
+ }).pipe(
113
+ Effect.retry({
114
+ schedule: Schedule.exponentialBackoff10Sec,
115
+ while: Schema.is(DockerComposeError),
116
+ }),
117
+ Effect.withSpan('pullDockerComposeImages'),
118
+ Effect.scoped,
119
+ )
120
+
121
+ const start = (options: StartOptions = {}) =>
122
+ Effect.gen(function* () {
123
+ const { detached = true, healthCheck } = options
124
+
125
+ // Build start command
126
+ const baseArgs = ['docker', 'compose', 'up']
127
+ if (detached) baseArgs.push('-d')
128
+ if (serviceName) baseArgs.push(serviceName)
129
+
130
+ const command = yield* Command.make(baseArgs[0]!, ...baseArgs.slice(1)).pipe(
131
+ Command.workingDirectory(cwd),
132
+ Command.env(options.env ?? {}),
133
+ Command.stderr('inherit'),
134
+ Command.stdout('inherit'),
135
+ Command.start,
136
+ Effect.catchAll((cause) =>
137
+ Effect.fail(
138
+ new DockerComposeError({
139
+ cause,
140
+ note: `Failed to start Docker Compose services in ${cwd}`,
141
+ }),
142
+ ),
143
+ ),
144
+ Effect.provide(commandExecutorContext),
145
+ )
146
+
147
+ // Wait for command completion
148
+ yield* command.exitCode.pipe(
149
+ Effect.flatMap((exitCode) =>
150
+ exitCode === 0
151
+ ? Effect.void
152
+ : Effect.fail(
153
+ new DockerComposeError({
154
+ cause: new Error(`Docker compose exited with code ${exitCode}`),
155
+ note: `Docker Compose failed to start with exit code ${exitCode}. Env: ${JSON.stringify(options.env)}`,
156
+ }),
157
+ ),
158
+ ),
159
+ Effect.provide(commandExecutorContext),
160
+ )
161
+
162
+ // Perform health check if requested
163
+ if (healthCheck) {
164
+ yield* performHealthCheck(healthCheck).pipe(Effect.provide(commandExecutorContext))
165
+ }
166
+
167
+ yield* Effect.log(`Docker Compose services started successfully in ${cwd}`)
168
+ }).pipe(Effect.withSpan('startDockerCompose'))
169
+
170
+ const stop = Effect.gen(function* () {
171
+ yield* Effect.log(`Stopping Docker Compose services in ${cwd}`)
172
+
173
+ const stopCommand = serviceName
174
+ ? Command.make('docker', 'compose', 'stop', serviceName)
175
+ : Command.make('docker', 'compose', 'stop')
176
+
177
+ yield* stopCommand.pipe(
178
+ Command.workingDirectory(cwd),
179
+ Command.exitCode,
180
+ Effect.flatMap((exitCode: number) =>
181
+ exitCode === 0
182
+ ? Effect.void
183
+ : Effect.fail(
184
+ new DockerComposeError({
185
+ cause: new Error(`Docker compose stop exited with code ${exitCode}`),
186
+ note: `Failed to stop Docker Compose services`,
187
+ }),
188
+ ),
189
+ ),
190
+ Effect.provide(commandExecutorContext),
191
+ )
192
+
193
+ yield* Effect.log(`Docker Compose services stopped successfully`)
194
+ }).pipe(Effect.withSpan('stopDockerCompose'))
195
+
196
+ const logs = (options: LogsOptions = {}) =>
197
+ Effect.gen(function* () {
198
+ const { follow = false, tail, since } = options
199
+
200
+ const baseArgs = ['docker', 'compose', 'logs']
201
+ if (follow) baseArgs.push('-f')
202
+ if (tail) baseArgs.push('--tail', tail.toString())
203
+ if (since) baseArgs.push('--since', since)
204
+ if (serviceName) baseArgs.push(serviceName)
205
+
206
+ const command = yield* Command.make(baseArgs[0]!, ...baseArgs.slice(1)).pipe(
207
+ Command.workingDirectory(cwd),
208
+ Command.start,
209
+ Effect.catchAll((cause) =>
210
+ Effect.fail(
211
+ new DockerComposeError({
212
+ cause,
213
+ note: `Failed to read Docker Compose logs in ${cwd}`,
214
+ }),
215
+ ),
216
+ ),
217
+ Effect.provide(commandExecutorContext),
218
+ )
219
+
220
+ return command.stdout.pipe(
221
+ Stream.decodeText('utf8'),
222
+ Stream.splitLines,
223
+ Stream.mapError(
224
+ (cause) =>
225
+ new DockerComposeError({
226
+ cause,
227
+ note: `Error reading Docker Compose logs in ${cwd}`,
228
+ }),
229
+ ),
230
+ )
231
+ }).pipe(Stream.unwrapScoped)
232
+
233
+ const down = (options?: {
234
+ readonly env?: Record<string, string>
235
+ readonly volumes?: boolean
236
+ readonly removeOrphans?: boolean
237
+ }) =>
238
+ Effect.gen(function* () {
239
+ yield* Effect.log(`Tearing down Docker Compose services in ${cwd}`)
240
+
241
+ const baseArgs = ['docker', 'compose', 'down']
242
+ if (options?.volumes) baseArgs.push('-v')
243
+ if (options?.removeOrphans) baseArgs.push('--remove-orphans')
244
+ if (serviceName) baseArgs.push(serviceName)
245
+
246
+ yield* Command.make(baseArgs[0]!, ...baseArgs.slice(1)).pipe(
247
+ Command.workingDirectory(cwd),
248
+ Command.env(options?.env ?? {}),
249
+ Command.exitCode,
250
+ Effect.flatMap((exitCode: number) =>
251
+ exitCode === 0
252
+ ? Effect.void
253
+ : Effect.fail(
254
+ new DockerComposeError({
255
+ cause: new Error(`Docker compose down exited with code ${exitCode}`),
256
+ note: `Failed to tear down Docker Compose services`,
257
+ }),
258
+ ),
259
+ ),
260
+ Effect.provide(commandExecutorContext),
261
+ )
262
+
263
+ yield* Effect.log(`Docker Compose services torn down successfully`)
264
+ }).pipe(Effect.withSpan('downDockerCompose'))
265
+
266
+ return { pull, start, stop, down, logs }
267
+ }),
268
+ }) {}
269
+
270
+ const performHealthCheck = ({
271
+ url,
272
+ timeout = Duration.minutes(2),
273
+ interval = Duration.seconds(2),
274
+ }: {
275
+ url: string
276
+ timeout?: Duration.Duration
277
+ interval?: Duration.Duration
278
+ }): Effect.Effect<void, DockerComposeError, CommandExecutor.CommandExecutor | Scope.Scope> =>
279
+ Effect.gen(function* () {
280
+ yield* Effect.log(`Performing health check on ${url}`)
281
+
282
+ const checkHealth = Command.make('curl', '-f', '-s', url).pipe(
283
+ Command.exitCode,
284
+ Effect.map((code: number) => code === 0),
285
+ Effect.catchAll(() => Effect.succeed(false)),
286
+ )
287
+
288
+ const healthCheck = checkHealth.pipe(
289
+ Effect.repeat({
290
+ while: (healthy: boolean) => !healthy,
291
+ schedule: Schedule.fixed(interval),
292
+ }),
293
+ Effect.timeout(timeout),
294
+ Effect.catchAll(() =>
295
+ Effect.fail(
296
+ new DockerComposeError({
297
+ cause: new Error('Health check timeout'),
298
+ note: `Health check failed for ${url} after ${Duration.toMillis(timeout)}ms`,
299
+ }),
300
+ ),
301
+ ),
302
+ )
303
+
304
+ yield* healthCheck
305
+ yield* Effect.log(`Health check passed for ${url}`)
306
+ })
307
+
308
+ // Convenience function for scoped Docker Compose operations with automatic cleanup
309
+ export const startDockerComposeServicesScoped = (
310
+ args: DockerComposeArgs & {
311
+ healthCheck?: StartOptions['healthCheck']
312
+ },
313
+ ): Effect.Effect<
314
+ void,
315
+ DockerComposeError | PlatformError.PlatformError,
316
+ DockerComposeService | CommandExecutor.CommandExecutor | Scope.Scope
317
+ > =>
318
+ Effect.gen(function* () {
319
+ const dockerCompose = yield* DockerComposeService
320
+
321
+ // Start the services
322
+ yield* dockerCompose.start({
323
+ ...omitUndefineds({ healthCheck: args.healthCheck ? args.healthCheck : undefined }),
324
+ })
325
+
326
+ // Add cleanup finalizer to the current scope
327
+ yield* Effect.addFinalizer(() => dockerCompose.stop.pipe(Effect.orDie))
328
+ })
@@ -0,0 +1,4 @@
1
+ services:
2
+ hello-world:
3
+ image: hello-world
4
+ profiles: [manual] # Don't auto-start this service
@@ -0,0 +1,206 @@
1
+ import * as fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import util from 'node:util'
4
+ import {
5
+ Cause,
6
+ Effect,
7
+ FiberId,
8
+ HashMap,
9
+ Inspectable,
10
+ Layer,
11
+ List,
12
+ Logger,
13
+ type LogLevel,
14
+ LogSpan,
15
+ ReadonlyArray,
16
+ } from '@livestore/utils/effect'
17
+
18
+ export const makeFileLogger = (
19
+ logFilePath: string,
20
+ options?: {
21
+ readonly threadName: string
22
+ readonly colors?: boolean
23
+ },
24
+ ) =>
25
+ Layer.unwrapScoped(
26
+ Effect.gen(function* () {
27
+ yield* Effect.sync(() => fs.mkdirSync(path.dirname(logFilePath), { recursive: true }))
28
+
29
+ const logFile = yield* Effect.acquireRelease(
30
+ Effect.sync(() => fs.openSync(logFilePath, 'a', 0o666)),
31
+ (fd) => Effect.sync(() => fs.closeSync(fd)),
32
+ )
33
+
34
+ return Logger.replace(
35
+ Logger.defaultLogger,
36
+ prettyLoggerTty({
37
+ colors: options?.colors ?? false,
38
+ stderr: false,
39
+ formatDate: (date) => `${defaultDateFormat(date)} ${options?.threadName ?? ''}`,
40
+ onLog: (str) => fs.writeSync(logFile, str),
41
+ }),
42
+ )
43
+ }),
44
+ )
45
+
46
+ const withColor = (text: string, ...colors: ReadonlyArray<string>) => {
47
+ let out = ''
48
+ for (let i = 0; i < colors.length; i++) {
49
+ out += `\x1b[${colors[i]}m`
50
+ }
51
+ return `${out}${text}\x1b[0m`
52
+ }
53
+ const withColorNoop = (text: string, ..._colors: ReadonlyArray<string>) => text
54
+
55
+ const colors = {
56
+ bold: '1',
57
+ red: '31',
58
+ green: '32',
59
+ yellow: '33',
60
+ blue: '34',
61
+ cyan: '36',
62
+ white: '37',
63
+ gray: '90',
64
+ black: '30',
65
+ bgBrightRed: '101',
66
+ } as const
67
+
68
+ const logLevelColors: Record<LogLevel.LogLevel['_tag'], ReadonlyArray<string>> = {
69
+ None: [],
70
+ All: [],
71
+ Trace: [colors.gray],
72
+ Debug: [colors.blue],
73
+ Info: [colors.green],
74
+ Warning: [colors.yellow],
75
+ Error: [colors.red],
76
+ Fatal: [colors.bgBrightRed, colors.black],
77
+ }
78
+
79
+ export const defaultDateFormat = (date: Date): string =>
80
+ `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date
81
+ .getSeconds()
82
+ .toString()
83
+ .padStart(2, '0')}.${date.getMilliseconds().toString().padStart(3, '0')}`
84
+
85
+ export const structuredMessage = (u: unknown): unknown => {
86
+ switch (typeof u) {
87
+ case 'bigint':
88
+ case 'function':
89
+ case 'symbol': {
90
+ return String(u)
91
+ }
92
+ default: {
93
+ return Inspectable.toJSON(u)
94
+ }
95
+ }
96
+ }
97
+
98
+ const consoleLogToString = (...s: any[]) => {
99
+ if (s.length === 0) return ''
100
+ const [first, ...rest] = s
101
+ if (typeof first === 'string') {
102
+ return rest.length > 0 ? util.format(first, ...rest.map(structuredMessage)) : first
103
+ }
104
+ return s
105
+ .map((v) => {
106
+ if (typeof v === 'string') return v
107
+ return util.inspect(structuredMessage(v), {
108
+ depth: 3,
109
+ colors: false,
110
+ compact: false,
111
+ breakLength: 120,
112
+ })
113
+ })
114
+ .join(' ')
115
+ }
116
+
117
+ export const prettyLoggerTty = (options: {
118
+ readonly colors: boolean
119
+ readonly stderr: boolean
120
+ readonly formatDate: (date: Date) => string
121
+ readonly onLog?: (str: string) => void
122
+ }) => {
123
+ const color = options.colors ? withColor : withColorNoop
124
+ return Logger.make<unknown, string>(({ annotations, cause, date, fiberId, logLevel, message: message_, spans }) => {
125
+ let str = ''
126
+
127
+ const log = (...s: any[]) => {
128
+ str += `${consoleLogToString(...s)}\n`
129
+ options.onLog?.(str)
130
+ }
131
+
132
+ const logIndented = (...s: any[]) => {
133
+ str += `${consoleLogToString(...s).replace(/^/gm, ' ')}\n`
134
+ options.onLog?.(str)
135
+ }
136
+
137
+ const message = ReadonlyArray.ensure(message_)
138
+
139
+ let firstLine =
140
+ color(`[${options.formatDate(date)}]`, colors.white) +
141
+ ` ${color(logLevel.label, ...logLevelColors[logLevel._tag])}` +
142
+ ` (${FiberId.threadName(fiberId)})`
143
+
144
+ if (List.isCons(spans)) {
145
+ const now = date.getTime()
146
+ const render = LogSpan.render(now)
147
+ for (const span of spans) {
148
+ firstLine += ` ${render(span)}`
149
+ }
150
+ }
151
+
152
+ firstLine += ':'
153
+ let messageIndex = 0
154
+ if (message.length > 0) {
155
+ const firstMaybeString = structuredMessage(message[0])
156
+ if (typeof firstMaybeString === 'string') {
157
+ firstLine += ` ${color(firstMaybeString, colors.bold, colors.cyan)}`
158
+ messageIndex++
159
+ }
160
+ }
161
+
162
+ log(firstLine)
163
+ // if (!processIsBun) console.group()
164
+
165
+ if (!Cause.isEmpty(cause)) {
166
+ logIndented(Cause.pretty(cause, { renderErrorCause: true }))
167
+ }
168
+
169
+ if (messageIndex < message.length) {
170
+ for (; messageIndex < message.length; messageIndex++) {
171
+ const msg = message[messageIndex]
172
+ if (typeof msg === 'object' && msg !== null) {
173
+ logIndented(
174
+ util.inspect(structuredMessage(msg), {
175
+ depth: 3,
176
+ colors: false,
177
+ compact: false,
178
+ breakLength: 120,
179
+ }),
180
+ )
181
+ } else {
182
+ logIndented(Inspectable.redact(msg))
183
+ }
184
+ }
185
+ }
186
+
187
+ if (HashMap.size(annotations) > 0) {
188
+ for (const [key, value] of annotations) {
189
+ const formattedValue =
190
+ typeof value === 'object' && value !== null
191
+ ? util.inspect(structuredMessage(value), {
192
+ depth: 3,
193
+ colors: false,
194
+ compact: false,
195
+ breakLength: 120,
196
+ })
197
+ : Inspectable.redact(value)
198
+ logIndented(color(`${key}:`, colors.bold, colors.white), formattedValue)
199
+ }
200
+ }
201
+
202
+ // if (!processIsBun) console.groupEnd()
203
+
204
+ return str
205
+ })
206
+ }