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

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 (52) hide show
  1. package/dist/.tsbuildinfo.json +1 -1
  2. package/dist/node/DockerComposeService/DockerComposeService.d.ts +48 -0
  3. package/dist/node/DockerComposeService/DockerComposeService.d.ts.map +1 -0
  4. package/dist/node/DockerComposeService/DockerComposeService.js +107 -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/WranglerDevServer/WranglerDevServer.d.ts +52 -0
  11. package/dist/node/WranglerDevServer/WranglerDevServer.d.ts.map +1 -0
  12. package/dist/node/WranglerDevServer/WranglerDevServer.js +122 -0
  13. package/dist/node/WranglerDevServer/WranglerDevServer.js.map +1 -0
  14. package/dist/node/WranglerDevServer/WranglerDevServer.test.d.ts +2 -0
  15. package/dist/node/WranglerDevServer/WranglerDevServer.test.d.ts.map +1 -0
  16. package/dist/node/WranglerDevServer/WranglerDevServer.test.js +179 -0
  17. package/dist/node/WranglerDevServer/WranglerDevServer.test.js.map +1 -0
  18. package/dist/node/WranglerDevServer/fixtures/cf-worker.d.ts +8 -0
  19. package/dist/node/WranglerDevServer/fixtures/cf-worker.d.ts.map +1 -0
  20. package/dist/node/WranglerDevServer/fixtures/cf-worker.js +11 -0
  21. package/dist/node/WranglerDevServer/fixtures/cf-worker.js.map +1 -0
  22. package/dist/node/WranglerDevServer/process-tree-manager.d.ts +55 -0
  23. package/dist/node/WranglerDevServer/process-tree-manager.d.ts.map +1 -0
  24. package/dist/node/WranglerDevServer/process-tree-manager.js +178 -0
  25. package/dist/node/WranglerDevServer/process-tree-manager.js.map +1 -0
  26. package/dist/node/mod.d.ts +3 -2
  27. package/dist/node/mod.d.ts.map +1 -1
  28. package/dist/node/mod.js +3 -2
  29. package/dist/node/mod.js.map +1 -1
  30. package/dist/node/vitest-docker-compose-setup.d.ts +1 -1
  31. package/dist/node-vitest/Vitest.d.ts +37 -3
  32. package/dist/node-vitest/Vitest.d.ts.map +1 -1
  33. package/dist/node-vitest/Vitest.js +75 -1
  34. package/dist/node-vitest/Vitest.js.map +1 -1
  35. package/dist/node-vitest/Vitest.test.d.ts +2 -0
  36. package/dist/node-vitest/Vitest.test.d.ts.map +1 -0
  37. package/dist/node-vitest/Vitest.test.js +59 -0
  38. package/dist/node-vitest/Vitest.test.js.map +1 -0
  39. package/package.json +5 -7
  40. package/src/node/DockerComposeService/DockerComposeService.test.ts +91 -0
  41. package/src/node/DockerComposeService/DockerComposeService.ts +252 -0
  42. package/src/node/DockerComposeService/test-fixtures/docker-compose.yml +4 -0
  43. package/src/node/WranglerDevServer/WranglerDevServer.test.ts +266 -0
  44. package/src/node/WranglerDevServer/WranglerDevServer.ts +266 -0
  45. package/src/node/WranglerDevServer/fixtures/cf-worker.ts +11 -0
  46. package/src/node/WranglerDevServer/fixtures/wrangler.toml +11 -0
  47. package/src/node/WranglerDevServer/process-tree-manager.ts +263 -0
  48. package/src/node/mod.ts +16 -2
  49. package/src/node-vitest/Vitest.test.ts +101 -0
  50. package/src/node-vitest/Vitest.ts +167 -5
  51. package/src/node/vitest-docker-compose-setup.ts +0 -182
  52. package/src/node/vitest-wrangler-setup.ts +0 -132
@@ -1,7 +1,18 @@
1
1
  import * as inspector from 'node:inspector'
