filesystem-sandbox 1.22.0 → 1.23.0

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/LICENSE CHANGED
@@ -1,29 +1,29 @@
1
- BSD 3-Clause License
2
-
3
- Copyright (c) 2020, Davyd McColl
4
- All rights reserved.
5
-
6
- Redistribution and use in source and binary forms, with or without
7
- modification, are permitted provided that the following conditions are met:
8
-
9
- 1. Redistributions of source code must retain the above copyright notice, this
10
- list of conditions and the following disclaimer.
11
-
12
- 2. Redistributions in binary form must reproduce the above copyright notice,
13
- this list of conditions and the following disclaimer in the documentation
14
- and/or other materials provided with the distribution.
15
-
16
- 3. Neither the name of the copyright holder nor the names of its
17
- contributors may be used to endorse or promote products derived from
18
- this software without specific prior written permission.
19
-
20
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2020, Davyd McColl
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,74 +1,74 @@
1
- filesystem-sandbox
2
- ---
3
-
4
- ![Test](https://github.com/fluffynuts/filesystem-sandbox/workflows/Tests/badge.svg)
5
-
6
- ![npm](https://img.shields.io/npm/v/filesystem-sandbox)
7
-
8
- JavaScript module to provide (insecure) filesystem sandboxes for testing
9
-
10
- ## Why?
11
- Because I've needed to write tests which do file I/O and I want an easy
12
- way to do that and clean up afterwards.
13
-
14
- ## Usage
15
- ### Creation
16
- ```typescript
17
- // create a sandbox in a folder under your repo dir:
18
- const sandbox1 = await Sandbox.create();
19
-
20
- // create a sandbox somehere specific
21
- const sandbox2 = await Sandbox.create("/tmp");
22
- ```
23
-
24
- ### Cleanup
25
- ```typescript
26
- const sandbox1 = await Sandbox.create();
27
- const sandbox2 = await Sandbox.create();
28
- const sandbox3 = await Sandbox.create();
29
-
30
- // clean up an individual sandbox
31
- await sandbox1.destroy();
32
-
33
- // clean up all sandboxes seen in this session, eg in `afterEach`
34
- await Sandbox.destroyAll();
35
-
36
- // precautionary: destroy any sandboxes in the default location
37
- // -> useful as a beforeAll in single test (beware using in jest
38
- // with concurrent testing!) or in your jest setup to clean
39
- // out remnants from prior interrupted sessions. Will not destroy
40
- // sandboxes in custom locations
41
- await Sandbox.destroyAny();
42
- ```
43
-
44
- ### Path resolution
45
- ```typescript
46
- // get the full path to a file for operations not catered for
47
- // by the sandbox:
48
- const sandbox = await Sandbox.create();
49
- const fullpath = sandbox.fullPathFor("some-file.txt");
50
- ```
51
-
52
- ### File I/O
53
- ```typescript
54
- const sandbox = Sandbox.create();
55
- // write a binary file
56
- const buf1 = Buffer.from([1,2,3]);
57
- await sandbox.writeFile("binary.blob", buf1);
58
- // write a text file
59
- await sandbox.writeFile("hello.txt", "hello world");
60
- // read a text file
61
- const text = await sandbox.readTextFile("hello.txt");
62
- // read a binary file
63
- const data = await sandbox.readFile("binary.blob");
64
- ```
65
-
66
- ## File operations
67
- ```typescript
68
- const sandbox = Sandbox.create();
69
- sandbox.writeFile("hello.txt", "hello world");
70
- const exists = await sandbox.fileExists("hello.txt"); // true
71
- const missing = await sandbox.folderExists("hello.txt"); // false: hello.txt is a file
72
- const stat = await sandbox.stat("hello.txt"); // get fulll stat info
73
- const noStats = await sandbox.stat("missing"); // you'll get null
74
- ```
1
+ filesystem-sandbox
2
+ ---
3
+
4
+ ![Test](https://github.com/fluffynuts/filesystem-sandbox/workflows/Tests/badge.svg)
5
+
6
+ ![npm](https://img.shields.io/npm/v/filesystem-sandbox)
7
+
8
+ JavaScript module to provide (insecure) filesystem sandboxes for testing
9
+
10
+ ## Why?
11
+ Because I've needed to write tests which do file I/O and I want an easy
12
+ way to do that and clean up afterwards.
13
+
14
+ ## Usage
15
+ ### Creation
16
+ ```typescript
17
+ // create a sandbox in a folder under your repo dir:
18
+ const sandbox1 = await Sandbox.create();
19
+
20
+ // create a sandbox somehere specific
21
+ const sandbox2 = await Sandbox.create("/tmp");
22
+ ```
23
+
24
+ ### Cleanup
25
+ ```typescript
26
+ const sandbox1 = await Sandbox.create();
27
+ const sandbox2 = await Sandbox.create();
28
+ const sandbox3 = await Sandbox.create();
29
+
30
+ // clean up an individual sandbox
31
+ await sandbox1.destroy();
32
+
33
+ // clean up all sandboxes seen in this session, eg in `afterEach`
34
+ await Sandbox.destroyAll();
35
+
36
+ // precautionary: destroy any sandboxes in the default location
37
+ // -> useful as a beforeAll in single test (beware using in jest
38
+ // with concurrent testing!) or in your jest setup to clean
39
+ // out remnants from prior interrupted sessions. Will not destroy
40
+ // sandboxes in custom locations
41
+ await Sandbox.destroyAny();
42
+ ```
43
+
44
+ ### Path resolution
45
+ ```typescript
46
+ // get the full path to a file for operations not catered for
47
+ // by the sandbox:
48
+ const sandbox = await Sandbox.create();
49
+ const fullpath = sandbox.fullPathFor("some-file.txt");
50
+ ```
51
+
52
+ ### File I/O
53
+ ```typescript
54
+ const sandbox = Sandbox.create();
55
+ // write a binary file
56
+ const buf1 = Buffer.from([1,2,3]);
57
+ await sandbox.writeFile("binary.blob", buf1);
58
+ // write a text file
59
+ await sandbox.writeFile("hello.txt", "hello world");
60
+ // read a text file
61
+ const text = await sandbox.readTextFile("hello.txt");
62
+ // read a binary file
63
+ const data = await sandbox.readFile("binary.blob");
64
+ ```
65
+
66
+ ## File operations
67
+ ```typescript
68
+ const sandbox = Sandbox.create();
69
+ sandbox.writeFile("hello.txt", "hello world");
70
+ const exists = await sandbox.fileExists("hello.txt"); // true
71
+ const missing = await sandbox.folderExists("hello.txt"); // false: hello.txt is a file
72
+ const stat = await sandbox.stat("hello.txt"); // get fulll stat info
73
+ const noStats = await sandbox.stat("missing"); // you'll get null
74
+ ```
@@ -1,44 +1,57 @@
1
- /// <reference types="node" />
2
- import { StatsBase } from "fs";
3
- export declare type Func<T> = () => T;
4
- export declare type AsyncFunc<T> = () => Promise<T>;
5
- export declare const basePrefix = "__sandboxes__";
6
- export declare class Sandbox {
7
- private readonly _path;
8
- private readonly _base;
9
- private readonly _at;
10
- get path(): string;
11
- constructor(at?: string);
12
- destroy(): Promise<void>;
13
- private tryDestroyAt;
14
- private tryDestroyContainer;
15
- private destroyFolderIfEmpty;
16
- private tryDestroySelf;
17
- writeFile(at: string, contents: string | Buffer | string[]): Promise<string>;
18
- appendFile(at: string, contents: string | Buffer | string[]): Promise<string>;
19
- mkdir(name: string): Promise<string>;
20
- private resolveRelativePath;
21
- readTextFile(at: string): Promise<string>;
22
- readFile(at: string): Promise<Buffer>;
23
- fullPathFor(relativePath: string, ...parts: string[]): string;
24
- stat(at: string): Promise<StatsBase<any> | null>;
25
- folderExists(at: string): Promise<boolean>;
26
- fileExists(at: string): Promise<boolean>;
27
- private runOnStat;
28
- run<T>(fn: Func<T> | AsyncFunc<T>, relativePath?: string): Promise<T>;
29
- private _validatePathInsideSandbox;
30
- /**
31
- * Destroys all sandboxes created in this process up until now
32
- */
33
- static destroyAll(): Promise<void>;
34
- /**
35
- * Destroys the default base folder for sandboxes -- useful as a once-off
36
- * run before all tests to ensure that there are no lingering sandboxes
37
- * - cannot destroy sandboxes in custom paths
38
- */
39
- static destroyAny(): Promise<void>;
40
- static create(at?: string): Promise<Sandbox>;
41
- static setBaseTargetToCurrentWorkingDirectory(): Promise<void>;
42
- static setBaseTargetToSystemTempFolder(): Promise<void>;
43
- static setBaseTarget(to: string): Promise<void>;
44
- }
1
+ /// <reference types="node" />
2
+ import { SpawnOptions } from "child_process";
3
+ import { StatsBase } from "fs";
4
+ export declare type Func<T> = () => T;
5
+ export declare type AsyncFunc<T> = () => Promise<T>;
6
+ export declare const basePrefix = "__sandboxes__";
7
+ export declare class Sandbox {
8
+ private readonly _path;
9
+ private readonly _base;
10
+ private readonly _at;
11
+ get path(): string;
12
+ constructor(at?: string);
13
+ destroy(): Promise<void>;
14
+ private tryDestroyAt;
15
+ private tryDestroyContainer;
16
+ private destroyFolderIfEmpty;
17
+ private tryDestroySelf;
18
+ writeFile(at: string, contents: string | Buffer | string[]): Promise<string>;
19
+ appendFile(at: string, contents: string | Buffer | string[]): Promise<string>;
20
+ mkdir(name: string): Promise<string>;
21
+ private resolveRelativePath;
22
+ readTextFile(at: string): Promise<string>;
23
+ readFile(at: string): Promise<Buffer>;
24
+ fullPathFor(relativePath: string, ...parts: string[]): string;
25
+ stat(at: string): Promise<StatsBase<any> | null>;
26
+ folderExists(at: string): Promise<boolean>;
27
+ fileExists(at: string): Promise<boolean>;
28
+ private runOnStat;
29
+ run<T>(fn: Func<T> | AsyncFunc<T>, relativePath?: string): Promise<T>;
30
+ exec(command: string, args?: string[], options?: SpawnOptions): Promise<ProcessData>;
31
+ private _validatePathInsideSandbox;
32
+ /**
33
+ * Destroys all sandboxes created in this process up until now
34
+ */
35
+ static destroyAll(): Promise<void>;
36
+ /**
37
+ * Destroys the default base folder for sandboxes -- useful as a once-off
38
+ * run before all tests to ensure that there are no lingering sandboxes
39
+ * - cannot destroy sandboxes in custom paths
40
+ */
41
+ static destroyAny(): Promise<void>;
42
+ static create(at?: string): Promise<Sandbox>;
43
+ static setBaseTargetToCurrentWorkingDirectory(): Promise<void>;
44
+ static setBaseTargetToSystemTempFolder(): Promise<void>;
45
+ static setBaseTarget(to: string): Promise<void>;
46
+ }
47
+ export interface ProcessData {
48
+ stdout: string[];
49
+ stderr: string[];
50
+ code: number;
51
+ }
52
+ export interface SpawnError extends Error {
53
+ command: string;
54
+ args: string[] | undefined;
55
+ options: SpawnOptions | undefined;
56
+ result: ProcessData;
57
+ }
@@ -1,251 +1,287 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.Sandbox = exports.basePrefix = void 0;
30
- const fs_1 = require("fs");
31
- const os = __importStar(require("os"));
32
- if (!fs_1.promises) {
33
- throw new Error("Yer node is olde! filesystem-sandboxes requires a Node with fs.promises");
34
- }
35
- // require for "path" produces the cleanest js output
36
- const path_1 = __importDefault(require("path"));
37
- const uuid_1 = require("uuid");
38
- const mkdirp_1 = require("mkdirp");
39
- const rimraf_1 = require("rimraf");
40
- const { writeFile, readFile, stat, appendFile } = fs_1.promises;
41
- async function isFolder(p) {
42
- try {
43
- const st = await stat(p);
44
- return st && st.isDirectory();
45
- }
46
- catch (e) {
47
- return false;
48
- }
49
- }
50
- async function readdir(p) {
51
- const exists = await isFolder(p);
52
- if (!exists) {
53
- return [];
54
- }
55
- return await fs_1.promises.readdir(p);
56
- }
57
- async function rimraf(p) {
58
- if (!(await isFolder(p))) {
59
- return;
60
- }
61
- return new Promise((resolve, reject) => {
62
- try {
63
- (0, rimraf_1.sync)(p, { maxBusyTries: 5 });
64
- resolve();
65
- }
66
- catch (e) {
67
- reject(e);
68
- }
69
- });
70
- }
71
- exports.basePrefix = "__sandboxes__";
72
- let baseTarget = os.tmpdir();
73
- const sandboxes = [];
74
- async function writeData(fullPath, contents, writeFunction) {
75
- const options = contents instanceof Buffer
76
- ? undefined
77
- : { encoding: "utf8" };
78
- if (Array.isArray(contents)) {
79
- contents = contents.join("\n");
80
- }
81
- await writeFunction(fullPath, contents, options);
82
- return fullPath;
83
- }
84
- class Sandbox {
85
- constructor(at) {
86
- this._at = at;
87
- this._base = path_1.default.join(at || baseTarget, exports.basePrefix);
88
- this._path = path_1.default.join(this._base, (0, uuid_1.v4)());
89
- (0, mkdirp_1.sync)(this._path);
90
- sandboxes.push(this);
91
- }
92
- get path() {
93
- return this._path;
94
- }
95
- async destroy() {
96
- await this.tryDestroySelf();
97
- await this.tryDestroyContainer();
98
- await this.tryDestroyAt();
99
- }
100
- async tryDestroyAt() {
101
- if (!this._at) {
102
- return;
103
- }
104
- await this.destroyFolderIfEmpty(this._at);
105
- }
106
- async tryDestroyContainer() {
107
- await this.destroyFolderIfEmpty(this._base);
108
- }
109
- async destroyFolderIfEmpty(p) {
110
- const contents = await readdir(p);
111
- if (!contents.length) {
112
- await rimraf(p);
113
- }
114
- }
115
- async tryDestroySelf() {
116
- const myIndex = sandboxes.indexOf(this);
117
- if (myIndex > -1) {
118
- sandboxes.splice(myIndex, 1);
119
- }
120
- await rimraf(this._path);
121
- }
122
- async writeFile(at, contents) {
123
- try {
124
- await this.mkdir(path_1.default.dirname(at));
125
- return await writeData(this.fullPathFor(at), contents, writeFile);
126
- }
127
- catch (e) {
128
- throw new Error(`Unable to write file at ${at}: ${e.message || e}`);
129
- }
130
- }
131
- async appendFile(at, contents) {
132
- try {
133
- await this.mkdir(path_1.default.dirname(at));
134
- return await writeData(this.fullPathFor(at), contents, appendFile);
135
- }
136
- catch (e) {
137
- throw new Error(`Unable to append to file at ${at}: ${e.message || e}`);
138
- }
139
- }
140
- async mkdir(name) {
141
- name = this.resolveRelativePath(name);
142
- return new Promise(async (resolve, reject) => {
143
- const fullpath = path_1.default.join(this._path, name);
144
- if (await isFolder(fullpath)) {
145
- resolve(fullpath);
146
- }
147
- try {
148
- (0, mkdirp_1.sync)(fullpath);
149
- resolve(fullpath);
150
- }
151
- catch (e) {
152
- reject(e);
153
- }
154
- });
155
- }
156
- resolveRelativePath(at) {
157
- if (!path_1.default.isAbsolute(at)) {
158
- return at;
159
- }
160
- const result = path_1.default.relative(this._path, at);
161
- if (result.startsWith("..")) {
162
- throw new Error(`${at} is outside the sandbox at ${this._path}`);
163
- }
164
- return result;
165
- }
166
- async readTextFile(at) {
167
- return readFile(this.fullPathFor(at), { encoding: "utf8" });
168
- }
169
- async readFile(at) {
170
- return readFile(this.fullPathFor(at));
171
- }
172
- fullPathFor(relativePath, ...parts) {
173
- relativePath = this.resolveRelativePath(relativePath);
174
- return path_1.default.join(this._path, relativePath, ...parts);
175
- }
176
- async stat(at) {
177
- at = this.resolveRelativePath(at);
178
- try {
179
- return await fs_1.promises.stat(this.fullPathFor(at));
180
- }
181
- catch (e) {
182
- return null;
183
- }
184
- }
185
- async folderExists(at) {
186
- at = this.resolveRelativePath(at);
187
- return this.runOnStat(at, st => !!st && st.isDirectory());
188
- }
189
- async fileExists(at) {
190
- at = this.resolveRelativePath(at);
191
- return this.runOnStat(at, st => !!st && st.isFile());
192
- }
193
- async runOnStat(relativePath, fn) {
194
- const st = await this.stat(relativePath);
195
- return fn(st);
196
- }
197
- async run(fn, relativePath) {
198
- const start = process.cwd();
199
- try {
200
- const target = relativePath
201
- ? path_1.default.resolve(path_1.default.join(this.path, relativePath))
202
- : this.path;
203
- this._validatePathInsideSandbox(target);
204
- process.chdir(target);
205
- return await fn();
206
- }
207
- finally {
208
- process.chdir(start);
209
- }
210
- }
211
- _validatePathInsideSandbox(t) {
212
- if (t.startsWith(this.path)) {
213
- return;
214
- }
215
- throw new Error(`${t} is not inside sandbox at ${this.path}`);
216
- }
217
- /**
218
- * Destroys all sandboxes created in this process up until now
219
- */
220
- static async destroyAll() {
221
- const toDestroy = sandboxes.splice(0, sandboxes.length);
222
- for (const sandbox of toDestroy) {
223
- await sandbox.destroy();
224
- }
225
- }
226
- /**
227
- * Destroys the default base folder for sandboxes -- useful as a once-off
228
- * run before all tests to ensure that there are no lingering sandboxes
229
- * - cannot destroy sandboxes in custom paths
230
- */
231
- static async destroyAny() {
232
- const target = path_1.default.join(baseTarget, exports.basePrefix);
233
- await rimraf(target);
234
- }
235
- static async create(at) {
236
- return new Sandbox(at);
237
- }
238
- static async setBaseTargetToCurrentWorkingDirectory() {
239
- await this.setBaseTarget(process.cwd());
240
- }
241
- static async setBaseTargetToSystemTempFolder() {
242
- await this.setBaseTarget(os.tmpdir());
243
- }
244
- static async setBaseTarget(to) {
245
- if (!(await isFolder(to))) {
246
- await (0, mkdirp_1.sync)(to);
247
- }
248
- baseTarget = to;
249
- }
250
- }
251
- exports.Sandbox = Sandbox;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.Sandbox = exports.basePrefix = void 0;
30
+ const child_process_1 = require("child_process");
31
+ const fs_1 = require("fs");
32
+ const os = __importStar(require("os"));
33
+ // require for "path" produces the cleanest js output
34
+ const path_1 = __importDefault(require("path"));
35
+ const uuid_1 = require("uuid");
36
+ const mkdirp_1 = require("mkdirp");
37
+ const rimraf_1 = require("rimraf");
38
+ if (!fs_1.promises) {
39
+ throw new Error("Yer node is olde! filesystem-sandboxes requires a Node with fs.promises");
40
+ }
41
+ const { writeFile, readFile, stat, appendFile } = fs_1.promises;
42
+ async function isFolder(p) {
43
+ try {
44
+ const st = await stat(p);
45
+ return st && st.isDirectory();
46
+ }
47
+ catch (e) {
48
+ return false;
49
+ }
50
+ }
51
+ async function readdir(p) {
52
+ const exists = await isFolder(p);
53
+ if (!exists) {
54
+ return [];
55
+ }
56
+ return await fs_1.promises.readdir(p);
57
+ }
58
+ async function rimraf(p) {
59
+ if (!(await isFolder(p))) {
60
+ return;
61
+ }
62
+ return new Promise((resolve, reject) => {
63
+ try {
64
+ (0, rimraf_1.sync)(p, { maxBusyTries: 5 });
65
+ resolve();
66
+ }
67
+ catch (e) {
68
+ reject(e);
69
+ }
70
+ });
71
+ }
72
+ exports.basePrefix = "__sandboxes__";
73
+ let baseTarget = os.tmpdir();
74
+ const sandboxes = [];
75
+ async function writeData(fullPath, contents, writeFunction) {
76
+ const options = contents instanceof Buffer
77
+ ? undefined
78
+ : { encoding: "utf8" };
79
+ if (Array.isArray(contents)) {
80
+ contents = contents.join("\n");
81
+ }
82
+ await writeFunction(fullPath, contents, options);
83
+ return fullPath;
84
+ }
85
+ class Sandbox {
86
+ constructor(at) {
87
+ this._at = at;
88
+ this._base = path_1.default.join(at || baseTarget, exports.basePrefix);
89
+ this._path = path_1.default.join(this._base, (0, uuid_1.v4)());
90
+ (0, mkdirp_1.sync)(this._path);
91
+ sandboxes.push(this);
92
+ }
93
+ get path() {
94
+ return this._path;
95
+ }
96
+ async destroy() {
97
+ await this.tryDestroySelf();
98
+ await this.tryDestroyContainer();
99
+ await this.tryDestroyAt();
100
+ }
101
+ async tryDestroyAt() {
102
+ if (!this._at) {
103
+ return;
104
+ }
105
+ await this.destroyFolderIfEmpty(this._at);
106
+ }
107
+ async tryDestroyContainer() {
108
+ await this.destroyFolderIfEmpty(this._base);
109
+ }
110
+ async destroyFolderIfEmpty(p) {
111
+ const contents = await readdir(p);
112
+ if (!contents.length) {
113
+ await rimraf(p);
114
+ }
115
+ }
116
+ async tryDestroySelf() {
117
+ const myIndex = sandboxes.indexOf(this);
118
+ if (myIndex > -1) {
119
+ sandboxes.splice(myIndex, 1);
120
+ }
121
+ await rimraf(this._path);
122
+ }
123
+ async writeFile(at, contents) {
124
+ try {
125
+ await this.mkdir(path_1.default.dirname(at));
126
+ return await writeData(this.fullPathFor(at), contents, writeFile);
127
+ }
128
+ catch (e) {
129
+ throw new Error(`Unable to write file at ${at}: ${e.message || e}`);
130
+ }
131
+ }
132
+ async appendFile(at, contents) {
133
+ try {
134
+ await this.mkdir(path_1.default.dirname(at));
135
+ return await writeData(this.fullPathFor(at), contents, appendFile);
136
+ }
137
+ catch (e) {
138
+ throw new Error(`Unable to append to file at ${at}: ${e.message || e}`);
139
+ }
140
+ }
141
+ async mkdir(name) {
142
+ name = this.resolveRelativePath(name);
143
+ return new Promise(async (resolve, reject) => {
144
+ const fullpath = path_1.default.join(this._path, name);
145
+ if (await isFolder(fullpath)) {
146
+ resolve(fullpath);
147
+ }
148
+ try {
149
+ (0, mkdirp_1.sync)(fullpath);
150
+ resolve(fullpath);
151
+ }
152
+ catch (e) {
153
+ reject(e);
154
+ }
155
+ });
156
+ }
157
+ resolveRelativePath(at) {
158
+ if (!path_1.default.isAbsolute(at)) {
159
+ return at;
160
+ }
161
+ const result = path_1.default.relative(this._path, at);
162
+ if (result.startsWith("..")) {
163
+ throw new Error(`${at} is outside the sandbox at ${this._path}`);
164
+ }
165
+ return result;
166
+ }
167
+ async readTextFile(at) {
168
+ return readFile(this.fullPathFor(at), { encoding: "utf8" });
169
+ }
170
+ async readFile(at) {
171
+ return readFile(this.fullPathFor(at));
172
+ }
173
+ fullPathFor(relativePath, ...parts) {
174
+ relativePath = this.resolveRelativePath(relativePath);
175
+ return path_1.default.join(this._path, relativePath, ...parts);
176
+ }
177
+ async stat(at) {
178
+ at = this.resolveRelativePath(at);
179
+ try {
180
+ return await fs_1.promises.stat(this.fullPathFor(at));
181
+ }
182
+ catch (e) {
183
+ return null;
184
+ }
185
+ }
186
+ async folderExists(at) {
187
+ at = this.resolveRelativePath(at);
188
+ return this.runOnStat(at, st => !!st && st.isDirectory());
189
+ }
190
+ async fileExists(at) {
191
+ at = this.resolveRelativePath(at);
192
+ return this.runOnStat(at, st => !!st && st.isFile());
193
+ }
194
+ async runOnStat(relativePath, fn) {
195
+ const st = await this.stat(relativePath);
196
+ return fn(st);
197
+ }
198
+ async run(fn, relativePath) {
199
+ const start = process.cwd();
200
+ try {
201
+ const target = relativePath
202
+ ? path_1.default.resolve(path_1.default.join(this.path, relativePath))
203
+ : this.path;
204
+ this._validatePathInsideSandbox(target);
205
+ process.chdir(target);
206
+ return await fn();
207
+ }
208
+ finally {
209
+ process.chdir(start);
210
+ }
211
+ }
212
+ async exec(command, args, options) {
213
+ return await this.run(() => {
214
+ const spawnArgs = args || [], spawnOptions = options || {};
215
+ return new Promise((resolve, reject) => {
216
+ var _a, _b;
217
+ const child = (0, child_process_1.spawn)(command, spawnArgs, spawnOptions), result = {
218
+ stdout: [],
219
+ stderr: [],
220
+ code: -1
221
+ };
222
+ (_a = child.stderr) === null || _a === void 0 ? void 0 : _a.on("data", d => {
223
+ result.stderr.push(d.toString());
224
+ });
225
+ (_b = child.stdout) === null || _b === void 0 ? void 0 : _b.on("data", d => {
226
+ result.stdout.push(d.toString());
227
+ });
228
+ child.on("close", code => {
229
+ result.code = code;
230
+ return code
231
+ ? reject(makeSpawnErrorFor(result, command, args, options))
232
+ : resolve(result);
233
+ });
234
+ });
235
+ });
236
+ }
237
+ _validatePathInsideSandbox(t) {
238
+ if (t.startsWith(this.path)) {
239
+ return;
240
+ }
241
+ throw new Error(`${t} is not inside sandbox at ${this.path}`);
242
+ }
243
+ /**
244
+ * Destroys all sandboxes created in this process up until now
245
+ */
246
+ static async destroyAll() {
247
+ const toDestroy = sandboxes.splice(0, sandboxes.length);
248
+ for (const sandbox of toDestroy) {
249
+ await sandbox.destroy();
250
+ }
251
+ }
252
+ /**
253
+ * Destroys the default base folder for sandboxes -- useful as a once-off
254
+ * run before all tests to ensure that there are no lingering sandboxes
255
+ * - cannot destroy sandboxes in custom paths
256
+ */
257
+ static async destroyAny() {
258
+ const target = path_1.default.join(baseTarget, exports.basePrefix);
259
+ await rimraf(target);
260
+ }
261
+ static async create(at) {
262
+ return new Sandbox(at);
263
+ }
264
+ static async setBaseTargetToCurrentWorkingDirectory() {
265
+ await this.setBaseTarget(process.cwd());
266
+ }
267
+ static async setBaseTargetToSystemTempFolder() {
268
+ await this.setBaseTarget(os.tmpdir());
269
+ }
270
+ static async setBaseTarget(to) {
271
+ if (!(await isFolder(to))) {
272
+ await (0, mkdirp_1.sync)(to);
273
+ }
274
+ baseTarget = to;
275
+ }
276
+ }
277
+ exports.Sandbox = Sandbox;
278
+ function makeSpawnErrorFor(result, command, args, options) {
279
+ const e = new Error(`Error exit code ${result.code} for: ${command} ${(args || []).join(" ")}`);
280
+ return {
281
+ ...e,
282
+ result,
283
+ command,
284
+ args,
285
+ options
286
+ };
287
+ }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from "./filesystem-sandbox";
2
- export * from "./index";
1
+ export * from "./filesystem-sandbox";
2
+ export * from "./index";
package/dist/index.js CHANGED
@@ -1,19 +1,19 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- // this is a generated file: do not edit
18
- __exportStar(require("./filesystem-sandbox"), exports);
19
- __exportStar(require("./index"), exports);
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ // this is a generated file: do not edit
18
+ __exportStar(require("./filesystem-sandbox"), exports);
19
+ __exportStar(require("./index"), exports);
package/index.d.ts CHANGED
@@ -1 +1 @@
1
- export * from "./dist";
1
+ export * from "./dist";
package/index.js CHANGED
@@ -1 +1 @@
1
- module.exports = require("./dist");
1
+ module.exports = require("./dist");
package/package.json CHANGED
@@ -1,64 +1,65 @@
1
- {
2
- "name": "filesystem-sandbox",
3
- "version": "1.22.0",
4
- "description": "JavaScript module to provide filesystem sandboxes for testing",
5
- "main": "index.js",
6
- "types": "index.d.ts",
7
- "files": [
8
- "dist/**/*",
9
- "index.js",
10
- "index.d.ts"
11
- ],
12
- "scripts": {
13
- "test": "jest",
14
- "prebuild": "run-p clean-dist generate-index",
15
- "clean-dist": "rimraf dist",
16
- "generate-index": "node generate-index.js",
17
- "build": "run-p tsc lint",
18
- "autobuild": "nodemon -V -w src -w tests -e ts -x \"run-s -s build autobuild-message\"",
19
- "autobuild-message": "node -e \"console.log('Auto-build completed', new Date());\"",
20
- "lint": "tslint -p .",
21
- "increment-package-version-beta": "cross-env VERSION_INCREMENT_STRATEGY=patch run-s \"zarro increment-package-json-version\"",
22
- "prerelease-beta": "run-s build test",
23
- "release-beta": "cross-env BETA=1 VERSION_INCREMENT_STRATEGY=patch run-s \"zarro release-npm\"",
24
- "prerelease": "run-s build test",
25
- "release": "cross-env VERSION_INCREMENT_STRATEGY=minor run-s \"zarro release-npm\"",
26
- "tsc": "tsc",
27
- "zarro": "zarro"
28
- },
29
- "repository": {
30
- "type": "git",
31
- "url": "git+ssh://git@github.com/fluffynuts/filesystem-sandbox.git"
32
- },
33
- "keywords": [],
34
- "author": "",
35
- "license": "ISC",
36
- "bugs": {
37
- "url": "https://github.com/fluffynuts/filesystem-sandbox/issues"
38
- },
39
- "homepage": "https://github.com/fluffynuts/filesystem-sandbox#readme",
40
- "devDependencies": {
41
- "@faker-js/faker": "^6.0.0",
42
- "@types/jest": "^25.2.3",
43
- "@types/lodash": "^4.14.153",
44
- "@types/mkdirp": "^1.0.0",
45
- "@types/node": "^14.0.5",
46
- "@types/rimraf": "^3.0.0",
47
- "@types/uuid": "^8.0.0",
48
- "eslint": "^7.1.0",
49
- "expect-even-more-jest": "^1.0.0",
50
- "expect-more-jest": "^5.1.0",
51
- "jest": "^27.5.1",
52
- "lodash": "^4.17.15",
53
- "nodemon": "^2.0.4",
54
- "ts-jest": "^27.1.3",
55
- "tslint": "^6.1.2",
56
- "typescript": "^4.6.2",
57
- "zarro": "^1.99.0"
58
- },
59
- "dependencies": {
60
- "mkdirp": "^1.0.4",
61
- "rimraf": "^3.0.2",
62
- "uuid": "^8.1.0"
63
- }
1
+ {
2
+ "name": "filesystem-sandbox",
3
+ "version": "1.23.0",
4
+ "description": "JavaScript module to provide filesystem sandboxes for testing",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "files": [
8
+ "dist/**/*",
9
+ "index.js",
10
+ "index.d.ts"
11
+ ],
12
+ "scripts": {
13
+ "test": "jest",
14
+ "prebuild": "run-p clean-dist generate-index",
15
+ "clean-dist": "rimraf dist",
16
+ "generate-index": "node generate-index.js",
17
+ "build": "run-p tsc lint",
18
+ "autobuild": "nodemon -V -w src -w tests -e ts -x \"run-s -s build autobuild-message\"",
19
+ "autobuild-message": "node -e \"console.log('Auto-build completed', new Date());\"",
20
+ "lint": "tslint -p .",
21
+ "increment-package-version-beta": "cross-env VERSION_INCREMENT_STRATEGY=patch run-s \"zarro increment-package-json-version\"",
22
+ "prerelease-beta": "run-s build test",
23
+ "release-beta": "cross-env BETA=1 VERSION_INCREMENT_STRATEGY=patch run-s \"zarro release-npm\"",
24
+ "prerelease": "run-s build test",
25
+ "release": "cross-env VERSION_INCREMENT_STRATEGY=minor run-s \"zarro release-npm\"",
26
+ "tsc": "tsc",
27
+ "zarro": "zarro"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+ssh://git@github.com/fluffynuts/filesystem-sandbox.git"
32
+ },
33
+ "keywords": [],
34
+ "author": "",
35
+ "license": "ISC",
36
+ "bugs": {
37
+ "url": "https://github.com/fluffynuts/filesystem-sandbox/issues"
38
+ },
39
+ "homepage": "https://github.com/fluffynuts/filesystem-sandbox#readme",
40
+ "devDependencies": {
41
+ "@faker-js/faker": "^6.0.0",
42
+ "@types/jest": "^25.2.3",
43
+ "@types/lodash": "^4.14.153",
44
+ "@types/mkdirp": "^1.0.0",
45
+ "@types/node": "^14.0.5",
46
+ "@types/rimraf": "^3.0.0",
47
+ "@types/uuid": "^8.0.0",
48
+ "eslint": "^7.1.0",
49
+ "expect-even-more-jest": "^1.0.0",
50
+ "expect-more-jest": "^5.1.0",
51
+ "jest": "^28.1.1",
52
+ "lodash": "^4.17.15",
53
+ "nodemon": "^2.0.4",
54
+ "ts-jest": "^28.0.4",
55
+ "tslint": "^6.1.2",
56
+ "typescript": "^4.6.2",
57
+ "yafs": "^1.23.0",
58
+ "zarro": "^1.99.0"
59
+ },
60
+ "dependencies": {
61
+ "mkdirp": "^1.0.4",
62
+ "rimraf": "^3.0.2",
63
+ "uuid": "^8.1.0"
64
+ }
64
65
  }