@atlaspack/fs 2.15.25 → 2.15.27-dev-ts-project-refs-d30e9754f.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.
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NodeFS = void 0;
4
+ // @ts-expect-error TS2420
5
+ class NodeFS {
6
+ constructor() {
7
+ throw new Error("NodeFS isn't available in the browser");
8
+ }
9
+ }
10
+ exports.NodeFS = NodeFS;
package/dist/NodeFS.js ADDED
@@ -0,0 +1,251 @@
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 () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.NodeFS = void 0;
40
+ // @ts-expect-error TS7016
41
+ const graceful_fs_1 = __importDefault(require("graceful-fs"));
42
+ const fs_1 = __importDefault(require("fs"));
43
+ // @ts-expect-error TS7016
44
+ const ncp_1 = __importDefault(require("ncp"));
45
+ const path_1 = __importDefault(require("path"));
46
+ const os_1 = require("os");
47
+ const util_1 = require("util");
48
+ const build_cache_1 = require("@atlaspack/build-cache");
49
+ const feature_flags_1 = require("@atlaspack/feature-flags");
50
+ const watcher_1 = __importDefault(require("@parcel/watcher"));
51
+ const package_json_1 = __importDefault(require("../package.json"));
52
+ const searchNative = __importStar(require("@atlaspack/rust"));
53
+ const searchJS = __importStar(require("./find"));
54
+ // Most of this can go away once we only support Node 10+, which includes
55
+ // require('fs').promises
56
+ const realpath = (0, util_1.promisify)(process.platform === 'win32' ? graceful_fs_1.default.realpath : graceful_fs_1.default.realpath.native);
57
+ const isPnP = process.versions.pnp != null;
58
+ function getWatchmanWatcher() {
59
+ // This is here to trick atlaspack into ignoring this require...
60
+ const packageName = ['@atlaspack', 'watcher-watchman-js'].join('/');
61
+ return require(packageName);
62
+ }
63
+ class NodeFS {
64
+ constructor() {
65
+ this.readFile = (0, util_1.promisify)(graceful_fs_1.default.readFile);
66
+ this.copyFile = (0, util_1.promisify)(graceful_fs_1.default.copyFile);
67
+ this.stat = (0, util_1.promisify)(graceful_fs_1.default.stat);
68
+ this.readdir = (0, util_1.promisify)(graceful_fs_1.default.readdir);
69
+ this.symlink = (0, util_1.promisify)(graceful_fs_1.default.symlink);
70
+ this.unlink = (0, util_1.promisify)(graceful_fs_1.default.unlink);
71
+ this.utimes = (0, util_1.promisify)(graceful_fs_1.default.utimes);
72
+ this.ncp = (0, util_1.promisify)(ncp_1.default);
73
+ this.createReadStream = graceful_fs_1.default.createReadStream;
74
+ this.cwd = () => process.cwd();
75
+ this.chdir = (directory) => process.chdir(directory);
76
+ this.statSync = (path) => graceful_fs_1.default.statSync(path);
77
+ this.realpathSync = process.platform === 'win32' ? graceful_fs_1.default.realpathSync : graceful_fs_1.default.realpathSync.native;
78
+ this.existsSync = graceful_fs_1.default.existsSync;
79
+ this.readdirSync = graceful_fs_1.default.readdirSync;
80
+ this.findAncestorFile = isPnP
81
+ ? // @ts-expect-error TS7019
82
+ (...args) => searchJS.findAncestorFile(this, ...args)
83
+ : searchNative.findAncestorFile;
84
+ this.findNodeModule = isPnP
85
+ ? // @ts-expect-error TS7019
86
+ (...args) => searchJS.findNodeModule(this, ...args)
87
+ : searchNative.findNodeModule;
88
+ this.findFirstFile = isPnP
89
+ ? // @ts-expect-error TS7019
90
+ (...args) => searchJS.findFirstFile(this, ...args)
91
+ : searchNative.findFirstFile;
92
+ }
93
+ watcher() {
94
+ return (0, feature_flags_1.getFeatureFlag)('useWatchmanWatcher')
95
+ ? getWatchmanWatcher()
96
+ : watcher_1.default;
97
+ }
98
+ createWriteStream(filePath, options) {
99
+ // Make createWriteStream atomic
100
+ let tmpFilePath = getTempFilePath(filePath);
101
+ let failed = false;
102
+ const move = async () => {
103
+ if (!failed) {
104
+ await graceful_fs_1.default.promises.rename(tmpFilePath, filePath);
105
+ }
106
+ };
107
+ let writeStream = graceful_fs_1.default.createWriteStream(tmpFilePath, {
108
+ ...options,
109
+ fs: {
110
+ ...graceful_fs_1.default,
111
+ // @ts-expect-error TS7006
112
+ close: (fd, cb) => {
113
+ // @ts-expect-error TS7006
114
+ graceful_fs_1.default.close(fd, (err) => {
115
+ if (err) {
116
+ cb(err);
117
+ }
118
+ else {
119
+ move().then(() => cb(), (err) => cb(err));
120
+ }
121
+ });
122
+ },
123
+ },
124
+ });
125
+ writeStream.once('error', () => {
126
+ failed = true;
127
+ try {
128
+ graceful_fs_1.default.unlinkSync(tmpFilePath);
129
+ }
130
+ catch (_err) {
131
+ // ignore
132
+ }
133
+ });
134
+ return writeStream;
135
+ }
136
+ async writeFile(filePath, contents, options) {
137
+ let tmpFilePath = getTempFilePath(filePath);
138
+ await graceful_fs_1.default.promises.writeFile(tmpFilePath, contents, options);
139
+ await graceful_fs_1.default.promises.rename(tmpFilePath, filePath);
140
+ }
141
+ readFileSync(filePath, encoding) {
142
+ if (encoding != null) {
143
+ return graceful_fs_1.default.readFileSync(filePath, encoding);
144
+ }
145
+ return graceful_fs_1.default.readFileSync(filePath);
146
+ }
147
+ async realpath(originalPath) {
148
+ try {
149
+ return await realpath(originalPath, 'utf8');
150
+ }
151
+ catch (e) {
152
+ // do nothing
153
+ }
154
+ return originalPath;
155
+ }
156
+ exists(filePath) {
157
+ return new Promise((resolve) => {
158
+ graceful_fs_1.default.exists(filePath, resolve);
159
+ });
160
+ }
161
+ watch(dir, fn, opts) {
162
+ return this.watcher().subscribe(dir, fn, opts);
163
+ }
164
+ getEventsSince(dir, snapshot, opts) {
165
+ return this.watcher().getEventsSince(dir, snapshot, opts);
166
+ }
167
+ async writeSnapshot(dir, snapshot, opts) {
168
+ await this.mkdirp(path_1.default.dirname(snapshot));
169
+ await this.watcher().writeSnapshot(dir, snapshot, opts);
170
+ }
171
+ static deserialize() {
172
+ return new NodeFS();
173
+ }
174
+ serialize() {
175
+ return null;
176
+ }
177
+ async mkdirp(filePath) {
178
+ await fs_1.default.promises.mkdir(filePath, { recursive: true });
179
+ }
180
+ async rimraf(filePath) {
181
+ if (graceful_fs_1.default.promises.rm) {
182
+ await graceful_fs_1.default.promises.rm(filePath, { recursive: true, force: true });
183
+ return;
184
+ }
185
+ // fs.promises.rm is not supported in node 12...
186
+ let stat;
187
+ try {
188
+ stat = await this.stat(filePath);
189
+ }
190
+ catch (err) {
191
+ return;
192
+ }
193
+ if (stat.isDirectory()) {
194
+ await fs_1.default.promises.rmdir(filePath, { recursive: true });
195
+ }
196
+ else {
197
+ await fs_1.default.promises.unlink(filePath);
198
+ }
199
+ }
200
+ }
201
+ exports.NodeFS = NodeFS;
202
+ (0, build_cache_1.registerSerializableClass)(`${package_json_1.default.version}:NodeFS`, NodeFS);
203
+ let writeStreamCalls = 0;
204
+ // @ts-expect-error TS7034
205
+ let threadId;
206
+ try {
207
+ ({ threadId } = require('worker_threads'));
208
+ }
209
+ catch {
210
+ //
211
+ }
212
+ // @ts-expect-error TS7034
213
+ let useOsTmpDir;
214
+ function shouldUseOsTmpDir(filePath) {
215
+ // @ts-expect-error TS7005
216
+ if (useOsTmpDir != null) {
217
+ // @ts-expect-error TS7005
218
+ return useOsTmpDir;
219
+ }
220
+ try {
221
+ const tmpDir = (0, os_1.tmpdir)();
222
+ fs_1.default.accessSync(tmpDir, fs_1.default.constants.R_OK | fs_1.default.constants.W_OK);
223
+ const tmpDirStats = fs_1.default.statSync(tmpDir);
224
+ const filePathStats = fs_1.default.statSync(filePath);
225
+ // Check the tmpdir is on the same partition as the target directory.
226
+ // This is required to ensure renaming is an atomic operation.
227
+ useOsTmpDir = tmpDirStats.dev === filePathStats.dev;
228
+ }
229
+ catch (e) {
230
+ // We don't have read/write access to the OS tmp directory
231
+ useOsTmpDir = false;
232
+ }
233
+ return useOsTmpDir;
234
+ }
235
+ // Generate a temporary file path used for atomic writing of files.
236
+ function getTempFilePath(filePath) {
237
+ writeStreamCalls = writeStreamCalls % Number.MAX_SAFE_INTEGER;
238
+ let tmpFilePath = filePath;
239
+ // If possible, write the tmp file to the OS tmp directory
240
+ // This reduces the amount of FS events the watcher needs to process during the build
241
+ if (shouldUseOsTmpDir(filePath)) {
242
+ tmpFilePath = path_1.default.join((0, os_1.tmpdir)(), path_1.default.basename(filePath));
243
+ }
244
+ return (tmpFilePath +
245
+ '.' +
246
+ process.pid +
247
+ // @ts-expect-error TS7005
248
+ (threadId != null ? '.' + threadId : '') +
249
+ '.' +
250
+ (writeStreamCalls++).toString(36));
251
+ }
@@ -0,0 +1,193 @@
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 () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
36
+ if (kind === "m") throw new TypeError("Private method is not writable");
37
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
38
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
39
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
40
+ };
41
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
42
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
43
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
44
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
45
+ };
46
+ var __importDefault = (this && this.__importDefault) || function (mod) {
47
+ return (mod && mod.__esModule) ? mod : { "default": mod };
48
+ };
49
+ var _NodeVCSAwareFS_excludePatterns, _NodeVCSAwareFS_logEventDiff, _NodeVCSAwareFS_gitRepoPath;
50
+ Object.defineProperty(exports, "__esModule", { value: true });
51
+ exports.NodeVCSAwareFS = void 0;
52
+ const path_1 = __importDefault(require("path"));
53
+ const NodeFS_1 = require("./NodeFS");
54
+ const rust_1 = require("@atlaspack/rust");
55
+ const build_cache_1 = require("@atlaspack/build-cache");
56
+ const logger_1 = __importStar(require("@atlaspack/logger"));
57
+ const feature_flags_1 = require("@atlaspack/feature-flags");
58
+ const package_json_1 = __importDefault(require("../package.json"));
59
+ class NodeVCSAwareFS extends NodeFS_1.NodeFS {
60
+ constructor(options) {
61
+ super();
62
+ /**
63
+ * These files are excluded from 'dirty file' tracking even if they are
64
+ * modified.
65
+ */
66
+ _NodeVCSAwareFS_excludePatterns.set(this, void 0);
67
+ /**
68
+ * Logging function for the diff between watcher events and vcs events.
69
+ */
70
+ _NodeVCSAwareFS_logEventDiff.set(this, void 0);
71
+ /**
72
+ * The path of the git repository containing the project root. Null if the
73
+ * project is not a git repository.
74
+ */
75
+ _NodeVCSAwareFS_gitRepoPath.set(this, void 0);
76
+ __classPrivateFieldSet(this, _NodeVCSAwareFS_excludePatterns, options.excludePatterns, "f");
77
+ __classPrivateFieldSet(this, _NodeVCSAwareFS_logEventDiff, options.logEventDiff, "f");
78
+ __classPrivateFieldSet(this, _NodeVCSAwareFS_gitRepoPath, options.gitRepoPath, "f");
79
+ }
80
+ static deserialize(data) {
81
+ const fs = new NodeVCSAwareFS({
82
+ excludePatterns: data.excludePatterns,
83
+ logEventDiff: null,
84
+ gitRepoPath: data.gitRepoPath,
85
+ });
86
+ return fs;
87
+ }
88
+ // @ts-expect-error TS2416
89
+ serialize() {
90
+ return {
91
+ excludePatterns: __classPrivateFieldGet(this, _NodeVCSAwareFS_excludePatterns, "f"),
92
+ logEventDiff: null,
93
+ gitRepoPath: __classPrivateFieldGet(this, _NodeVCSAwareFS_gitRepoPath, "f"),
94
+ };
95
+ }
96
+ setGitRepoPath(gitRepoPath) {
97
+ __classPrivateFieldSet(this, _NodeVCSAwareFS_gitRepoPath, gitRepoPath, "f");
98
+ }
99
+ async getEventsSince(dir, snapshot, opts) {
100
+ const gitRepoPath = __classPrivateFieldGet(this, _NodeVCSAwareFS_gitRepoPath, "f");
101
+ if (gitRepoPath == null) {
102
+ return this.watcher().getEventsSince(dir, snapshot, opts);
103
+ }
104
+ const { nativeSnapshotPath, vcsState } = await (0, logger_1.instrumentAsync)('NodeVCSAwareFS.readSnapshot', async () => {
105
+ // Note: can't use toString() directly, or it won't resolve the promise
106
+ const snapshotFile = await this.readFile(snapshot);
107
+ const snapshotFileContent = snapshotFile.toString();
108
+ return JSON.parse(snapshotFileContent);
109
+ });
110
+ let watcherEventsSince = [];
111
+ const vcsEventsSince = vcsState != null
112
+ ? // @ts-expect-error TS2571
113
+ (await (0, logger_1.instrumentAsync)('NodeVCSAwareFS::rust.getEventsSince', () =>
114
+ // @ts-expect-error TS2739
115
+ (0, rust_1.getEventsSince)(gitRepoPath, vcsState, null)))
116
+ // @ts-expect-error TS7006
117
+ .map((e) => ({
118
+ path: e.path,
119
+ type: e.changeType,
120
+ }))
121
+ : null;
122
+ if ((0, feature_flags_1.getFeatureFlagValue)('vcsMode') !== 'NEW' && vcsEventsSince != null) {
123
+ watcherEventsSince = await (0, logger_1.instrumentAsync)('NodeVCSAwareFS::watchman.getEventsSince', () => this.watcher().getEventsSince(dir, nativeSnapshotPath, opts));
124
+ __classPrivateFieldGet(this, _NodeVCSAwareFS_logEventDiff, "f")?.call(this, watcherEventsSince, vcsEventsSince);
125
+ }
126
+ // @ts-expect-error TS2345
127
+ if (['NEW_AND_CHECK', 'NEW'].includes((0, feature_flags_1.getFeatureFlagValue)('vcsMode'))) {
128
+ if (vcsEventsSince == null) {
129
+ logger_1.default.error({
130
+ origin: '@atlaspack/fs',
131
+ message: 'Missing VCS state. There was an error when writing the snapshot. Please clear your cache.',
132
+ meta: {
133
+ trackableEvent: 'vcs_state_snapshot_read_failed',
134
+ },
135
+ });
136
+ return [];
137
+ }
138
+ return vcsEventsSince;
139
+ }
140
+ return watcherEventsSince;
141
+ }
142
+ async writeSnapshot(dir, snapshot, opts) {
143
+ const gitRepoPath = __classPrivateFieldGet(this, _NodeVCSAwareFS_gitRepoPath, "f");
144
+ if (gitRepoPath == null) {
145
+ await this.watcher().writeSnapshot(dir, snapshot, opts);
146
+ return;
147
+ }
148
+ const snapshotDirectory = path_1.default.dirname(snapshot);
149
+ await this.mkdirp(snapshotDirectory);
150
+ const filename = path_1.default.basename(snapshot, '.txt');
151
+ const nativeSnapshotPath = path_1.default.join(snapshotDirectory, `${filename}.native-snapshot.txt`);
152
+ if ((0, feature_flags_1.getFeatureFlagValue)('vcsMode') !== 'NEW') {
153
+ await (0, logger_1.instrumentAsync)('NodeVCSAwareFS::watchman.writeSnapshot', async () => {
154
+ await this.watcher().writeSnapshot(dir, nativeSnapshotPath, opts);
155
+ });
156
+ }
157
+ let vcsState = null;
158
+ try {
159
+ vcsState = await (0, logger_1.instrumentAsync)('NodeVCSAwareFS::getVcsStateSnapshot',
160
+ // @ts-expect-error TS2322
161
+ () => (0, rust_1.getVcsStateSnapshot)(gitRepoPath, __classPrivateFieldGet(this, _NodeVCSAwareFS_excludePatterns, "f")));
162
+ logger_1.default.verbose({
163
+ origin: '@atlaspack/fs',
164
+ message: 'Expose VCS timing metrics',
165
+ meta: {
166
+ trackableEvent: 'vcs_timing_metrics',
167
+ // @ts-expect-error TS2339
168
+ dirtyFilesExecutionTime: vcsState?.dirtyFilesExecutionTime,
169
+ // @ts-expect-error TS2339
170
+ yarnStatesExecutionTime: vcsState?.yarnStatesExecutionTime,
171
+ },
172
+ });
173
+ }
174
+ catch (err) {
175
+ logger_1.default.error({
176
+ origin: '@atlaspack/fs',
177
+ message: `Failed to get VCS state snapshot: ${err.message}`,
178
+ meta: {
179
+ trackableEvent: 'vcs_state_snapshot_failed',
180
+ error: err,
181
+ },
182
+ });
183
+ }
184
+ const snapshotContents = {
185
+ vcsState,
186
+ nativeSnapshotPath,
187
+ };
188
+ await this.writeFile(snapshot, JSON.stringify(snapshotContents));
189
+ }
190
+ }
191
+ exports.NodeVCSAwareFS = NodeVCSAwareFS;
192
+ _NodeVCSAwareFS_excludePatterns = new WeakMap(), _NodeVCSAwareFS_logEventDiff = new WeakMap(), _NodeVCSAwareFS_gitRepoPath = new WeakMap();
193
+ (0, build_cache_1.registerSerializableClass)(`${package_json_1.default.version}:NodeVCSAwareFS`, NodeVCSAwareFS);