@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,263 +0,0 @@
1
- import { Command, type CommandExecutor, Effect, Schema, type Scope, Stream } from '@livestore/utils/effect'
2
-
3
- export class ProcessTreeError extends Schema.TaggedError<ProcessTreeError>()('ProcessTreeError', {
4
- cause: Schema.Unknown,
5
- message: Schema.String,
6
- pid: Schema.Number,
7
- }) {}
8
-
9
- /**
10
- * Finds all child processes of a given parent PID
11
- */
12
- export const findChildProcesses = (
13
- parentPid: number,
14
- ): Effect.Effect<number[], never, CommandExecutor.CommandExecutor | Scope.Scope> =>
15
- Effect.gen(function* () {
16
- const result = yield* Command.make('ps', '-o', 'pid,ppid', '-ax').pipe(
17
- Command.start,
18
- Effect.flatMap((command) =>
19
- command.stdout.pipe(
20
- Stream.decodeText('utf8'),
21
- Stream.runCollect,
22
- Effect.map((chunks) => Array.from(chunks).join('')),
23
- ),
24
- ),
25
- Effect.catchAll(() => Effect.succeed('')), // Return empty string if command fails
26
- )
27
-
28
- if (!result) return []
29
-
30
- const lines = result.split('\n')
31
- const pattern = new RegExp(`^\\s*([0-9]+)\\s+${parentPid}\\s*$`)
32
-
33
- const childPids = lines
34
- .map((line) => {
35
- const match = line.trim().match(pattern)
36
- return match ? Number.parseInt(match[1]!, 10) : null
37
- })
38
- .filter((pid): pid is number => pid !== null)
39
-
40
- return childPids
41
- })
42
-
43
- /**
44
- * Recursively finds all descendants of a process
45
- */
46
- export const findProcessTree = (
47
- rootPid: number,
48
- ): Effect.Effect<number[], never, CommandExecutor.CommandExecutor | Scope.Scope> =>
49
- Effect.gen(function* () {
50
- const allPids = new Set<number>([rootPid])
51
- const toProcess = [rootPid]
52
-
53
- while (toProcess.length > 0) {
54
- const currentPid = toProcess.pop()!
55
- const children = yield* findChildProcesses(currentPid)
56
-
57
- for (const childPid of children) {
58
- if (!allPids.has(childPid)) {
59
- allPids.add(childPid)
60
- toProcess.push(childPid)
61
- }
62
- }
63
- }
64
-
65
- return Array.from(allPids)
66
- })
67
-
68
- /**
69
- * Checks if a process is running
70
- */
71
- export const isProcessRunning = (pid: number): Effect.Effect<boolean, never, never> =>
72
- Effect.sync(() => {
73
- try {
74
- process.kill(pid, 0)
75
- return true
76
- } catch {
77
- return false
78
- }
79
- })
80
-
81
- /**
82
- * Kills a process tree with escalating signals
83
- */
84
- export const killProcessTree = (
85
- rootPid: number,
86
- options: {
87
- timeout?: number
88
- signals?: NodeJS.Signals[]
89
- includeRoot?: boolean
90
- } = {},
91
- ): Effect.Effect<
92
- { killedPids: number[]; failedPids: number[] },
93
- never,
94
- CommandExecutor.CommandExecutor | Scope.Scope
95
- > =>
96
- Effect.gen(function* () {
97
- const { timeout = 5000, signals = ['SIGTERM', 'SIGKILL'], includeRoot = true } = options
98
-
99
- // Find all processes in the tree
100
- const allPids = yield* findProcessTree(rootPid)
101
- const pidsToKill = includeRoot ? allPids : allPids.filter((pid) => pid !== rootPid)
102
-
103
- if (pidsToKill.length === 0) {
104
- return { killedPids: [], failedPids: [] }
105
- }
106
-
107
- const killedPids: number[] = []
108
- const failedPids: number[] = []
109
-
110
- // Try each signal with timeout
111
- for (const signal of signals) {
112
- // Check which processes are still running and not yet killed
113
- const stillRunningChecks = yield* Effect.all(
114
- pidsToKill
115
- .filter((pid) => !killedPids.includes(pid))
116
- .map((pid) => isProcessRunning(pid).pipe(Effect.map((running) => ({ pid, running })))),
117
- )
118
- const remainingPids = stillRunningChecks.filter(({ running }) => running).map(({ pid }) => pid)
119
-
120
- if (remainingPids.length === 0) break
121
-
122
- // Send signal to all remaining processes
123
- for (const pid of remainingPids) {
124
- yield* Effect.sync(() => {
125
- try {
126
- process.kill(pid, signal)
127
- } catch {
128
- // Process might already be dead, continue
129
- }
130
- })
131
- }
132
-
133
- // Wait for processes to terminate with polling
134
- const waitStart = Date.now()
135
- while (Date.now() - waitStart < timeout) {
136
- const runningChecks = yield* Effect.all(
137
- remainingPids.map((pid) => isProcessRunning(pid).pipe(Effect.map((running) => ({ pid, running })))),
138
- )
139
- const stillRunning = runningChecks.filter(({ running }) => running).map(({ pid }) => pid)
140
-
141
- if (stillRunning.length === 0) {
142
- // All processes terminated
143
- killedPids.push(...remainingPids)
144
- break
145
- }
146
-
147
- // Short sleep before checking again
148
- yield* Effect.sleep('100 millis')
149
- }
150
- }
151
-
152
- // Check final status
153
- const finalChecks = yield* Effect.all(
154
- pidsToKill.map((pid) => isProcessRunning(pid).pipe(Effect.map((running) => ({ pid, running })))),
155
- )
156
-
157
- for (const { pid, running } of finalChecks) {
158
- if (!killedPids.includes(pid) && running) {
159
- failedPids.push(pid)
160
- }
161
- }
162
-
163
- return { killedPids, failedPids }
164
- })
165
-
166
- /**
167
- * Finds orphaned processes by name pattern
168
- */
169
- export const findOrphanedProcesses = (
170
- namePattern: string,
171
- ): Effect.Effect<number[], never, CommandExecutor.CommandExecutor | Scope.Scope> =>
172
- Effect.gen(function* () {
173
- // Find processes that match the pattern and have init (PID 1) as parent
174
- const result = yield* Command.make('ps', '-eo', 'pid,ppid,comm').pipe(
175
- Command.start,
176
- Effect.flatMap((command) =>
177
- command.stdout.pipe(
178
- Stream.decodeText('utf8'),
179
- Stream.runCollect,
180
- Effect.map((chunks) => Array.from(chunks).join('')),
181
- ),
182
- ),
183
- Effect.catchAll(() => Effect.succeed('')), // Return empty string if command fails
184
- )
185
-
186
- if (!result) return []
187
-
188
- const lines = result.split('\n')
189
- const patternRegex = new RegExp(namePattern)
190
- const parentRegex = /^\s*(\d+)\s+1\s+/
191
-
192
- const orphanedPids = lines
193
- .filter((line) => patternRegex.test(line))
194
- .map((line) => {
195
- const match = line.trim().match(parentRegex)
196
- return match ? Number.parseInt(match[1]!, 10) : null
197
- })
198
- .filter((pid): pid is number => pid !== null)
199
-
200
- return orphanedPids
201
- })
202
-
203
- /**
204
- * Defensive cleanup for orphaned processes matching given patterns.
205
- *
206
- * This function provides fallback cleanup for edge cases where normal process
207
- * termination mechanisms fail (e.g., hard crashes, SIGKILL before cleanup runs,
208
- * or limitations in synchronous exit handlers). While proper process tree cleanup
209
- * should prevent orphans in most cases, this serves as a safety net for scenarios
210
- * where child processes become orphaned despite cleanup efforts.
211
- *
212
- * @param processPatterns - Array of process name patterns to search for (e.g., ['wrangler', 'workerd'])
213
- * @returns Object with arrays of successfully cleaned and failed PIDs
214
- */
215
- export const cleanupOrphanedProcesses = (
216
- processPatterns: string[],
217
- ): Effect.Effect<{ cleaned: number[]; failed: number[] }, never, CommandExecutor.CommandExecutor | Scope.Scope> =>
218
- Effect.gen(function* () {
219
- const cleaned: number[] = []
220
- const failed: number[] = []
221
-
222
- // Find all orphaned processes matching the patterns
223
- const allOrphanedPids: number[] = []
224
- const patternCounts: Record<string, number> = {}
225
-
226
- for (const pattern of processPatterns) {
227
- const orphaned = yield* findOrphanedProcesses(pattern)
228
- allOrphanedPids.push(...orphaned)
229
- patternCounts[pattern] = orphaned.length
230
- }
231
-
232
- if (allOrphanedPids.length === 0) {
233
- return { cleaned, failed }
234
- }
235
-
236
- const patternSummary = Object.entries(patternCounts)
237
- .map(([pattern, count]) => `${count} ${pattern}`)
238
- .join(', ')
239
-
240
- yield* Effect.logInfo(
241
- `Found ${allOrphanedPids.length} orphaned processes (${patternSummary}): ${allOrphanedPids.join(', ')}`,
242
- )
243
-
244
- for (const pid of allOrphanedPids) {
245
- const result = yield* killProcessTree(pid, {
246
- timeout: 2000,
247
- signals: ['SIGTERM', 'SIGKILL'],
248
- includeRoot: true,
249
- }).pipe(Effect.orElse(() => Effect.succeed({ killedPids: [], failedPids: [pid] })))
250
-
251
- if (result.failedPids.length === 0) {
252
- cleaned.push(...result.killedPids)
253
- yield* Effect.logInfo(
254
- `Cleaned up orphaned process tree starting with ${pid} (${result.killedPids.length} processes)`,
255
- )
256
- } else {
257
- failed.push(pid, ...result.failedPids)
258
- yield* Effect.logWarning(`Failed to clean up some processes in tree ${pid}: ${result.failedPids.join(', ')}`)
259
- }
260
- }
261
-
262
- return { cleaned, failed }
263
- })
package/src/node/cmd.ts DELETED
@@ -1,99 +0,0 @@
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
- }) {}
@@ -1,101 +0,0 @@
1
- import { Effect, FastCheck } from '@livestore/utils/effect'
2
- import * as Vitest from './Vitest.ts'
3
-
4
- // Demonstrate enhanced asProp functionality with clear shrinking progress
5
- // This showcases the fix for the "Run 26/6" bug and accurate shrinking detection
6
-
7
- Vitest.describe('Vitest.asProp', () => {
8
- const IntArbitrary = FastCheck.integer({ min: 1, max: 100 })
9
-
10
- // Always-passing test - should only show initial phase
11
- Vitest.asProp(
12
- Vitest.scopedLive,
13
- 'always-pass test (shows only initial runs)',
14
- [IntArbitrary],
15
- (properties, _ctx, enhanced) =>
16
- Effect.gen(function* () {
17
- const [value] = properties
18
- if (value === undefined) {
19
- return yield* Effect.fail(new Error('Value is undefined'))
20
- }
21
-
22
- console.log(
23
- `✅ ALWAYS-PASS [${enhanced._tag.toUpperCase()}]: ` +
24
- (enhanced._tag === 'initial'
25
- ? `Run ${enhanced.runIndex + 1}/${enhanced.numRuns}`
26
- : `Shrink #${enhanced.shrinkAttempt} (finding minimal counterexample)`) +
27
- `, value=${value}, total=${enhanced.totalExecutions}`,
28
- )
29
-
30
- // This test always passes, so no shrinking will occur
31
- return
32
- }),
33
- { fastCheck: { numRuns: 4 } },
34
- )
35
-
36
- // Failing test - should show initial + shrinking phases
37
- let alreadyFailed = false
38
- Vitest.asProp(
39
- Vitest.scopedLive,
40
- 'failing test (shows initial runs + shrinking)',
41
- [IntArbitrary],
42
- (properties, ctx, enhanced) =>
43
- Effect.gen(function* () {
44
- const [value] = properties
45
- if (value === undefined) {
46
- return yield* Effect.fail(new Error('Value is undefined'))
47
- }
48
-
49
- const displayInfo =
50
- enhanced._tag === 'initial'
51
- ? `Run ${enhanced.runIndex + 1}/${enhanced.numRuns}`
52
- : `Shrink #${enhanced.shrinkAttempt} (finding minimal counterexample)`
53
-
54
- const status = value > 80 ? '💥' : '✅'
55
- console.log(
56
- `${status} FAILING-TEST [${enhanced._tag.toUpperCase()}]: ${displayInfo}, value=${value}, total=${enhanced.totalExecutions}`,
57
- )
58
-
59
- // Fail when value is greater than 80 to trigger shrinking
60
- if (value > 80) {
61
- alreadyFailed = true
62
- return yield* Effect.fail(new Error(`Value ${value} is too large (> 80)`))
63
- }
64
-
65
- if (alreadyFailed && enhanced._tag === 'shrinking') {
66
- ctx.skip("For the sake of this test, we don't want to fail but want to skip")
67
- return
68
- }
69
-
70
- return
71
- }),
72
- { fastCheck: { numRuns: 3 } },
73
- )
74
-
75
- // Test with endOnFailure: true - should not show shrinking
76
- Vitest.asProp(
77
- Vitest.scopedLive,
78
- 'failing test with endOnFailure (no shrinking)',
79
- [IntArbitrary],
80
- (properties, _ctx, enhanced) =>
81
- Effect.gen(function* () {
82
- const [value] = properties
83
- if (value === undefined) {
84
- return yield* Effect.fail(new Error('Value is undefined'))
85
- }
86
-
87
- console.log(
88
- `🚫 END-ON-FAILURE [${enhanced._tag.toUpperCase()}]: ` +
89
- `Run ${enhanced.runIndex + 1}/${enhanced.numRuns}, value=${value}, total=${enhanced.totalExecutions}`,
90
- )
91
-
92
- // This will fail but shrinking is disabled
93
- if (value > 50) {
94
- yield* Effect.fail(new Error(`Value ${value} is too large (> 50) - but no shrinking!`))
95
- }
96
-
97
- return
98
- }),
99
- { fastCheck: { numRuns: 5, endOnFailure: true }, fails: true },
100
- )
101
- })
@@ -1,221 +0,0 @@
1
- import * as inspector from 'node:inspector'
2
- import type * as Vitest from '@effect/vitest'
3
- import { IS_CI } from '@livestore/utils'
4
- import {
5
- type Cause,
6
- Duration,
7
- Effect,
8
- type FastCheck as FC,
9
- identity,
10
- Layer,
11
- type OtelTracer,
12
- Predicate,
13
- type Schema,
14
- type Scope,
15
- } from '@livestore/utils/effect'
16
- import { OtelLiveDummy } from '@livestore/utils/node'
17
- import { OtelLiveHttp } from '../node/mod.ts'
18
-
19
- export * from '@effect/vitest'
20
-
21
- export const DEBUGGER_ACTIVE = Boolean(process.env.DEBUGGER_ACTIVE ?? inspector.url() !== undefined)
22
-
23
- export const makeWithTestCtx =
24
- <R1 = never, E1 = never>(ctxParams: WithTestCtxParams<R1, E1>) =>
25
- (testContext: Vitest.TestContext) =>
26
- withTestCtx(testContext, ctxParams)
27
-
28
- export type WithTestCtxParams<R1 = never, E1 = never> = {
29
- suffix?: string
30
- makeLayer?: (testContext: Vitest.TestContext) => Layer.Layer<R1, E1, Scope.Scope>
31
- timeout?: Duration.DurationInput
32
- forceOtel?: boolean
33
- }
34
-
35
- export const withTestCtx =
36
- <R1 = never, E1 = never>(
37
- testContext: Vitest.TestContext,
38
- {
39
- suffix,
40
- makeLayer,
41
- timeout = IS_CI ? 60_000 : 10_000,
42
- forceOtel = false,
43
- }: {
44
- suffix?: string
45
- makeLayer?: (testContext: Vitest.TestContext) => Layer.Layer<R1, E1, Scope.Scope>
46
- timeout?: Duration.DurationInput
47
- forceOtel?: boolean
48
- } = {},
49
- ) =>
50
- <A, E>(
51
- self: Effect.Effect<A, E, Scope.Scope | OtelTracer.OtelTracer | R1>,
52
- ): Effect.Effect<A, E | Cause.TimeoutException | E1, Scope.Scope> => {
53
- const spanName = `${testContext.task.suite?.name}:${testContext.task.name}${suffix ? `:${suffix}` : ''}`
54
- const layer = makeLayer?.(testContext)
55
-
56
- const otelLayer =
57
- DEBUGGER_ACTIVE || forceOtel
58
- ? OtelLiveHttp({ rootSpanName: spanName, serviceName: 'vitest-runner', skipLogUrl: false })
59
- : OtelLiveDummy
60
-
61
- const combinedLayer = (layer ?? Layer.empty).pipe(Layer.provideMerge(otelLayer))
62
-
63
- return self.pipe(
64
- DEBUGGER_ACTIVE
65
- ? identity
66
- : Effect.logWarnIfTakesLongerThan({
67
- duration: Duration.toMillis(timeout) * 0.8,
68
- label: `${spanName} approaching timeout (timeout: ${Duration.format(timeout)})`,
69
- }),
70
- DEBUGGER_ACTIVE ? identity : Effect.timeout(timeout),
71
- Effect.provide(combinedLayer),
72
- Effect.scoped, // We need to scope the effect manually here because otherwise the span is not closed
73
- Effect.annotateLogs({ suffix }),
74
- ) as any
75
- }
76
-
77
- /**
78
- * Shared properties for all enhanced test context phases
79
- */
80
- export interface EnhancedTestContextBase {
81
- numRuns: number
82
- /** 0-based index */
83
- runIndex: number
84
- /** Total number of executions including initial runs and shrinking attempts */
85
- totalExecutions: number
86
- }
87
-
88
- /**
89
- * Enhanced context for property-based tests that includes shrinking phase information
90
- */
91
- export type EnhancedTestContext =
92
- | (EnhancedTestContextBase & {
93
- _tag: 'initial'
94
- })
95
- | (EnhancedTestContextBase & {
96
- _tag: 'shrinking'
97
- /** Number of shrinking attempts */
98
- shrinkAttempt: number
99
- })
100
-
101
- /**
102
- * Normalizes propOptions to ensure @effect/vitest receives correct fastCheck structure
103
- */
104
- const normalizePropOptions = <Arbs extends Vitest.Vitest.Arbitraries>(
105
- propOptions:
106
- | number
107
- | (Vitest.TestOptions & {
108
- fastCheck?: FC.Parameters<{
109
- [K in keyof Arbs]: Arbs[K] extends FC.Arbitrary<infer T> ? T : Schema.Schema.Type<Arbs[K]>
110
- }>
111
- }),
112
- ): Vitest.TestOptions & {
113
- fastCheck?: FC.Parameters<{
114
- [K in keyof Arbs]: Arbs[K] extends FC.Arbitrary<infer T> ? T : Schema.Schema.Type<Arbs[K]>
115
- }>
116
- } => {
117
- // If it's a number, treat as timeout and add our default fastCheck
118
- if (!Predicate.isObject(propOptions)) {
119
- return {
120
- timeout: propOptions,
121
- fastCheck: { numRuns: 100 },
122
- }
123
- }
124
-
125
- // If no fastCheck property, add it with our default numRuns
126
- if (!propOptions.fastCheck) {
127
- return {
128
- ...propOptions,
129
- fastCheck: { numRuns: 100 },
130
- }
131
- }
132
-
133
- // If fastCheck exists but no numRuns, add our default
134
- if (propOptions.fastCheck && !propOptions.fastCheck.numRuns) {
135
- return {
136
- ...propOptions,
137
- fastCheck: {
138
- ...propOptions.fastCheck,
139
- numRuns: 100,
140
- },
141
- }
142
- }
143
-
144
- // If everything is properly structured, pass through
145
- return propOptions
146
- }
147
-
148
- /**
149
- * Equivalent to Vitest.prop but provides enhanced context including shrinking progress visibility
150
- *
151
- * This function enhances the standard property-based testing by providing clear information about
152
- * whether FastCheck is in the initial testing phase or the shrinking phase, solving the confusion
153
- * where tests show "Run 26/6" when FastCheck's shrinking algorithm is active.
154
- *
155
- * TODO: allow for upper timelimit instead of / additional to `numRuns`
156
- *
157
- * TODO: Upstream to Effect
158
- */
159
- export const asProp = <Arbs extends Vitest.Vitest.Arbitraries, A, E, R>(
160
- api: Vitest.Vitest.Tester<R>,
161
- name: string,
162
- arbitraries: Arbs,
163
- test: Vitest.Vitest.TestFunction<
164
- A,
165
- E,
166
- R,
167
- [
168
- { [K in keyof Arbs]: Arbs[K] extends FC.Arbitrary<infer T> ? T : Schema.Schema.Type<Arbs[K]> },
169
- Vitest.TestContext,
170
- EnhancedTestContext,
171
- ]
172
- >,
173
- propOptions:
174
- | number
175
- | (Vitest.TestOptions & {
176
- fastCheck?: FC.Parameters<{
177
- [K in keyof Arbs]: Arbs[K] extends FC.Arbitrary<infer T> ? T : Schema.Schema.Type<Arbs[K]>
178
- }>
179
- }),
180
- ) => {
181
- const normalizedPropOptions = normalizePropOptions(propOptions)
182
- const numRuns = normalizedPropOptions.fastCheck?.numRuns ?? 100
183
- let runIndex = 0
184
- let shrinkAttempts = 0
185
- let totalExecutions = 0
186
-
187
- return api.prop(
188
- name,
189
- arbitraries,
190
- (properties, ctx) => {
191
- if (ctx.signal.aborted) {
192
- return ctx.skip('Test aborted')
193
- }
194
-
195
- totalExecutions++
196
- const isInShrinkingPhase = runIndex >= numRuns
197
-
198
- if (isInShrinkingPhase) {
199
- shrinkAttempts++
200
- }
201
-
202
- const enhancedContext: EnhancedTestContext = isInShrinkingPhase
203
- ? {
204
- _tag: 'shrinking',
205
- numRuns,
206
- runIndex: runIndex++,
207
- shrinkAttempt: shrinkAttempts,
208
- totalExecutions,
209
- }
210
- : {
211
- _tag: 'initial',
212
- numRuns,
213
- runIndex: runIndex++,
214
- totalExecutions,
215
- }
216
-
217
- return test(properties, ctx, enhancedContext)
218
- },
219
- normalizedPropOptions,
220
- )
221
- }
File without changes