@livestore/utils-dev 0.0.0-snapshot-dffcd59e9628b35efd943619b722cf924c4ed98f → 0.0.0-snapshot-1c345a0e6695466bdc7c4483444e7b3513620261

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 (72) hide show
  1. package/dist/.tsbuildinfo.json +1 -1
  2. package/dist/node/mod.d.ts +13 -7
  3. package/dist/node/mod.d.ts.map +1 -1
  4. package/dist/node/mod.js +37 -22
  5. package/dist/node/mod.js.map +1 -1
  6. package/dist/node-vitest/mod.d.ts +1 -2
  7. package/dist/node-vitest/mod.d.ts.map +1 -1
  8. package/dist/node-vitest/mod.js +1 -2
  9. package/dist/node-vitest/mod.js.map +1 -1
  10. package/dist/node-vitest/polyfill.d.ts +2 -0
  11. package/dist/node-vitest/polyfill.d.ts.map +1 -0
  12. package/dist/node-vitest/{global.js → polyfill.js} +1 -1
  13. package/dist/node-vitest/polyfill.js.map +1 -0
  14. package/package.json +23 -16
  15. package/src/node/mod.ts +77 -39
  16. package/src/node-vitest/mod.ts +1 -3
  17. package/dist/node/DockerComposeService/DockerComposeService.d.ts +0 -48
  18. package/dist/node/DockerComposeService/DockerComposeService.d.ts.map +0 -1
  19. package/dist/node/DockerComposeService/DockerComposeService.js +0 -107
  20. package/dist/node/DockerComposeService/DockerComposeService.js.map +0 -1
  21. package/dist/node/DockerComposeService/DockerComposeService.test.d.ts +0 -2
  22. package/dist/node/DockerComposeService/DockerComposeService.test.d.ts.map +0 -1
  23. package/dist/node/DockerComposeService/DockerComposeService.test.js +0 -64
  24. package/dist/node/DockerComposeService/DockerComposeService.test.js.map +0 -1
  25. package/dist/node/FileLogger.d.ts +0 -14
  26. package/dist/node/FileLogger.d.ts.map +0 -1
  27. package/dist/node/FileLogger.js +0 -151
  28. package/dist/node/FileLogger.js.map +0 -1
  29. package/dist/node/WranglerDevServer/WranglerDevServer.d.ts +0 -53
  30. package/dist/node/WranglerDevServer/WranglerDevServer.d.ts.map +0 -1
  31. package/dist/node/WranglerDevServer/WranglerDevServer.js +0 -113
  32. package/dist/node/WranglerDevServer/WranglerDevServer.js.map +0 -1
  33. package/dist/node/WranglerDevServer/WranglerDevServer.test.d.ts +0 -2
  34. package/dist/node/WranglerDevServer/WranglerDevServer.test.d.ts.map +0 -1
  35. package/dist/node/WranglerDevServer/WranglerDevServer.test.js +0 -186
  36. package/dist/node/WranglerDevServer/WranglerDevServer.test.js.map +0 -1
  37. package/dist/node/WranglerDevServer/fixtures/cf-worker.d.ts +0 -8
  38. package/dist/node/WranglerDevServer/fixtures/cf-worker.d.ts.map +0 -1
  39. package/dist/node/WranglerDevServer/fixtures/cf-worker.js +0 -11
  40. package/dist/node/WranglerDevServer/fixtures/cf-worker.js.map +0 -1
  41. package/dist/node/WranglerDevServer/process-tree-manager.d.ts +0 -55
  42. package/dist/node/WranglerDevServer/process-tree-manager.d.ts.map +0 -1
  43. package/dist/node/WranglerDevServer/process-tree-manager.js +0 -178
  44. package/dist/node/WranglerDevServer/process-tree-manager.js.map +0 -1
  45. package/dist/node/cmd.d.ts +0 -27
  46. package/dist/node/cmd.d.ts.map +0 -1
  47. package/dist/node/cmd.js +0 -55
  48. package/dist/node/cmd.js.map +0 -1
  49. package/dist/node-vitest/Vitest.d.ts +0 -52
  50. package/dist/node-vitest/Vitest.d.ts.map +0 -1
  51. package/dist/node-vitest/Vitest.js +0 -98
  52. package/dist/node-vitest/Vitest.js.map +0 -1
  53. package/dist/node-vitest/Vitest.test.d.ts +0 -2
  54. package/dist/node-vitest/Vitest.test.d.ts.map +0 -1
  55. package/dist/node-vitest/Vitest.test.js +0 -59
  56. package/dist/node-vitest/Vitest.test.js.map +0 -1
  57. package/dist/node-vitest/global.d.ts +0 -2
  58. package/dist/node-vitest/global.d.ts.map +0 -1
  59. package/dist/node-vitest/global.js.map +0 -1
  60. package/src/node/DockerComposeService/DockerComposeService.test.ts +0 -91
  61. package/src/node/DockerComposeService/DockerComposeService.ts +0 -252
  62. package/src/node/DockerComposeService/test-fixtures/docker-compose.yml +0 -4
  63. package/src/node/FileLogger.ts +0 -206
  64. package/src/node/WranglerDevServer/WranglerDevServer.test.ts +0 -268
  65. package/src/node/WranglerDevServer/WranglerDevServer.ts +0 -220
  66. package/src/node/WranglerDevServer/fixtures/cf-worker.ts +0 -11
  67. package/src/node/WranglerDevServer/fixtures/wrangler.toml +0 -11
  68. package/src/node/WranglerDevServer/process-tree-manager.ts +0 -263
  69. package/src/node/cmd.ts +0 -99
  70. package/src/node-vitest/Vitest.test.ts +0 -101
  71. package/src/node-vitest/Vitest.ts +0 -221
  72. /package/src/node-vitest/{global.ts → polyfill.ts} +0 -0