2
2
  import type * as Vitest from '@effect/vitest'
3
3
  import { IS_CI } from '@livestore/utils'
4
- import { type Cause, Duration, Effect, identity, Layer, type OtelTracer, type Scope } from '@livestore/utils/effect'
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'
5
16
  import { OtelLiveDummy } from '@livestore/utils/node'
6
17
  import { OtelLiveHttp } from '../node/mod.ts'
7
18
 
@@ -9,12 +20,17 @@ export * from '@effect/vitest'
9
20
 
10
21
  export const DEBUGGER_ACTIVE = Boolean(process.env.DEBUGGER_ACTIVE ?? inspector.url() !== undefined)
11
22
 
12
- export const makeWithTestCtx =
13
- <R1 = never, E1 = never>(ctxParams: WithTestCtxParams<R1, E1>) =>
14
- (testContext: Vitest.TestContext) =>
23
+ export const makeWithTestCtx: <R1, E1>(
24
+ ctxParams: WithTestCtxParams<R1, E1>,
25
+ ) => (
26
+ testContext: Vitest.TestContext,
27
+ ) => <A, E>(
28
+ self: Effect.Effect<A, E, Scope.Scope | NoInfer<R1> | OtelTracer.OtelTracer>,
29
+ ) => Effect.Effect<A, E1 | Cause.TimeoutException | E, Scope.Scope> =
30
+ (ctxParams) => (testContext: Vitest.TestContext) =>
15
31
  withTestCtx(testContext, ctxParams)
16
32
 
17
- export type WithTestCtxParams<R1 = never, E1 = never> = {
33
+ export type WithTestCtxParams<R1, E1> = {
18
34
  suffix?: string
19
35
  makeLayer?: (testContext: Vitest.TestContext) => Layer.Layer<R1, E1, Scope.Scope>
20
36
  timeout?: Duration.DurationInput
@@ -62,3 +78,149 @@ export const withTestCtx =
62
78
  Effect.annotateLogs({ suffix }),
63
79
  ) as any
64
80
  }
