@sanity/cli-test 0.0.2-alpha.4 → 0.0.2-alpha.6
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.
- package/README.md +228 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/test/constants.d.ts +2 -0
- package/dist/test/constants.js +8 -0
- package/dist/test/constants.js.map +1 -0
- package/dist/test/setupExamples.d.ts +60 -0
- package/dist/test/setupExamples.js +129 -0
- package/dist/test/setupExamples.js.map +1 -0
- package/dist/test/testExample.d.ts +46 -0
- package/dist/test/testExample.js +93 -0
- package/dist/test/testExample.js.map +1 -0
- package/dist/utils/fileExists.d.ts +9 -0
- package/dist/utils/fileExists.js +13 -0
- package/dist/utils/fileExists.js.map +1 -0
- package/dist/utils/paths.d.ts +22 -0
- package/dist/utils/paths.js +30 -0
- package/dist/utils/paths.js.map +1 -0
- package/dist/vitest.d.ts +20 -0
- package/dist/vitest.js +21 -0
- package/dist/vitest.js.map +1 -0
- package/dist/vitestWorker.d.ts +23 -0
- package/dist/vitestWorker.js +131 -0
- package/dist/vitestWorker.js.map +1 -0
- package/examples/basic-app/package.json +27 -0
- package/examples/basic-app/sanity.cli.ts +12 -0
- package/examples/basic-app/src/App.css +20 -0
- package/examples/basic-app/src/App.tsx +26 -0
- package/examples/basic-app/src/ExampleComponent.css +84 -0
- package/examples/basic-app/src/ExampleComponent.tsx +38 -0
- package/examples/basic-app/tsconfig.json +17 -0
- package/examples/basic-studio/package.json +29 -0
- package/examples/basic-studio/sanity.cli.ts +11 -0
- package/examples/basic-studio/sanity.config.ts +18 -0
- package/examples/basic-studio/schemaTypes/author.ts +52 -0
- package/examples/basic-studio/schemaTypes/blockContent.ts +71 -0
- package/examples/basic-studio/schemaTypes/category.ts +20 -0
- package/examples/basic-studio/schemaTypes/index.ts +6 -0
- package/examples/basic-studio/schemaTypes/post.ts +67 -0
- package/examples/basic-studio/tsconfig.json +17 -0
- package/examples/multi-workspace-studio/package.json +29 -0
- package/examples/multi-workspace-studio/sanity.cli.ts +11 -0
- package/examples/multi-workspace-studio/sanity.config.ts +37 -0
- package/examples/multi-workspace-studio/schemaTypes/author.ts +52 -0
- package/examples/multi-workspace-studio/schemaTypes/blockContent.ts +70 -0
- package/examples/multi-workspace-studio/schemaTypes/category.ts +20 -0
- package/examples/multi-workspace-studio/schemaTypes/index.ts +6 -0
- package/examples/multi-workspace-studio/schemaTypes/post.ts +67 -0
- package/examples/multi-workspace-studio/tsconfig.json +17 -0
- package/examples/worst-case-studio/README.md +21 -0
- package/examples/worst-case-studio/package.json +33 -0
- package/examples/worst-case-studio/sanity.cli.ts +16 -0
- package/examples/worst-case-studio/sanity.config.tsx +48 -0
- package/examples/worst-case-studio/src/defines.ts +8 -0
- package/examples/worst-case-studio/src/descriptionIcon.svg +7 -0
- package/examples/worst-case-studio/src/descriptionInput.module.css +13 -0
- package/examples/worst-case-studio/src/descriptionInput.tsx +55 -0
- package/examples/worst-case-studio/src/schemaTypes/author.ts +52 -0
- package/examples/worst-case-studio/src/schemaTypes/blockContent.ts +70 -0
- package/examples/worst-case-studio/src/schemaTypes/category.ts +20 -0
- package/examples/worst-case-studio/src/schemaTypes/index.ts +6 -0
- package/examples/worst-case-studio/src/schemaTypes/post.ts +71 -0
- package/examples/worst-case-studio/src/typings.d.ts +37 -0
- package/examples/worst-case-studio/tsconfig.json +22 -0
- package/package.json +31 -14
package/README.md
CHANGED
|
@@ -2,8 +2,161 @@
|
|
|
2
2
|
|
|
3
3
|
Provides test helpers for the Sanity CLI.
|
|
4
4
|
|
|
5
|
+
## Quick Start
|
|
6
|
+
|
|
7
|
+
### 1. Set up vitest global setup
|
|
8
|
+
|
|
9
|
+
Add the cli-test vitest setup to your `vitest.config.ts`:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import {defineConfig} from 'vitest/config'
|
|
13
|
+
|
|
14
|
+
export default defineConfig({
|
|
15
|
+
test: {
|
|
16
|
+
globalSetup: ['@sanity/cli-test/vitest'],
|
|
17
|
+
},
|
|
18
|
+
})
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
This will automatically copy and install dependencies for all bundled examples before tests run.
|
|
22
|
+
|
|
23
|
+
### 2. Use test examples in your tests
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import {testExample} from '@sanity/cli-test'
|
|
27
|
+
import {describe, test} from 'vitest'
|
|
28
|
+
|
|
29
|
+
describe('my test suite', () => {
|
|
30
|
+
test('should work with basic-studio', async () => {
|
|
31
|
+
const cwd = await testExample('basic-studio')
|
|
32
|
+
// The example is now available at `cwd` with dependencies installed
|
|
33
|
+
// Tests that need built output should build explicitly:
|
|
34
|
+
// await buildExample(cwd)
|
|
35
|
+
})
|
|
36
|
+
})
|
|
37
|
+
```
|
|
38
|
+
|
|
5
39
|
## API
|
|
6
40
|
|
|
41
|
+
### `testExample(exampleName: string, options?: TestExampleOptions): Promise<string>`
|
|
42
|
+
|
|
43
|
+
Creates an isolated copy of a bundled example for testing. Returns the absolute path to the temporary directory containing the example.
|
|
44
|
+
|
|
45
|
+
**Parameters:**
|
|
46
|
+
|
|
47
|
+
- `exampleName` - Name of the example to copy (e.g., 'basic-app', 'basic-studio')
|
|
48
|
+
- `options.tempDir` - Optional custom temp directory path (defaults to `process.cwd()/tmp`)
|
|
49
|
+
|
|
50
|
+
**Returns:** Absolute path to the temporary example directory
|
|
51
|
+
|
|
52
|
+
**Available Examples:**
|
|
53
|
+
|
|
54
|
+
- `basic-app` - Basic Sanity application
|
|
55
|
+
- `basic-studio` - Basic Sanity Studio
|
|
56
|
+
- `multi-workspace-studio` - Multi-workspace Sanity Studio
|
|
57
|
+
- `worst-case-studio` - Stress-test Sanity Studio
|
|
58
|
+
|
|
59
|
+
**Example:**
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import {testExample} from '@sanity/cli-test'
|
|
63
|
+
|
|
64
|
+
const cwd = await testExample('basic-studio')
|
|
65
|
+
// Example is ready at `cwd` with dependencies installed
|
|
66
|
+
// Note: Examples are NOT built by default - tests should build if needed
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### `setup(options?: SetupTestExamplesOptions): Promise<void>`
|
|
70
|
+
|
|
71
|
+
Vitest global setup function that copies examples and installs dependencies. This is automatically called by vitest when using `@sanity/cli-test/vitest` in your globalSetup config.
|
|
72
|
+
|
|
73
|
+
**Parameters:**
|
|
74
|
+
|
|
75
|
+
- `options.additionalExamples` - Glob patterns for additional example directories from your local repo to set up alongside the default bundled examples (e.g., `['examples/*', 'dev/*']`). Only directories containing a `package.json` are included.
|
|
76
|
+
- `options.tempDir` - Custom temp directory path (defaults to `process.cwd()/tmp`)
|
|
77
|
+
|
|
78
|
+
**Note:** Examples are NOT built during setup. Tests that need built output should build explicitly.
|
|
79
|
+
|
|
80
|
+
**Adding examples from your local repo:**
|
|
81
|
+
|
|
82
|
+
If your repo has its own example directories that you want to test alongside the default bundled examples, use the `additionalExamples` option to include them:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
// vitest.setup.ts
|
|
86
|
+
import {setup as cliTestSetup, teardown} from '@sanity/cli-test/vitest'
|
|
87
|
+
|
|
88
|
+
export {teardown}
|
|
89
|
+
|
|
90
|
+
export async function setup(project) {
|
|
91
|
+
return cliTestSetup(project, {
|
|
92
|
+
additionalExamples: ['examples/*', 'dev/*'],
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
// vitest.config.ts
|
|
99
|
+
import {defineConfig} from 'vitest/config'
|
|
100
|
+
|
|
101
|
+
export default defineConfig({
|
|
102
|
+
test: {
|
|
103
|
+
globalSetup: ['vitest.setup.ts'],
|
|
104
|
+
},
|
|
105
|
+
})
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### `teardown(options?: TeardownTestExamplesOptions): Promise<void>`
|
|
109
|
+
|
|
110
|
+
Vitest global teardown function that removes the temp directory. This is automatically called by vitest when using `@sanity/cli-test/vitest`.
|
|
111
|
+
|
|
112
|
+
**Parameters:**
|
|
113
|
+
|
|
114
|
+
- `options.tempDir` - Custom temp directory path (defaults to `process.cwd()/tmp`)
|
|
115
|
+
|
|
116
|
+
### `setupWorkerBuild(filePaths: string[]): Promise<void>`
|
|
117
|
+
|
|
118
|
+
Utility function to compile TypeScript worker files (`.worker.ts`) to JavaScript for use in tests. Must be integrated into a custom vitest global setup file.
|
|
119
|
+
|
|
120
|
+
**Parameters:**
|
|
121
|
+
|
|
122
|
+
- `filePaths` - Array of paths to `.worker.ts` files to compile
|
|
123
|
+
|
|
124
|
+
**Features:**
|
|
125
|
+
|
|
126
|
+
- Compiles TypeScript to JavaScript using SWC for fast compilation
|
|
127
|
+
- Generates source maps for debugging
|
|
128
|
+
- Automatically watches for changes in watch mode (detects `VITEST_WATCH=true` or `--watch` flag)
|
|
129
|
+
- Handles files from both `@sanity/cli` and `@sanity/cli-core` packages
|
|
130
|
+
|
|
131
|
+
**Note:** This is a utility function, NOT automatically called. See the "Worker Files" section for integration examples.
|
|
132
|
+
|
|
133
|
+
**Example:**
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
// test/workerBuild.ts
|
|
137
|
+
import {setupWorkerBuild} from '@sanity/cli-test/vitest'
|
|
138
|
+
import {glob} from 'tinyglobby'
|
|
139
|
+
|
|
140
|
+
export async function setup() {
|
|
141
|
+
const workerFiles = await glob('**/*.worker.ts', {
|
|
142
|
+
ignore: ['**/node_modules/**', '**/dist/**'],
|
|
143
|
+
})
|
|
144
|
+
return setupWorkerBuild(workerFiles)
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### `teardownWorkerBuild(): Promise<void>`
|
|
149
|
+
|
|
150
|
+
Utility function to clean up worker build artifacts and close file watchers. Must be integrated into a custom vitest global setup file.
|
|
151
|
+
|
|
152
|
+
**Features:**
|
|
153
|
+
|
|
154
|
+
- Closes file watchers if in watch mode
|
|
155
|
+
- Deletes all compiled `.js` files that were generated from `.worker.ts` files
|
|
156
|
+
- Clears internal tracking of compiled files
|
|
157
|
+
|
|
158
|
+
**Note:** This is a utility function, NOT automatically called. See the "Worker Files" section for integration examples.
|
|
159
|
+
|
|
7
160
|
### `testCommand(command: Command, args?: string[])`
|
|
8
161
|
|
|
9
162
|
Runs the given command with the given arguments and returns the output.
|
|
@@ -30,3 +183,78 @@ mockApi({
|
|
|
30
183
|
email: 'john.doe@example.com',
|
|
31
184
|
})
|
|
32
185
|
```
|
|
186
|
+
|
|
187
|
+
## How It Works
|
|
188
|
+
|
|
189
|
+
This package bundles pre-configured Sanity examples that can be used for testing. When you call `testExample()`:
|
|
190
|
+
|
|
191
|
+
1. It creates a unique temporary copy of the requested example
|
|
192
|
+
2. Symlinks the node_modules directory from the global setup version (for performance)
|
|
193
|
+
3. Returns the path to the isolated test directory
|
|
194
|
+
|
|
195
|
+
The examples work identically whether this package is used in a monorepo or installed from npm.
|
|
196
|
+
|
|
197
|
+
## Building Examples
|
|
198
|
+
|
|
199
|
+
Examples are NOT built during global setup or when calling `testExample()`. Tests that need built output should build explicitly:
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
import {exec} from 'node:child_process'
|
|
203
|
+
import {promisify} from 'node:util'
|
|
204
|
+
|
|
205
|
+
const execAsync = promisify(exec)
|
|
206
|
+
|
|
207
|
+
const cwd = await testExample('basic-studio')
|
|
208
|
+
// Build the example before running tests that need it
|
|
209
|
+
await execAsync('npx sanity build --yes', {cwd})
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
## Worker Files
|
|
213
|
+
|
|
214
|
+
Worker files (`.worker.ts`) are TypeScript files that run in separate threads or processes. This package provides utilities to compile these files for testing, but they must be integrated into a custom vitest global setup file.
|
|
215
|
+
|
|
216
|
+
### Setting Up Worker Compilation
|
|
217
|
+
|
|
218
|
+
**Step 1: Create a worker setup file** (e.g., `test/workerBuild.ts`):
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
import {setupWorkerBuild, teardownWorkerBuild} from '@sanity/cli-test/vitest'
|
|
222
|
+
import {glob} from 'tinyglobby'
|
|
223
|
+
|
|
224
|
+
export async function setup() {
|
|
225
|
+
// Find all .worker.ts files in your project
|
|
226
|
+
const workerFiles = await glob('**/*.worker.ts', {
|
|
227
|
+
cwd: process.cwd(),
|
|
228
|
+
ignore: ['**/node_modules/**', '**/dist/**'],
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
return setupWorkerBuild(workerFiles)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export async function teardown() {
|
|
235
|
+
return teardownWorkerBuild()
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
**Step 2: Add to vitest config:**
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
// vitest.config.ts
|
|
243
|
+
import {defineConfig} from 'vitest/config'
|
|
244
|
+
|
|
245
|
+
export default defineConfig({
|
|
246
|
+
test: {
|
|
247
|
+
globalSetup: [
|
|
248
|
+
'test/workerBuild.ts', // Your worker setup
|
|
249
|
+
'@sanity/cli-test/vitest', // Example setup
|
|
250
|
+
],
|
|
251
|
+
},
|
|
252
|
+
})
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
**Features:**
|
|
256
|
+
|
|
257
|
+
- Compiles TypeScript to JavaScript using SWC for fast compilation
|
|
258
|
+
- Generates source maps for debugging
|
|
259
|
+
- Automatically watches for changes in watch mode (detects `VITEST_WATCH=true` or `--watch` flag)
|
|
260
|
+
- Cleans up compiled `.js` files after tests complete
|
package/dist/index.d.ts
CHANGED
|
@@ -2,5 +2,8 @@ export * from './test/createTestClient.js';
|
|
|
2
2
|
export * from './test/createTestToken.js';
|
|
3
3
|
export * from './test/mockApi.js';
|
|
4
4
|
export * from './test/mockSanityCommand.js';
|
|
5
|
+
export * from './test/setupExamples.js';
|
|
5
6
|
export * from './test/testCommand.js';
|
|
7
|
+
export * from './test/testExample.js';
|
|
6
8
|
export * from './test/testHook.js';
|
|
9
|
+
export * from './utils/paths.js';
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,10 @@ export * from './test/createTestClient.js';
|
|
|
2
2
|
export * from './test/createTestToken.js';
|
|
3
3
|
export * from './test/mockApi.js';
|
|
4
4
|
export * from './test/mockSanityCommand.js';
|
|
5
|
+
export * from './test/setupExamples.js';
|
|
5
6
|
export * from './test/testCommand.js';
|
|
7
|
+
export * from './test/testExample.js';
|
|
6
8
|
export * from './test/testHook.js';
|
|
9
|
+
export * from './utils/paths.js';
|
|
7
10
|
|
|
8
11
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './test/createTestClient.js'\nexport * from './test/createTestToken.js'\nexport * from './test/mockApi.js'\nexport * from './test/mockSanityCommand.js'\nexport * from './test/testCommand.js'\nexport * from './test/testHook.js'\n"],"names":[],"mappings":"AAAA,cAAc,6BAA4B;AAC1C,cAAc,4BAA2B;AACzC,cAAc,oBAAmB;AACjC,cAAc,8BAA6B;AAC3C,cAAc,wBAAuB;AACrC,cAAc,qBAAoB"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './test/createTestClient.js'\nexport * from './test/createTestToken.js'\nexport * from './test/mockApi.js'\nexport * from './test/mockSanityCommand.js'\nexport * from './test/setupExamples.js'\nexport * from './test/testCommand.js'\nexport * from './test/testExample.js'\nexport * from './test/testHook.js'\nexport * from './utils/paths.js'\n"],"names":[],"mappings":"AAAA,cAAc,6BAA4B;AAC1C,cAAc,4BAA2B;AACzC,cAAc,oBAAmB;AACjC,cAAc,8BAA6B;AAC3C,cAAc,0BAAyB;AACvC,cAAc,wBAAuB;AACrC,cAAc,wBAAuB;AACrC,cAAc,qBAAoB;AAClC,cAAc,mBAAkB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/test/constants.ts"],"sourcesContent":["export const DEFAULT_EXAMPLES = [\n 'basic-app',\n 'basic-studio',\n 'multi-workspace-studio',\n 'worst-case-studio',\n] as const\n\nexport type ExampleName = (typeof DEFAULT_EXAMPLES)[number]\n"],"names":["DEFAULT_EXAMPLES"],"mappings":"AAAA,OAAO,MAAMA,mBAAmB;IAC9B;IACA;IACA;IACA;CACD,CAAS"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { type TestProject } from 'vitest/node';
|
|
2
|
+
/** Options for setupTestExamples */
|
|
3
|
+
export interface SetupTestExamplesOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Glob patterns for additional example directories to set up.
|
|
6
|
+
*
|
|
7
|
+
* Each pattern is matched against directories in the current working directory.
|
|
8
|
+
* Only directories containing a `package.json` file are included.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* ['examples/*', 'dev/*']
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
additionalExamples?: string[];
|
|
16
|
+
/**
|
|
17
|
+
* Custom temp directory path. Defaults to process.cwd()/tmp
|
|
18
|
+
*/
|
|
19
|
+
tempDir?: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Global setup function for initializing test examples.
|
|
23
|
+
*
|
|
24
|
+
* Copies examples from the bundled location to a temp directory
|
|
25
|
+
* and installs dependencies.
|
|
26
|
+
*
|
|
27
|
+
* Note: Examples are NOT built during setup. Tests that need built
|
|
28
|
+
* examples should build them as part of the test.
|
|
29
|
+
*
|
|
30
|
+
* This function is designed to be used with vitest globalSetup.
|
|
31
|
+
*
|
|
32
|
+
* @param options - Configuration options
|
|
33
|
+
* @example
|
|
34
|
+
* ```typescript
|
|
35
|
+
* // In vitest.config.ts
|
|
36
|
+
* export default defineConfig({
|
|
37
|
+
* test: {
|
|
38
|
+
* globalSetup: ['@sanity/cli-test/vitest']
|
|
39
|
+
* }
|
|
40
|
+
* })
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export declare function setup(_: TestProject, options?: SetupTestExamplesOptions): Promise<void>;
|
|
44
|
+
/** Options for teardownTestExamples */
|
|
45
|
+
export interface TeardownTestExamplesOptions {
|
|
46
|
+
/**
|
|
47
|
+
* Custom temp directory path. Defaults to process.cwd()/tmp
|
|
48
|
+
*/
|
|
49
|
+
tempDir?: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Teardown function to clean up test examples.
|
|
53
|
+
*
|
|
54
|
+
* Removes the temp directory created by setupTestExamples.
|
|
55
|
+
*
|
|
56
|
+
* This function is designed to be used with vitest globalSetup.
|
|
57
|
+
*
|
|
58
|
+
* @param options - Configuration options
|
|
59
|
+
*/
|
|
60
|
+
export declare function teardown(options?: TeardownTestExamplesOptions): Promise<void>;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { exec as execNode } from 'node:child_process';
|
|
2
|
+
import { readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { basename, join } from 'node:path';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
import ora from 'ora';
|
|
6
|
+
import { glob } from 'tinyglobby';
|
|
7
|
+
import { fileExists } from '../utils/fileExists.js';
|
|
8
|
+
import { getExamplesPath, getTempPath } from '../utils/paths.js';
|
|
9
|
+
import { DEFAULT_EXAMPLES } from './constants.js';
|
|
10
|
+
import { testCopyDirectory } from './testExample.js';
|
|
11
|
+
const exec = promisify(execNode);
|
|
12
|
+
async function getAdditionalExamplePaths(examples) {
|
|
13
|
+
const paths = await glob(examples, {
|
|
14
|
+
absolute: true,
|
|
15
|
+
ignore: [
|
|
16
|
+
'**/node_modules/**',
|
|
17
|
+
'**/dist/**'
|
|
18
|
+
],
|
|
19
|
+
onlyDirectories: true
|
|
20
|
+
});
|
|
21
|
+
const additionalExamples = [];
|
|
22
|
+
for (const path of paths){
|
|
23
|
+
if (await fileExists(join(`${path}/package.json`))) {
|
|
24
|
+
additionalExamples.push({
|
|
25
|
+
example: basename(path),
|
|
26
|
+
fromPath: path
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return additionalExamples;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Global setup function for initializing test examples.
|
|
34
|
+
*
|
|
35
|
+
* Copies examples from the bundled location to a temp directory
|
|
36
|
+
* and installs dependencies.
|
|
37
|
+
*
|
|
38
|
+
* Note: Examples are NOT built during setup. Tests that need built
|
|
39
|
+
* examples should build them as part of the test.
|
|
40
|
+
*
|
|
41
|
+
* This function is designed to be used with vitest globalSetup.
|
|
42
|
+
*
|
|
43
|
+
* @param options - Configuration options
|
|
44
|
+
* @example
|
|
45
|
+
* ```typescript
|
|
46
|
+
* // In vitest.config.ts
|
|
47
|
+
* export default defineConfig({
|
|
48
|
+
* test: {
|
|
49
|
+
* globalSetup: ['@sanity/cli-test/vitest']
|
|
50
|
+
* }
|
|
51
|
+
* })
|
|
52
|
+
* ```
|
|
53
|
+
*/ export async function setup(_, options = {}) {
|
|
54
|
+
const { additionalExamples, tempDir } = options;
|
|
55
|
+
const spinner = ora({
|
|
56
|
+
// Without this, the watch mode input is discarded
|
|
57
|
+
discardStdin: false,
|
|
58
|
+
text: 'Initializing test environment...'
|
|
59
|
+
}).start();
|
|
60
|
+
try {
|
|
61
|
+
const examplesDir = getExamplesPath();
|
|
62
|
+
const tempDirectory = getTempPath(tempDir);
|
|
63
|
+
const allExamplePaths = [];
|
|
64
|
+
// Add the default examples
|
|
65
|
+
for (const example of DEFAULT_EXAMPLES){
|
|
66
|
+
allExamplePaths.push({
|
|
67
|
+
example,
|
|
68
|
+
fromPath: join(examplesDir, example)
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
// Add the additional examples
|
|
72
|
+
if (additionalExamples && additionalExamples.length > 0) {
|
|
73
|
+
const additionalExamplePaths = await getAdditionalExamplePaths(additionalExamples);
|
|
74
|
+
if (additionalExamplePaths.length > 0) {
|
|
75
|
+
allExamplePaths.push(...additionalExamplePaths);
|
|
76
|
+
} else {
|
|
77
|
+
spinner.warn(`No additional examples found, check the glob pattern: ${additionalExamples.join(', ')}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
for (const { example, fromPath } of allExamplePaths){
|
|
81
|
+
const toPath = join(tempDirectory, `example-${example}`);
|
|
82
|
+
// Copy the example, excluding node_modules and dist
|
|
83
|
+
await testCopyDirectory(fromPath, toPath, [
|
|
84
|
+
'node_modules',
|
|
85
|
+
'dist'
|
|
86
|
+
]);
|
|
87
|
+
// Replace the package.json name with a temp name
|
|
88
|
+
const packageJsonPath = join(toPath, 'package.json');
|
|
89
|
+
const packageJson = await readFile(packageJsonPath, 'utf8');
|
|
90
|
+
const packageJsonData = JSON.parse(packageJson);
|
|
91
|
+
packageJsonData.name = `${packageJsonData.name}-test`;
|
|
92
|
+
await writeFile(packageJsonPath, JSON.stringify(packageJsonData, null, 2));
|
|
93
|
+
// Run pnpm install --no-lockfile in the temp directory
|
|
94
|
+
try {
|
|
95
|
+
await exec(`pnpm install --prefer-offline --no-lockfile`, {
|
|
96
|
+
cwd: toPath
|
|
97
|
+
});
|
|
98
|
+
} catch (error) {
|
|
99
|
+
const execError = error;
|
|
100
|
+
spinner.fail('Failed to install dependencies');
|
|
101
|
+
console.error(execError.stderr || execError.stdout || execError.message);
|
|
102
|
+
throw new Error(`Error installing dependencies in ${toPath}: ${execError.stderr || execError.stdout || execError.message}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
spinner.succeed('Test environment initialized');
|
|
106
|
+
} catch (error) {
|
|
107
|
+
spinner.fail('Failed to initialize test environment');
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Teardown function to clean up test examples.
|
|
113
|
+
*
|
|
114
|
+
* Removes the temp directory created by setupTestExamples.
|
|
115
|
+
*
|
|
116
|
+
* This function is designed to be used with vitest globalSetup.
|
|
117
|
+
*
|
|
118
|
+
* @param options - Configuration options
|
|
119
|
+
*/ export async function teardown(options = {}) {
|
|
120
|
+
const { tempDir } = options;
|
|
121
|
+
const tempDirectory = getTempPath(tempDir);
|
|
122
|
+
// Remove the tmp directory
|
|
123
|
+
await rm(tempDirectory, {
|
|
124
|
+
force: true,
|
|
125
|
+
recursive: true
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
//# sourceMappingURL=setupExamples.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/test/setupExamples.ts"],"sourcesContent":["import {exec as execNode} from 'node:child_process'\nimport {readFile, rm, writeFile} from 'node:fs/promises'\nimport {basename, join} from 'node:path'\nimport {promisify} from 'node:util'\n\nimport ora from 'ora'\nimport {glob} from 'tinyglobby'\nimport {type TestProject} from 'vitest/node'\n\nimport {fileExists} from '../utils/fileExists.js'\nimport {getExamplesPath, getTempPath} from '../utils/paths.js'\nimport {DEFAULT_EXAMPLES} from './constants.js'\nimport {testCopyDirectory} from './testExample.js'\n\nconst exec = promisify(execNode)\n\n/** Options for setupTestExamples */\nexport interface SetupTestExamplesOptions {\n /**\n * Glob patterns for additional example directories to set up.\n *\n * Each pattern is matched against directories in the current working directory.\n * Only directories containing a `package.json` file are included.\n *\n * @example\n * ```typescript\n * ['examples/*', 'dev/*']\n * ```\n */\n additionalExamples?: string[]\n\n /**\n * Custom temp directory path. Defaults to process.cwd()/tmp\n */\n tempDir?: string\n}\n\nasync function getAdditionalExamplePaths(examples: string[]): Promise<ExamplePath[]> {\n const paths = await glob(examples, {\n absolute: true,\n ignore: ['**/node_modules/**', '**/dist/**'],\n onlyDirectories: true,\n })\n\n const additionalExamples: ExamplePath[] = []\n\n for (const path of paths) {\n if (await fileExists(join(`${path}/package.json`))) {\n additionalExamples.push({\n example: basename(path),\n fromPath: path,\n })\n }\n }\n\n return additionalExamples\n}\n\ninterface ExamplePath {\n example: string\n fromPath: string\n}\n/**\n * Global setup function for initializing test examples.\n *\n * Copies examples from the bundled location to a temp directory\n * and installs dependencies.\n *\n * Note: Examples are NOT built during setup. Tests that need built\n * examples should build them as part of the test.\n *\n * This function is designed to be used with vitest globalSetup.\n *\n * @param options - Configuration options\n * @example\n * ```typescript\n * // In vitest.config.ts\n * export default defineConfig({\n * test: {\n * globalSetup: ['@sanity/cli-test/vitest']\n * }\n * })\n * ```\n */\nexport async function setup(_: TestProject, options: SetupTestExamplesOptions = {}): Promise<void> {\n const {additionalExamples, tempDir} = options\n\n const spinner = ora({\n // Without this, the watch mode input is discarded\n discardStdin: false,\n text: 'Initializing test environment...',\n }).start()\n\n try {\n const examplesDir = getExamplesPath()\n const tempDirectory = getTempPath(tempDir)\n\n const allExamplePaths: ExamplePath[] = []\n\n // Add the default examples\n for (const example of DEFAULT_EXAMPLES) {\n allExamplePaths.push({\n example,\n fromPath: join(examplesDir, example),\n })\n }\n\n // Add the additional examples\n if (additionalExamples && additionalExamples.length > 0) {\n const additionalExamplePaths = await getAdditionalExamplePaths(additionalExamples)\n\n if (additionalExamplePaths.length > 0) {\n allExamplePaths.push(...additionalExamplePaths)\n } else {\n spinner.warn(\n `No additional examples found, check the glob pattern: ${additionalExamples.join(', ')}`,\n )\n }\n }\n\n for (const {example, fromPath} of allExamplePaths) {\n const toPath = join(tempDirectory, `example-${example}`)\n // Copy the example, excluding node_modules and dist\n await testCopyDirectory(fromPath, toPath, ['node_modules', 'dist'])\n\n // Replace the package.json name with a temp name\n const packageJsonPath = join(toPath, 'package.json')\n const packageJson = await readFile(packageJsonPath, 'utf8')\n const packageJsonData = JSON.parse(packageJson)\n packageJsonData.name = `${packageJsonData.name}-test`\n await writeFile(packageJsonPath, JSON.stringify(packageJsonData, null, 2))\n\n // Run pnpm install --no-lockfile in the temp directory\n try {\n await exec(`pnpm install --prefer-offline --no-lockfile`, {\n cwd: toPath,\n })\n } catch (error) {\n const execError = error as {message: string; stderr?: string; stdout?: string}\n spinner.fail('Failed to install dependencies')\n console.error(execError.stderr || execError.stdout || execError.message)\n throw new Error(\n `Error installing dependencies in ${toPath}: ${execError.stderr || execError.stdout || execError.message}`,\n )\n }\n }\n\n spinner.succeed('Test environment initialized')\n } catch (error) {\n spinner.fail('Failed to initialize test environment')\n throw error\n }\n}\n\n/** Options for teardownTestExamples */\nexport interface TeardownTestExamplesOptions {\n /**\n * Custom temp directory path. Defaults to process.cwd()/tmp\n */\n tempDir?: string\n}\n\n/**\n * Teardown function to clean up test examples.\n *\n * Removes the temp directory created by setupTestExamples.\n *\n * This function is designed to be used with vitest globalSetup.\n *\n * @param options - Configuration options\n */\nexport async function teardown(options: TeardownTestExamplesOptions = {}): Promise<void> {\n const {tempDir} = options\n const tempDirectory = getTempPath(tempDir)\n\n // Remove the tmp directory\n await rm(tempDirectory, {force: true, recursive: true})\n}\n"],"names":["exec","execNode","readFile","rm","writeFile","basename","join","promisify","ora","glob","fileExists","getExamplesPath","getTempPath","DEFAULT_EXAMPLES","testCopyDirectory","getAdditionalExamplePaths","examples","paths","absolute","ignore","onlyDirectories","additionalExamples","path","push","example","fromPath","setup","_","options","tempDir","spinner","discardStdin","text","start","examplesDir","tempDirectory","allExamplePaths","length","additionalExamplePaths","warn","toPath","packageJsonPath","packageJson","packageJsonData","JSON","parse","name","stringify","cwd","error","execError","fail","console","stderr","stdout","message","Error","succeed","teardown","force","recursive"],"mappings":"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"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type ExampleName } from './constants.js';
|
|
2
|
+
/**
|
|
3
|
+
* Recursively copy a directory, skipping specified folders.
|
|
4
|
+
*
|
|
5
|
+
* @param srcDir - Source directory to copy from
|
|
6
|
+
* @param destDir - Destination directory to copy to
|
|
7
|
+
* @param skip - Array of directory/file names to skip (e.g., ['node_modules', 'dist'])
|
|
8
|
+
* @internal
|
|
9
|
+
*/
|
|
10
|
+
export declare function testCopyDirectory(srcDir: string, destDir: string, skip?: string[]): Promise<void>;
|
|
11
|
+
/** Options for testExample */
|
|
12
|
+
export interface TestExampleOptions {
|
|
13
|
+
/**
|
|
14
|
+
* Custom temp directory. Defaults to process.cwd()/tmp
|
|
15
|
+
*/
|
|
16
|
+
tempDir?: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Clones an example directory into a temporary directory with an isolated copy.
|
|
20
|
+
*
|
|
21
|
+
* The function creates a unique temporary copy of the specified example with:
|
|
22
|
+
* - A random unique ID to avoid conflicts between parallel tests
|
|
23
|
+
* - Symlinked node_modules for performance (from the global setup version)
|
|
24
|
+
* - Modified package.json name to prevent conflicts
|
|
25
|
+
*
|
|
26
|
+
* The example is first looked up in the temp directory (if global setup ran),
|
|
27
|
+
* otherwise it falls back to the bundled examples in the package.
|
|
28
|
+
*
|
|
29
|
+
* @param exampleName - The name of the example to clone (e.g., 'basic-app', 'basic-studio')
|
|
30
|
+
* @param options - Configuration options
|
|
31
|
+
* @returns The absolute path to the temporary directory containing the example
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```typescript
|
|
35
|
+
* import {testExample} from '@sanity/cli-test'
|
|
36
|
+
* import {describe, test} from 'vitest'
|
|
37
|
+
*
|
|
38
|
+
* describe('my test suite', () => {
|
|
39
|
+
* test('should work with basic-studio', async () => {
|
|
40
|
+
* const cwd = await testExample('basic-studio')
|
|
41
|
+
* // ... run your tests in this directory
|
|
42
|
+
* })
|
|
43
|
+
* })
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
export declare function testExample(exampleName: ExampleName | (string & {}), options?: TestExampleOptions): Promise<string>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { copyFile, mkdir, readdir, readFile, stat, symlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { getExamplesPath, getTempPath } from '../utils/paths.js';
|
|
5
|
+
/**
|
|
6
|
+
* Recursively copy a directory, skipping specified folders.
|
|
7
|
+
*
|
|
8
|
+
* @param srcDir - Source directory to copy from
|
|
9
|
+
* @param destDir - Destination directory to copy to
|
|
10
|
+
* @param skip - Array of directory/file names to skip (e.g., ['node_modules', 'dist'])
|
|
11
|
+
* @internal
|
|
12
|
+
*/ export async function testCopyDirectory(srcDir, destDir, skip = []) {
|
|
13
|
+
await mkdir(destDir, {
|
|
14
|
+
recursive: true
|
|
15
|
+
});
|
|
16
|
+
const entries = await readdir(srcDir);
|
|
17
|
+
for (const entry of entries){
|
|
18
|
+
if (skip.includes(entry)) {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
const srcPath = join(srcDir, entry);
|
|
22
|
+
const destPath = join(destDir, entry);
|
|
23
|
+
const stats = await stat(srcPath);
|
|
24
|
+
await (stats.isDirectory() ? testCopyDirectory(srcPath, destPath, skip) : copyFile(srcPath, destPath));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Clones an example directory into a temporary directory with an isolated copy.
|
|
29
|
+
*
|
|
30
|
+
* The function creates a unique temporary copy of the specified example with:
|
|
31
|
+
* - A random unique ID to avoid conflicts between parallel tests
|
|
32
|
+
* - Symlinked node_modules for performance (from the global setup version)
|
|
33
|
+
* - Modified package.json name to prevent conflicts
|
|
34
|
+
*
|
|
35
|
+
* The example is first looked up in the temp directory (if global setup ran),
|
|
36
|
+
* otherwise it falls back to the bundled examples in the package.
|
|
37
|
+
*
|
|
38
|
+
* @param exampleName - The name of the example to clone (e.g., 'basic-app', 'basic-studio')
|
|
39
|
+
* @param options - Configuration options
|
|
40
|
+
* @returns The absolute path to the temporary directory containing the example
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* import {testExample} from '@sanity/cli-test'
|
|
45
|
+
* import {describe, test} from 'vitest'
|
|
46
|
+
*
|
|
47
|
+
* describe('my test suite', () => {
|
|
48
|
+
* test('should work with basic-studio', async () => {
|
|
49
|
+
* const cwd = await testExample('basic-studio')
|
|
50
|
+
* // ... run your tests in this directory
|
|
51
|
+
* })
|
|
52
|
+
* })
|
|
53
|
+
* ```
|
|
54
|
+
*/ export async function testExample(exampleName, options = {}) {
|
|
55
|
+
const { tempDir } = options;
|
|
56
|
+
const tempDirectory = getTempPath(tempDir);
|
|
57
|
+
// Examples are cloned in the tmp directory by the setup function
|
|
58
|
+
let tempExamplePath = join(tempDirectory, `example-${exampleName}`);
|
|
59
|
+
try {
|
|
60
|
+
const stats = await stat(tempExamplePath);
|
|
61
|
+
if (!stats.isDirectory()) {
|
|
62
|
+
throw new Error(`${tempExamplePath} is not a directory`);
|
|
63
|
+
}
|
|
64
|
+
} catch (e) {
|
|
65
|
+
// If the cloned example doesn't exist, copy from the bundled examples
|
|
66
|
+
if (e.code === 'ENOENT') {
|
|
67
|
+
tempExamplePath = join(getExamplesPath(), exampleName);
|
|
68
|
+
} else {
|
|
69
|
+
throw e;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const tempId = randomBytes(8).toString('hex');
|
|
73
|
+
const tempPath = join(tempDirectory, `example-${exampleName}-${tempId}`);
|
|
74
|
+
// Always skip node_modules (will be symlinked), dist (tests build if needed), and tmp
|
|
75
|
+
const skipDirs = [
|
|
76
|
+
'node_modules',
|
|
77
|
+
'dist',
|
|
78
|
+
'tmp'
|
|
79
|
+
];
|
|
80
|
+
// Copy the example to the temp directory
|
|
81
|
+
await testCopyDirectory(tempExamplePath, tempPath, skipDirs);
|
|
82
|
+
// Symlink the node_modules directory for performance
|
|
83
|
+
await symlink(join(tempExamplePath, 'node_modules'), join(tempPath, 'node_modules'));
|
|
84
|
+
// Replace the package.json name with a temp name
|
|
85
|
+
const packageJsonPath = join(tempPath, 'package.json');
|
|
86
|
+
const packageJson = await readFile(packageJsonPath, 'utf8');
|
|
87
|
+
const packageJsonData = JSON.parse(packageJson);
|
|
88
|
+
packageJsonData.name = `${packageJsonData.name}-${tempId}`;
|
|
89
|
+
await writeFile(packageJsonPath, JSON.stringify(packageJsonData, null, 2));
|
|
90
|
+
return tempPath;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
//# sourceMappingURL=testExample.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/test/testExample.ts"],"sourcesContent":["import {randomBytes} from 'node:crypto'\nimport {copyFile, mkdir, readdir, readFile, stat, symlink, writeFile} from 'node:fs/promises'\nimport {join} from 'node:path'\n\nimport {getExamplesPath, getTempPath} from '../utils/paths.js'\nimport {type ExampleName} from './constants.js'\n\n/**\n * Recursively copy a directory, skipping specified folders.\n *\n * @param srcDir - Source directory to copy from\n * @param destDir - Destination directory to copy to\n * @param skip - Array of directory/file names to skip (e.g., ['node_modules', 'dist'])\n * @internal\n */\nexport async function testCopyDirectory(\n srcDir: string,\n destDir: string,\n skip: string[] = [],\n): Promise<void> {\n await mkdir(destDir, {recursive: true})\n\n const entries = await readdir(srcDir)\n\n for (const entry of entries) {\n if (skip.includes(entry)) {\n continue\n }\n\n const srcPath = join(srcDir, entry)\n const destPath = join(destDir, entry)\n\n const stats = await stat(srcPath)\n\n await (stats.isDirectory()\n ? testCopyDirectory(srcPath, destPath, skip)\n : copyFile(srcPath, destPath))\n }\n}\n\n/** Options for testExample */\nexport interface TestExampleOptions {\n /**\n * Custom temp directory. Defaults to process.cwd()/tmp\n */\n tempDir?: string\n}\n\n/**\n * Clones an example directory into a temporary directory with an isolated copy.\n *\n * The function creates a unique temporary copy of the specified example with:\n * - A random unique ID to avoid conflicts between parallel tests\n * - Symlinked node_modules for performance (from the global setup version)\n * - Modified package.json name to prevent conflicts\n *\n * The example is first looked up in the temp directory (if global setup ran),\n * otherwise it falls back to the bundled examples in the package.\n *\n * @param exampleName - The name of the example to clone (e.g., 'basic-app', 'basic-studio')\n * @param options - Configuration options\n * @returns The absolute path to the temporary directory containing the example\n *\n * @example\n * ```typescript\n * import {testExample} from '@sanity/cli-test'\n * import {describe, test} from 'vitest'\n *\n * describe('my test suite', () => {\n * test('should work with basic-studio', async () => {\n * const cwd = await testExample('basic-studio')\n * // ... run your tests in this directory\n * })\n * })\n * ```\n */\nexport async function testExample(\n exampleName: ExampleName | (string & {}),\n options: TestExampleOptions = {},\n): Promise<string> {\n const {tempDir} = options\n\n const tempDirectory = getTempPath(tempDir)\n\n // Examples are cloned in the tmp directory by the setup function\n let tempExamplePath = join(tempDirectory, `example-${exampleName}`)\n\n try {\n const stats = await stat(tempExamplePath)\n if (!stats.isDirectory()) {\n throw new Error(`${tempExamplePath} is not a directory`)\n }\n } catch (e) {\n // If the cloned example doesn't exist, copy from the bundled examples\n if ((e as NodeJS.ErrnoException).code === 'ENOENT') {\n tempExamplePath = join(getExamplesPath(), exampleName)\n } else {\n throw e\n }\n }\n\n const tempId = randomBytes(8).toString('hex')\n const tempPath = join(tempDirectory, `example-${exampleName}-${tempId}`)\n\n // Always skip node_modules (will be symlinked), dist (tests build if needed), and tmp\n const skipDirs = ['node_modules', 'dist', 'tmp']\n\n // Copy the example to the temp directory\n await testCopyDirectory(tempExamplePath, tempPath, skipDirs)\n\n // Symlink the node_modules directory for performance\n await symlink(join(tempExamplePath, 'node_modules'), join(tempPath, 'node_modules'))\n\n // Replace the package.json name with a temp name\n const packageJsonPath = join(tempPath, 'package.json')\n const packageJson = await readFile(packageJsonPath, 'utf8')\n const packageJsonData = JSON.parse(packageJson)\n packageJsonData.name = `${packageJsonData.name}-${tempId}`\n await writeFile(packageJsonPath, JSON.stringify(packageJsonData, null, 2))\n\n return tempPath\n}\n"],"names":["randomBytes","copyFile","mkdir","readdir","readFile","stat","symlink","writeFile","join","getExamplesPath","getTempPath","testCopyDirectory","srcDir","destDir","skip","recursive","entries","entry","includes","srcPath","destPath","stats","isDirectory","testExample","exampleName","options","tempDir","tempDirectory","tempExamplePath","Error","e","code","tempId","toString","tempPath","skipDirs","packageJsonPath","packageJson","packageJsonData","JSON","parse","name","stringify"],"mappings":"AAAA,SAAQA,WAAW,QAAO,cAAa;AACvC,SAAQC,QAAQ,EAAEC,KAAK,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,OAAO,EAAEC,SAAS,QAAO,mBAAkB;AAC7F,SAAQC,IAAI,QAAO,YAAW;AAE9B,SAAQC,eAAe,EAAEC,WAAW,QAAO,oBAAmB;AAG9D;;;;;;;CAOC,GACD,OAAO,eAAeC,kBACpBC,MAAc,EACdC,OAAe,EACfC,OAAiB,EAAE;IAEnB,MAAMZ,MAAMW,SAAS;QAACE,WAAW;IAAI;IAErC,MAAMC,UAAU,MAAMb,QAAQS;IAE9B,KAAK,MAAMK,SAASD,QAAS;QAC3B,IAAIF,KAAKI,QAAQ,CAACD,QAAQ;YACxB;QACF;QAEA,MAAME,UAAUX,KAAKI,QAAQK;QAC7B,MAAMG,WAAWZ,KAAKK,SAASI;QAE/B,MAAMI,QAAQ,MAAMhB,KAAKc;QAEzB,MAAOE,CAAAA,MAAMC,WAAW,KACpBX,kBAAkBQ,SAASC,UAAUN,QACrCb,SAASkB,SAASC,SAAQ;IAChC;AACF;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,eAAeG,YACpBC,WAAwC,EACxCC,UAA8B,CAAC,CAAC;IAEhC,MAAM,EAACC,OAAO,EAAC,GAAGD;IAElB,MAAME,gBAAgBjB,YAAYgB;IAElC,iEAAiE;IACjE,IAAIE,kBAAkBpB,KAAKmB,eAAe,CAAC,QAAQ,EAAEH,aAAa;IAElE,IAAI;QACF,MAAMH,QAAQ,MAAMhB,KAAKuB;QACzB,IAAI,CAACP,MAAMC,WAAW,IAAI;YACxB,MAAM,IAAIO,MAAM,GAAGD,gBAAgB,mBAAmB,CAAC;QACzD;IACF,EAAE,OAAOE,GAAG;QACV,sEAAsE;QACtE,IAAI,AAACA,EAA4BC,IAAI,KAAK,UAAU;YAClDH,kBAAkBpB,KAAKC,mBAAmBe;QAC5C,OAAO;YACL,MAAMM;QACR;IACF;IAEA,MAAME,SAAShC,YAAY,GAAGiC,QAAQ,CAAC;IACvC,MAAMC,WAAW1B,KAAKmB,eAAe,CAAC,QAAQ,EAAEH,YAAY,CAAC,EAAEQ,QAAQ;IAEvE,sFAAsF;IACtF,MAAMG,WAAW;QAAC;QAAgB;QAAQ;KAAM;IAEhD,yCAAyC;IACzC,MAAMxB,kBAAkBiB,iBAAiBM,UAAUC;IAEnD,qDAAqD;IACrD,MAAM7B,QAAQE,KAAKoB,iBAAiB,iBAAiBpB,KAAK0B,UAAU;IAEpE,iDAAiD;IACjD,MAAME,kBAAkB5B,KAAK0B,UAAU;IACvC,MAAMG,cAAc,MAAMjC,SAASgC,iBAAiB;IACpD,MAAME,kBAAkBC,KAAKC,KAAK,CAACH;IACnCC,gBAAgBG,IAAI,GAAG,GAAGH,gBAAgBG,IAAI,CAAC,CAAC,EAAET,QAAQ;IAC1D,MAAMzB,UAAU6B,iBAAiBG,KAAKG,SAAS,CAACJ,iBAAiB,MAAM;IAEvE,OAAOJ;AACT"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checks if a file exists and can be "accessed".
|
|
3
|
+
* Prone to race conditions, but good enough for our use cases.
|
|
4
|
+
*
|
|
5
|
+
* @param filePath - The path to the file to check
|
|
6
|
+
* @returns A promise that resolves to true if the file exists, false otherwise
|
|
7
|
+
* @internal
|
|
8
|
+
*/
|
|
9
|
+
export declare function fileExists(filePath: string): Promise<boolean>;
|