@livestore/utils-dev 0.0.0-snapshot-e5a7caabcf7660aefa55568a44ed0fe306d00597 → 0.0.0-snapshot-9d8807d2c51c95b4df3556744702cea55dc7ded3

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/mod.d.ts +13 -5
  3. package/dist/node/mod.d.ts.map +1 -1
  4. package/dist/node/mod.js +42 -67
  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 +22 -16
  15. package/src/node/mod.ts +82 -81
  16. package/src/node-vitest/mod.ts +1 -3
  17. package/dist/node/DockerComposeService/DockerComposeService.d.ts +0 -58
  18. package/dist/node/DockerComposeService/DockerComposeService.d.ts.map +0 -1
  19. package/dist/node/DockerComposeService/DockerComposeService.js +0 -144
  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/cmd-log.d.ts +0 -21
  30. package/dist/node/cmd-log.d.ts.map +0 -1
  31. package/dist/node/cmd-log.js +0 -50
  32. package/dist/node/cmd-log.js.map +0 -1
  33. package/dist/node/cmd.d.ts +0 -36
  34. package/dist/node/cmd.d.ts.map +0 -1
  35. package/dist/node/cmd.js +0 -234
  36. package/dist/node/cmd.js.map +0 -1
  37. package/dist/node/cmd.test.d.ts +0 -2
  38. package/dist/node/cmd.test.d.ts.map +0 -1
  39. package/dist/node/cmd.test.js +0 -101
  40. package/dist/node/cmd.test.js.map +0 -1
  41. package/dist/node-vitest/Vitest.d.ts +0 -52
  42. package/dist/node-vitest/Vitest.d.ts.map +0 -1
  43. package/dist/node-vitest/Vitest.js +0 -98
  44. package/dist/node-vitest/Vitest.js.map +0 -1
  45. package/dist/node-vitest/Vitest.test.d.ts +0 -2
  46. package/dist/node-vitest/Vitest.test.d.ts.map +0 -1
  47. package/dist/node-vitest/Vitest.test.js +0 -70
  48. package/dist/node-vitest/Vitest.test.js.map +0 -1
  49. package/dist/node-vitest/global.d.ts +0 -2
  50. package/dist/node-vitest/global.d.ts.map +0 -1
  51. package/dist/node-vitest/global.js.map +0 -1
  52. package/dist/wrangler/WranglerDevServer.d.ts +0 -52
  53. package/dist/wrangler/WranglerDevServer.d.ts.map +0 -1
  54. package/dist/wrangler/WranglerDevServer.js +0 -90
  55. package/dist/wrangler/WranglerDevServer.js.map +0 -1
  56. package/dist/wrangler/WranglerDevServer.test.d.ts +0 -2
  57. package/dist/wrangler/WranglerDevServer.test.d.ts.map +0 -1
  58. package/dist/wrangler/WranglerDevServer.test.js +0 -77
  59. package/dist/wrangler/WranglerDevServer.test.js.map +0 -1
  60. package/dist/wrangler/fixtures/cf-worker.d.ts +0 -8
  61. package/dist/wrangler/fixtures/cf-worker.d.ts.map +0 -1
  62. package/dist/wrangler/fixtures/cf-worker.js +0 -11
  63. package/dist/wrangler/fixtures/cf-worker.js.map +0 -1
  64. package/dist/wrangler/mod.d.ts +0 -2
  65. package/dist/wrangler/mod.d.ts.map +0 -1
  66. package/dist/wrangler/mod.js +0 -2
  67. package/dist/wrangler/mod.js.map +0 -1
  68. package/src/node/DockerComposeService/DockerComposeService.test.ts +0 -91
  69. package/src/node/DockerComposeService/DockerComposeService.ts +0 -328
  70. package/src/node/DockerComposeService/test-fixtures/docker-compose.yml +0 -4
  71. package/src/node/FileLogger.ts +0 -206
  72. package/src/node/cmd-log.ts +0 -92
  73. package/src/node/cmd.test.ts +0 -129
  74. package/src/node/cmd.ts +0 -419
  75. package/src/node-vitest/Vitest.test.ts +0 -112
  76. package/src/node-vitest/Vitest.ts +0 -238
  77. package/src/wrangler/WranglerDevServer.test.ts +0 -133
  78. package/src/wrangler/WranglerDevServer.ts +0 -180
  79. package/src/wrangler/fixtures/cf-worker.ts +0 -11
  80. package/src/wrangler/fixtures/wrangler.toml +0 -11
  81. package/src/wrangler/mod.ts +0 -6
  82. /package/src/node-vitest/{global.ts → polyfill.ts} +0 -0