81
+
82
+ /**
83
+ * Shared properties for all enhanced test context phases
84
+ */
85
+ export interface EnhancedTestContextBase {
86
+ numRuns: number
87
+ /** 0-based index */
88
+ runIndex: number
89
+ /** Total number of executions including initial runs and shrinking attempts */
90
+ totalExecutions: number
91
+ }
92
+
93
+ /**
94
+ * Enhanced context for property-based tests that includes shrinking phase information
95
+ */
96
+ export type EnhancedTestContext =
97
+ | (EnhancedTestContextBase & {
98
+ _tag: 'initial'
99
+ })
100
+ | (EnhancedTestContextBase & {
101
+ _tag: 'shrinking'
102
+ /** Number of shrinking attempts */
103
+ shrinkAttempt: number
104
+ })
105
+
106
+ /**
107
+ * Normalizes propOptions to ensure @effect/vitest receives correct fastCheck structure
108
+ */
109
+ const normalizePropOptions = <Arbs extends Vitest.Vitest.Arbitraries>(
110
+ propOptions:
111
+ | number
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
+ ): Vitest.TestOptions & {
118
+ fastCheck?: FC.Parameters<{
119
+ [K in keyof Arbs]: Arbs[K] extends FC.Arbitrary<infer T> ? T : Schema.Schema.Type<Arbs[K]>
120
+ }>
121
+ } => {
122
+ // If it's a number, treat as timeout and add our default fastCheck
123
+ if (!Predicate.isObject(propOptions)) {
124
+ return {
125
+ timeout: propOptions,
126
+ fastCheck: { numRuns: 100 },
127
+ }
128
+ }
129
+
130
+ // If no fastCheck property, add it with our default numRuns
131
+ if (!propOptions.fastCheck) {
132
+ return {
133
+ ...propOptions,
134
+ fastCheck: { numRuns: 100 },
135
+ }
136
+ }
137
+
138
+ // If fastCheck exists but no numRuns, add our default
139
+ if (propOptions.fastCheck && !propOptions.fastCheck.numRuns) {
140
+ return {
141
+ ...propOptions,
142
+ fastCheck: {
143
+ ...propOptions.fastCheck,
144
+ numRuns: 100,
145
+ },
146
+ }
147
+ }
148
+
149
+ // If everything is properly structured, pass through
150
+ return propOptions
151
+ }
152
+
153
+ /**
154
+ * Equivalent to Vitest.prop but provides enhanced context including shrinking progress visibility
155
+ *
156
+ * This function enhances the standard property-based testing by providing clear information about
157
+ * whether FastCheck is in the initial testing phase or the shrinking phase, solving the confusion
158
+ * where tests show "Run 26/6" when FastCheck's shrinking algorithm is active.
159
+ *
160
+ * TODO: allow for upper timelimit instead of / additional to `numRuns`
161
+ *
162
+ * TODO: Upstream to Effect
163
+ */
164
+ export const asProp = <Arbs extends Vitest.Vitest.Arbitraries, A, E, R>(
165
+ api: Vitest.Vitest.Tester<R>,
166
+ name: string,
167
+ arbitraries: Arbs,
168
+ test: Vitest.Vitest.TestFunction<
169
+ A,
170
+ E,
171
+ R,
172
+ [
173
+ { [K in keyof Arbs]: Arbs[K] extends FC.Arbitrary<infer T> ? T : Schema.Schema.Type<Arbs[K]> },
174
+ Vitest.TestContext,
175
+ EnhancedTestContext,
176
+ ]
177
+ >,
178
+ propOptions:
179
+ | number
180
+ | (Vitest.TestOptions & {
181
+ fastCheck?: FC.Parameters<{
182
+ [K in keyof Arbs]: Arbs[K] extends FC.Arbitrary<infer T> ? T : Schema.Schema.Type<Arbs[K]>
183
+ }>
184
+ }),
185
+ ) => {
186
+ const normalizedPropOptions = normalizePropOptions(propOptions)
187
+ const numRuns = normalizedPropOptions.fastCheck?.numRuns ?? 100
188
+ let runIndex = 0
189
+ let shrinkAttempts = 0
190
+ let totalExecutions = 0
191
+
192
+ return api.prop(
193
+ name,
194
+ arbitraries,
195
+ (properties, ctx) => {
196
+ if (ctx.signal.aborted) {
197
+ return ctx.skip('Test aborted')
198
+ }
199
+
200
+ totalExecutions++
201
+ const isInShrinkingPhase = runIndex >= numRuns
202
+
203
+ if (isInShrinkingPhase) {
204
+ shrinkAttempts++
205
+ }
206
+
207
+ const enhancedContext: EnhancedTestContext = isInShrinkingPhase
208
+ ? {
209
+ _tag: 'shrinking',
210
+ numRuns,
211
+ runIndex: runIndex++,
212
+ shrinkAttempt: shrinkAttempts,
213
+ totalExecutions,
214
+ }
215
+ : {
216
+ _tag: 'initial',
217
+ numRuns,
218
+ runIndex: runIndex++,
219
+ totalExecutions,
220
+ }
221
+
222
+ return test(properties, ctx, enhancedContext)
223
+ },
224
+ normalizedPropOptions,
225
+ )
226
+ }
@@ -1,182 +0,0 @@
1
- import { spawn } from 'node:child_process'
2
- import path from 'node:path'
3
- import { Effect, UnknownError } from '@livestore/utils/effect'
4
- import { cmd } from './cmd.ts'
5
-
6
- export const startDockerComposeServices = (args: StartDockerComposeServicesArgs) =>
7
- Effect.tryPromise({
8
- try: () => startDockerComposeServicesPromise(args),
9
- catch: (error) => UnknownError.make({ cause: new Error(`Failed to start Docker Compose: ${error}`) }),
10
- }).pipe(Effect.withSpan('startDockerComposeServices'))
11
-
12
- type StartDockerComposeServicesArgs = {
13
- composeFilePath?: string
14
- cwd: string
15
- serviceName?: string
16
- waitForLog?: string
17
- env?: Record<string, string>
18
- healthCheck?: {
19
- url: string // URL template with ${port} placeholder
20
- expectedStatus?: number // default 200
21
- maxAttempts?: number // default 30
22
- delayMs?: number // default 1000
23
- }
24
- /** @default false */
25
- forwardLogs?: boolean
26
- }
27
-
28
- export const pullDockerComposeImages = ({
29
- cwd,
30
- composeFilePath,
31
- }: Pick<StartDockerComposeServicesArgs, 'composeFilePath' | 'cwd'>) =>
32
- Effect.gen(function* () {
33
- const resolvedComposeFilePath = path.resolve(composeFilePath ?? path.join(cwd, 'docker-compose.yml'))
34
- yield* cmd(['docker', 'compose', '-f', resolvedComposeFilePath, 'pull'], { cwd })
35
- }).pipe(Effect.withSpan('pullDockerComposeImages'))
36
-
37
- /**
38
- * Starts Docker Compose services for testing with automatic cleanup.
39
- * Automatically allocates a free port and passes it as EXPOSED_PORT environment variable.
40
- *
41
- * @param composeFilePath - Path to docker-compose.yml file (defaults to `${cwd}/docker-compose.yml`)
42
- * @param cwd - Working directory for Docker Compose commands
43
- * @param env - Environment variables to pass to the Docker Compose commands (useful for passing ports)
44
- * @param serviceName - Optional specific service to start (omit to start all)
45
- * @param waitForLog - Log pattern to wait for before considering services ready
46
- * @param healthCheck - Health check configuration for waiting until service is ready
47
- */
48
- // TODO refactor implementation with Effect
49
- // TODO add test for this
50
- export const startDockerComposeServicesPromise = async ({
51
- composeFilePath,
52
- cwd,
53
- serviceName,
54
- waitForLog,
55
- healthCheck,
56
- env,
57
- forwardLogs = false,
58
- }: StartDockerComposeServicesArgs) => {
59
- let dockerComposeProcess: ReturnType<typeof spawn> | undefined
60
-
61
- const setup = async () => {
62
- const resolvedComposeFilePath = path.resolve(composeFilePath ?? path.join(cwd, 'docker-compose.yml'))
63
-
64
- // Build the docker compose command arguments
65
- const composeArgs = ['compose', '-f', resolvedComposeFilePath, 'up']
66
-
67
- // Add service name if specified
68
- if (serviceName) {
69
- composeArgs.push(serviceName)
70
- }
71
-
72
- dockerComposeProcess = spawn('docker', composeArgs, {
73
- stdio: ['ignore', 'pipe', 'pipe'],
74
- cwd,
75
- env: { ...process.env, ...env },
76
- })
77
-
78
- dockerComposeProcess.stdout?.setEncoding('utf8')
79
- dockerComposeProcess.stderr?.setEncoding('utf8')
80
-
81
- if (forwardLogs) {
82
- dockerComposeProcess.stdout?.on('data', (data: string) => {
83
- console.log(data)
84
- })
85
-
86
- dockerComposeProcess.stderr?.on('data', (data: string) => {
87
- console.error(data)
88
- })
89
- }
90
-
91
- // Wait for the service to be ready
92
- if (healthCheck) {
93
- // Use health check approach
94
- const maxAttempts = healthCheck.maxAttempts ?? 30
95
- const delayMs = healthCheck.delayMs ?? 1000
96
- const expectedStatus = healthCheck.expectedStatus ?? 200
97
- const healthUrl = healthCheck.url
98
-
99
- console.log(`Waiting for health check at ${healthUrl}...`)
100
-
101
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
102
- try {
103
- const response = await fetch(healthUrl)
104
- if (response.status === expectedStatus) {
105
- console.log(`Health check passed after ${attempt} attempts`)
106
- break
107
- }
108
- console.log(`Health check attempt ${attempt}/${maxAttempts}: status ${response.status}`)
109
- } catch (error) {
110
- console.log(
111
- `Health check attempt ${attempt}/${maxAttempts}: ${error instanceof Error ? error.message : 'failed'}`,
112
- )
113
- }
114
-
115
- if (attempt === maxAttempts) {
116
- throw new Error(`Health check failed after ${maxAttempts} attempts at ${healthUrl}`)
117
- }
118
-
119
- await new Promise((resolve) => setTimeout(resolve, delayMs))
120
- }
121
- } else if (waitForLog) {
122
- // Fallback to log-based waiting
123
- await new Promise<void>((resolve) => {
124
- const onData = (data: string) => {
125
- if (data.includes(waitForLog)) {
126
- dockerComposeProcess?.stdout?.off('data', onData)
127
- resolve()
128
- }
129
- }
130
- dockerComposeProcess?.stdout?.on('data', onData)
131
- dockerComposeProcess?.stderr?.on('data', onData)
132
- })
133
- } else {
134
- // No wait condition, just give it a moment to start
135
- await new Promise((resolve) => setTimeout(resolve, 2000))
136
- }
137
-
138
- console.log(`Docker Compose services ready${serviceName ? ` (${serviceName})` : ''}`)
139
- }
140
-
141
- const stopDockerComposeServices = async () => {
142
- if (dockerComposeProcess) {
143
- console.log('Stopping Docker Compose services...')
144
-
145
- const resolvedComposeFilePath = path.resolve(composeFilePath ?? path.join(cwd, 'docker-compose.yml'))
146
-
147
- // Use docker compose down to properly stop and clean up
148
- const downProcess = spawn('docker', ['compose', '-f', resolvedComposeFilePath, 'down'], {
149
- stdio: 'inherit',
150
- cwd,
151
- })
152
-
153
- await new Promise<void>((resolve) => {
154
- downProcess.on('close', () => {
155
- resolve()
156
- })
157
- })
158
-
159
- dockerComposeProcess.kill('SIGTERM')
160
- dockerComposeProcess = undefined
161
- }
162
- }
163
-
164
- process.on('exit', () => {
165
- stopDockerComposeServices()
166
- })
167
- process.on('SIGINT', () => {
168
- stopDockerComposeServices()
169
- })
170
- process.on('SIGTERM', () => {
171
- stopDockerComposeServices()
172
- })
173
-
174
- // try {
175
- // const { afterAll } = await import('vitest')
176
- // afterAll(async () => {
177
- // await stopDockerComposeServices()
178
- // })
179
- // } catch {}
180
-
181
- await setup()
182
- }
@@ -1,132 +0,0 @@
1
- import { spawn } from 'node:child_process'
2
- import net from 'node:net'
3
- import path from 'node:path'
4
- import { Effect, UnknownError } from '@livestore/utils/effect'
5
-
6
- export type StartWranglerDevServerArgs = {
7
- wranglerConfigPath?: string
8
- cwd: string
9
- port?: number
10
- }
11
-
12
- export const startWranglerDevServer = (args: StartWranglerDevServerArgs) =>
13
- Effect.tryPromise({
14
- try: (abortSignal) => startWranglerDevServerPromise({ ...args, abortSignal }),
15
- catch: (error) => UnknownError.make({ cause: new Error(`Failed to start Wrangler: ${error}`) }),
16
- }).pipe(Effect.withSpan('startWranglerDevServer'))
17
-
18
- // TODO refactor implementation with Effect
19
- // TODO add test for this
20
- // TODO allow for config to be passed in via code instead of `wrangler.toml` file
21
- // TODO fix zombie workerd processes causing high CPU usage - see https://github.com/livestorejs/livestore/issues/568
22
- /**
23
- * Starts a Wrangler dev server for testing with automatic cleanup.
24
- *
25
- * @param wranglerConfigPath - Path to wrangler.toml file (defaults to `${cwd}/wrangler.toml`)
26
- * @param cwd - Working directory for Wrangler commands
27
- * @returns Object with allocated port for the dev server
28
- */
29
- export const startWranglerDevServerPromise = async ({
30
- wranglerConfigPath,
31
- abortSignal,
32
- cwd,
33
- port: inputPort,
34
- }: {
35
- wranglerConfigPath?: string
36
- abortSignal?: AbortSignal
37
- cwd: string
38
- port?: number
39
- }) => {
40
- let wranglerProcess: ReturnType<typeof spawn> | undefined
41
-
42
- const getFreePort = (): Promise<number> => {
43
- return new Promise((resolve, reject) => {
44
- const server = net.createServer()
45
- server.listen(0, () => {
46
- const port = (server.address() as net.AddressInfo)?.port
47
- server.close(() => {
48
- if (port) {
49
- resolve(port)
50
- } else {
51
- reject(new Error('Could not get port'))
52
- }
53
- })
54
- })
55
- server.on('error', reject)
56
- })
57
- }
58
-
59
- const setup = async () => {
60
- const syncPort = inputPort ?? (await getFreePort())
61
-
62
- const resolvedWranglerConfigPath = path.resolve(wranglerConfigPath ?? path.join(cwd, 'wrangler.toml'))
63
-
64
- wranglerProcess = spawn(
65
- 'bunx',
66
- ['wrangler', 'dev', '--port', syncPort.toString(), '--config', resolvedWranglerConfigPath],
67
- {
68
- stdio: ['ignore', 'pipe', 'pipe'],
69
- cwd,
70
- env: {
71
- ...process.env,
72
- // NODE_OPTIONS: '--inspect --inspect-port=9233',
73
- },
74
- signal: abortSignal,
75
- },
76
- )
77
-
78
- wranglerProcess.stdout?.setEncoding('utf8')
79
- wranglerProcess.stderr?.setEncoding('utf8')
80
-
81
- wranglerProcess.stdout?.on('data', (data: string) => {
82
- // console.log(`[wrangler] ${data}`)
83
- console.log(data)
84
- })
85
-
86
- wranglerProcess.stderr?.on('data', (data: string) => {
87
- // console.error(`[wrangler] ${data}`)
88
- console.error(data)
89
- })
90
-
91
- await new Promise<void>((resolve) => {
92
- const onData = (data: string) => {
93
- if (data.includes('Ready on')) {
94
- wranglerProcess?.stdout?.off('data', onData)
95
- resolve()
96
- }
97
- }
98
- wranglerProcess?.stdout?.on('data', onData)
99
- })
100
-
101
- console.log(`Wrangler dev server ready on port ${syncPort}`)
102
-
103
- // Wait longer for the Cloudflare Workers runtime to fully initialize
104
- // console.log('Waiting for Cloudflare Workers runtime to fully initialize...')
105
- // await new Promise(resolve => setTimeout(resolve, 10000))
106
-
107
- return { port: syncPort }
108
- }
109
-
110
- const killWranglerProcess = () => {
111
- if (wranglerProcess) {
112
- console.log('Killing wrangler process...')
113
- wranglerProcess.kill('SIGTERM')
114
- wranglerProcess = undefined
115
- }
116
- }
117
-
118
- process.on('exit', killWranglerProcess)
119
- process.on('SIGINT', killWranglerProcess)
120
- process.on('SIGTERM', killWranglerProcess)
121
-
122
- try {
123
- const { afterAll } = await import('vitest')
124
- afterAll(() => {
125
- killWranglerProcess()
126
- })
127
- } catch {}
128
-
129
- const { port } = await setup()
130
-
131
- return { port, kill: killWranglerProcess }
132
- }