@@ -1,59 +0,0 @@
1
- import { Effect, FastCheck } from '@livestore/utils/effect';
2
- import * as Vitest from "./Vitest.js";
3
- // Demonstrate enhanced asProp functionality with clear shrinking progress
4
- // This showcases the fix for the "Run 26/6" bug and accurate shrinking detection
5
- Vitest.describe('Vitest.asProp', () => {
6
- const IntArbitrary = FastCheck.integer({ min: 1, max: 100 });
7
- // Always-passing test - should only show initial phase
8
- Vitest.asProp(Vitest.scopedLive, 'always-pass test (shows only initial runs)', [IntArbitrary], (properties, _ctx, enhanced) => Effect.gen(function* () {
9
- const [value] = properties;
10
- if (value === undefined) {
11
- return yield* Effect.fail(new Error('Value is undefined'));
12
- }
13
- console.log(`✅ ALWAYS-PASS [${enhanced._tag.toUpperCase()}]: ` +
14
- (enhanced._tag === 'initial'
15
- ? `Run ${enhanced.runIndex + 1}/${enhanced.numRuns}`
16
- : `Shrink #${enhanced.shrinkAttempt} (finding minimal counterexample)`) +
17
- `, value=${value}, total=${enhanced.totalExecutions}`);
18
- // This test always passes, so no shrinking will occur
19
- return;
20
- }), { fastCheck: { numRuns: 4 } });
21
- // Failing test - should show initial + shrinking phases
22
- let alreadyFailed = false;
23
- Vitest.asProp(Vitest.scopedLive, 'failing test (shows initial runs + shrinking)', [IntArbitrary], (properties, ctx, enhanced) => Effect.gen(function* () {
24
- const [value] = properties;
25
- if (value === undefined) {
26
- return yield* Effect.fail(new Error('Value is undefined'));
27
- }
28
- const displayInfo = enhanced._tag === 'initial'
29
- ? `Run ${enhanced.runIndex + 1}/${enhanced.numRuns}`
30
- : `Shrink #${enhanced.shrinkAttempt} (finding minimal counterexample)`;
31
- const status = value > 80 ? '💥' : '✅';
32
- console.log(`${status} FAILING-TEST [${enhanced._tag.toUpperCase()}]: ${displayInfo}, value=${value}, total=${enhanced.totalExecutions}`);
33
- // Fail when value is greater than 80 to trigger shrinking
34
- if (value > 80) {
35
- alreadyFailed = true;
36
- return yield* Effect.fail(new Error(`Value ${value} is too large (> 80)`));
37
- }
38
- if (alreadyFailed && enhanced._tag === 'shrinking') {
39
- ctx.skip("For the sake of this test, we don't want to fail but want to skip");
40
- return;
41
- }
42
- return;
43
- }), { fastCheck: { numRuns: 3 } });
44
- // Test with endOnFailure: true - should not show shrinking
45
- Vitest.asProp(Vitest.scopedLive, 'failing test with endOnFailure (no shrinking)', [IntArbitrary], (properties, _ctx, enhanced) => Effect.gen(function* () {
46
- const [value] = properties;
47
- if (value === undefined) {
48
- return yield* Effect.fail(new Error('Value is undefined'));
49
- }
50
- console.log(`🚫 END-ON-FAILURE [${enhanced._tag.toUpperCase()}]: ` +
51
- `Run ${enhanced.runIndex + 1}/${enhanced.numRuns}, value=${value}, total=${enhanced.totalExecutions}`);
52
- // This will fail but shrinking is disabled
53
- if (value > 50) {
54
- yield* Effect.fail(new Error(`Value ${value} is too large (> 50) - but no shrinking!`));
55
- }
56
- return;
57
- }), { fastCheck: { numRuns: 5, endOnFailure: true }, fails: true });
58
- });
59
- //# sourceMappingURL=Vitest.test.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Vitest.test.js","sourceRoot":"","sources":["../../src/node-vitest/Vitest.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAA;AAC3D,OAAO,KAAK,MAAM,MAAM,aAAa,CA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,+CAA+C,EAC/C,CAAC,YAAY,CAAC,EACd,CAAC,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,CAC7B,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;QAClB,MAAM,CAAC,KAAK,CAAC,GAAG,UAAU,CAAA;QAC1B,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC,CAAA;QAC5D,CAAC;QAED,OAAO,CAAC,GAAG,CACT,sBAAsB,QAAQ,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK;YACpD,OAAO,QAAQ,CAAC,QAAQ,GAAG,CAAC,IAAI,QAAQ,CAAC,OAAO,WAAW,KAAK,WAAW,QAAQ,CAAC,eAAe,EAAE,CACxG,CAAA;QAED,2CAA2C;QAC3C,IAAI,KAAK,GAAG,EAAE,EAAE,CAAC;YACf,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,SAAS,KAAK,0CAA0C,CAAC,CAAC,CAAA;QACzF,CAAC;QAED,OAAM;IACR,CAAC,CAAC,EACJ,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAC/D,CAAA;AACH,CAAC,CAAC,CAAA"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=global.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"global.d.ts","sourceRoot":"","sources":["../../src/node-vitest/global.ts"],"names":[],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"global.js","sourceRoot":"","sources":["../../src/node-vitest/global.ts"],"names":[],"mappings":"AAAA,OAAO,CAAC,MAAM,CAAC,KAAK,GAAG,IAAI,CAAA"}
@@ -1,91 +0,0 @@
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
- })
@@ -1,252 +0,0 @@
1
- import { omitUndefineds } from '@livestore/utils'
2
- import {
3
- Command,
4
- type CommandExecutor,
5
- Duration,
6
- Effect,
7
- type PlatformError,
8
- Schedule,
9
- Schema,
10
- type Scope,
11
- Stream,
12
- } from '@livestore/utils/effect'
13
-
14
- export class DockerComposeError extends Schema.TaggedError<DockerComposeError>()('DockerComposeError', {
15
- cause: Schema.Defect,
16
- message: Schema.String,
17
- }) {}
18
-
19
- export interface DockerComposeArgs {
20
- readonly cwd: string
21
- readonly serviceName?: string
22
- }
23
-
24
- export interface StartOptions {
25
- readonly detached?: boolean
26
- readonly env?: Record<string, string>
27
- readonly healthCheck?: {
28
- readonly url: string
29
- readonly timeout?: Duration.Duration
30
- readonly interval?: Duration.Duration
31
- }
32
- }
33
-
34
- export interface LogsOptions {
35
- readonly follow?: boolean
36
- readonly tail?: number
37
- readonly since?: string
38
- }
39
-
40
- export interface DockerComposeOperations {
41
- readonly pull: Effect.Effect<void, DockerComposeError | PlatformError.PlatformError>
42
- readonly start: (
43
- options?: StartOptions,
44
- ) => Effect.Effect<void, DockerComposeError | PlatformError.PlatformError, Scope.Scope>
45
- readonly stop: Effect.Effect<void, DockerComposeError | PlatformError.PlatformError>
46
- readonly logs: (
47
- options?: LogsOptions,
48
- ) => Stream.Stream<string, DockerComposeError | PlatformError.PlatformError, Scope.Scope>
49
- }
50
-
51
- export class DockerComposeService extends Effect.Service<DockerComposeService>()('DockerComposeService', {
52
- scoped: (args: DockerComposeArgs) =>
53
- Effect.gen(function* () {
54
- const { cwd, serviceName } = args
55
-
56
- const commandExecutorContext = yield* Effect.context<CommandExecutor.CommandExecutor>()
57
-
58
- const pull = Effect.gen(function* () {
59
- yield* Effect.log(`Pulling Docker Compose images in ${cwd}`)
60
-
61
- yield* Command.make('docker', 'compose', 'pull').pipe(
62
- Command.workingDirectory(cwd),
63
- Command.exitCode,
64
- Effect.flatMap((exitCode: number) =>
65
- exitCode === 0
66
- ? Effect.void
67
- : Effect.fail(
68
- new DockerComposeError({
69
- cause: new Error(`Docker compose pull failed with exit code ${exitCode}`),
70
- message: `Docker compose pull failed with exit code ${exitCode}`,
71
- }),
72
- ),
73
- ),
74
- Effect.provide(commandExecutorContext),
75
- )
76
-
77
- yield* Effect.log(`Successfully pulled Docker Compose images`)
78
- }).pipe(Effect.withSpan('pullDockerComposeImages'))
79
-
80
- const start = (options: StartOptions = {}) =>
81
- Effect.gen(function* () {
82
- const { detached = true, healthCheck } = options
83
-
84
- // Build start command
85
- const baseArgs = ['docker', 'compose', 'up']
86
- if (detached) baseArgs.push('-d')
87
- if (serviceName) baseArgs.push(serviceName)
88
-
89
- const command = yield* Command.make(baseArgs[0]!, ...baseArgs.slice(1)).pipe(
90
- Command.workingDirectory(cwd),
91
- Command.env(options.env ?? {}),
92
- Command.start,
93
- Effect.catchAll((cause) =>
94
- Effect.fail(
95
- new DockerComposeError({
96
- cause,
97
- message: `Failed to start Docker Compose services in ${cwd}`,
98
- }),
99
- ),
100
- ),
101
- Effect.provide(commandExecutorContext),
102
- )
103
-
104
- // Wait for command completion
105
- yield* command.exitCode.pipe(
106
- Effect.flatMap((exitCode: number) =>
107
- exitCode === 0
108
- ? Effect.void
109
- : Effect.fail(
110
- new DockerComposeError({
111
- cause: new Error(`Docker compose exited with code ${exitCode}`),
112
- message: `Docker Compose failed to start with exit code ${exitCode}`,
113
- }),
114
- ),
115
- ),
116
- Effect.provide(commandExecutorContext),
117
- )
118
-
119
- // Perform health check if requested
120
- if (healthCheck) {
121
- yield* performHealthCheck(healthCheck).pipe(Effect.provide(commandExecutorContext))
122
- }
123
-
124
- yield* Effect.log(`Docker Compose services started successfully in ${cwd}`)
125
- }).pipe(Effect.withSpan('startDockerCompose'))
126
-
127
- const stop = Effect.gen(function* () {
128
- yield* Effect.log(`Stopping Docker Compose services in ${cwd}`)
129
-
130
- const stopCommand = serviceName
131
- ? Command.make('docker', 'compose', 'stop', serviceName)
132
- : Command.make('docker', 'compose', 'stop')
133
-
134
- yield* stopCommand.pipe(
135
- Command.workingDirectory(cwd),
136
- Command.exitCode,
137
- Effect.flatMap((exitCode: number) =>
138
- exitCode === 0
139
- ? Effect.void
140
- : Effect.fail(
141
- new DockerComposeError({
142
- cause: new Error(`Docker compose stop exited with code ${exitCode}`),
143
- message: `Failed to stop Docker Compose services`,
144
- }),
145
- ),
146
- ),
147
- Effect.provide(commandExecutorContext),
148
- )
149
-
150
- yield* Effect.log(`Docker Compose services stopped successfully`)
151
- }).pipe(Effect.withSpan('stopDockerCompose'))
152
-
153
- const logs = (options: LogsOptions = {}) =>
154
- Effect.gen(function* () {
155
- const { follow = false, tail, since } = options
156
-
157
- const baseArgs = ['docker', 'compose', 'logs']
158
- if (follow) baseArgs.push('-f')
159
- if (tail) baseArgs.push('--tail', tail.toString())
160
- if (since) baseArgs.push('--since', since)
161
- if (serviceName) baseArgs.push(serviceName)
162
-
163
- const command = yield* Command.make(baseArgs[0]!, ...baseArgs.slice(1)).pipe(
164
- Command.workingDirectory(cwd),
165
- Command.start,
166
- Effect.catchAll((cause) =>
167
- Effect.fail(
168
- new DockerComposeError({
169
- cause,
170
- message: `Failed to read Docker Compose logs in ${cwd}`,
171
- }),
172
- ),
173
- ),
174
- Effect.provide(commandExecutorContext),
175
- )
176
-
177
- return command.stdout.pipe(
178
- Stream.decodeText('utf8'),
179
- Stream.splitLines,
180
- Stream.mapError(
181
- (cause) =>
182
- new DockerComposeError({
183
- cause,
184
- message: `Error reading Docker Compose logs in ${cwd}`,
185
- }),
186
- ),
187
- )
188
- }).pipe(Stream.unwrapScoped)
189
-
190
- return { pull, start, stop, logs }
191
- }),
192
- }) {}
193
-
194
- const performHealthCheck = ({
195
- url,
196
- timeout = Duration.minutes(2),
197
- interval = Duration.seconds(2),
198
- }: {
199
- url: string
200
- timeout?: Duration.Duration
201
- interval?: Duration.Duration
202
- }): Effect.Effect<void, DockerComposeError, CommandExecutor.CommandExecutor | Scope.Scope> =>
203
- Effect.gen(function* () {
204
- yield* Effect.log(`Performing health check on ${url}`)
205
-
206
- const checkHealth = Command.make('curl', '-f', '-s', url).pipe(
207
- Command.exitCode,
208
- Effect.map((code: number) => code === 0),
209
- Effect.catchAll(() => Effect.succeed(false)),
210
- )
211
-
212
- const healthCheck = checkHealth.pipe(
213
- Effect.repeat({
214
- while: (healthy: boolean) => !healthy,
215
- schedule: Schedule.fixed(interval),
216
- }),
217
- Effect.timeout(timeout),
218
- Effect.catchAll(() =>
219
- Effect.fail(
220
- new DockerComposeError({
221
- cause: new Error('Health check timeout'),
222
- message: `Health check failed for ${url} after ${Duration.toMillis(timeout)}ms`,
223
- }),
224
- ),
225
- ),
226
- )
227
-
228
- yield* healthCheck
229
- yield* Effect.log(`Health check passed for ${url}`)
230
- })
231
-
232
- // Convenience function for scoped Docker Compose operations with automatic cleanup
233
- export const startDockerComposeServicesScoped = (
234
- args: DockerComposeArgs & {
235
- healthCheck?: StartOptions['healthCheck']
236
- },
237
- ): Effect.Effect<
238
- void,
239
- DockerComposeError | PlatformError.PlatformError,
240
- DockerComposeService | CommandExecutor.CommandExecutor | Scope.Scope
241
- > =>
242
- Effect.gen(function* () {
243
- const dockerCompose = yield* DockerComposeService
244
-
245
- // Start the services
246
- yield* dockerCompose.start({
247
- ...omitUndefineds({ healthCheck: args.healthCheck ? args.healthCheck : undefined }),
248
- })
249
-
250
- // Add cleanup finalizer to the current scope
251
- yield* Effect.addFinalizer(() => dockerCompose.stop.pipe(Effect.orDie))
252
- })
@@ -1,4 +0,0 @@
1
- services:
2
- hello-world:
3
- image: hello-world
4
- profiles: [manual] # Don't auto-start this service
@@ -1,206 +0,0 @@
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
- }