@@ -1,328 +0,0 @@
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
- })
@@ -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
- }
@@ -1,92 +0,0 @@
1
- import fs from 'node:fs'
2
- import path from 'node:path'
3
-
4
- import { isNotUndefined } from '@livestore/utils'
5
- import { Effect, identity } from '@livestore/utils/effect'
6
-
7
- export type TCmdLoggingOptions = {
8
- readonly logDir?: string
9
- readonly logFileName?: string
10
- readonly logRetention?: number
11
- }
12
-
13
- /**
14
- * Prepares logging directories, archives previous canonical log and prunes archives.
15
- * Returns the canonical current log path if logging is enabled, otherwise undefined.
16
- */
17
- export const prepareCmdLogging: (options: TCmdLoggingOptions) => Effect.Effect<string | undefined, never, never> =
18
- Effect.fn('cmd.logging.prepare')(function* ({
19
- logDir,
20
- logFileName = 'dev.log',
21
- logRetention = 50,
22
- }: TCmdLoggingOptions) {
23
- if (!logDir || logDir === '') return undefined as string | undefined
24
-
25
- const logsDir = logDir
26
- const archiveDir = path.join(logsDir, 'archive')
27
- const currentLogPath = path.join(logsDir, logFileName)
28
-
29
- // Ensure directories exist
30
- yield* Effect.sync(() => fs.mkdirSync(archiveDir, { recursive: true }))
31
-
32
- // Archive previous log if present
33
- if (fs.existsSync(currentLogPath)) {
34
- const safeIso = new Date().toISOString().replaceAll(':', '-')
35
- const archivedBase = `${path.parse(logFileName).name}-${safeIso}.log`
36
- const archivedLog = path.join(archiveDir, archivedBase)
37
- yield* Effect.try({ try: () => fs.renameSync(currentLogPath, archivedLog), catch: identity }).pipe(
38
- Effect.catchAll(() =>
39
- Effect.try({
40
- try: () => {
41
- fs.copyFileSync(currentLogPath, archivedLog)
42
- fs.truncateSync(currentLogPath, 0)
43
- },
44
- catch: identity,
45
- }),
46
- ),
47
- Effect.ignore,
48
- )
49
-
50
- // Prune archives to retain only the newest N
51
- yield* Effect.try({ try: () => fs.readdirSync(archiveDir), catch: identity }).pipe(
52
- Effect.map((names) => names.filter((n) => n.endsWith('.log'))),
53
- Effect.map((names) =>
54
- names
55
- .map((name) => ({ name, mtimeMs: fs.statSync(path.join(archiveDir, name)).mtimeMs }))
56
- .sort((a, b) => b.mtimeMs - a.mtimeMs),
57
- ),
58
- Effect.flatMap((entries) =>
59
- Effect.forEach(entries.slice(logRetention), (e) =>
60
- Effect.try({ try: () => fs.unlinkSync(path.join(archiveDir, e.name)), catch: identity }).pipe(
61
- Effect.ignore,
62
- ),
63
- ),
64
- ),
65
- Effect.ignore,
66
- )
67
- }
68
-
69
- return currentLogPath
70
- })
71
-
72
- /**
73
- * Given a command input, applies logging by piping output through `tee` to the
74
- * canonical log file. Returns the transformed input and whether a shell is required.
75
- */
76
- export const applyLoggingToCommand: (
77
- commandInput: string | (string | undefined)[],
78
- options: TCmdLoggingOptions,
79
- ) => Effect.Effect<{ input: string | string[]; subshell: boolean; logPath?: string }, never, never> = Effect.fn(
80
- 'cmd.logging.apply',
81
- )(function* (commandInput, options) {
82
- const asArray = Array.isArray(commandInput)
83
- const parts = asArray ? (commandInput as (string | undefined)[]).filter(isNotUndefined) : undefined
84
-
85
- const logPath = yield* prepareCmdLogging(options)
86
-
87
- return {
88
- input: asArray ? ((parts as string[]) ?? []) : (commandInput as string),
89
- subshell: false,
90
- ...(logPath ? { logPath } : {}),
91
- }
92
- })