@heybox/hb-sdk 0.9.1-alpha.5 → 0.9.1-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.
Files changed (32) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +22 -0
  3. package/dist/cli-chunks/browser-DUdEZCyq.cjs +15 -0
  4. package/dist/cli-chunks/{build-D91J_GAa.cjs → build-DYYWRiaY.cjs} +14 -8
  5. package/dist/cli-chunks/{context-Xdd45FFd.cjs → context-Bo4L-Cx_.cjs} +12 -12
  6. package/dist/cli-chunks/{create-BzpdRC5r.cjs → create-CKC4yp0J.cjs} +12 -5
  7. package/dist/cli-chunks/{dev-C7acO3Kt.cjs → dev-BMX6UXUe.cjs} +12 -13
  8. package/dist/cli-chunks/{doctor-BgHRDQmG.cjs → doctor-DqEYRo4I.cjs} +13 -6
  9. package/dist/cli-chunks/{index-CjhQXbxy.cjs → index-DmCWB_hF.cjs} +3 -3
  10. package/dist/cli-chunks/{index-TQwjvNjL.cjs → index-J4uQvKT_.cjs} +10810 -6510
  11. package/dist/cli-chunks/{index.esm-dgqkvowo.cjs → index.esm-eNPTDv6W.cjs} +18 -19
  12. package/dist/cli-chunks/{login-B14iGXHh.cjs → login-BL2OE6r9.cjs} +32 -33
  13. package/dist/cli-chunks/{project-vite-CN6mMjzX.cjs → project-vite-Du1m7Y_3.cjs} +1 -1
  14. package/dist/cli-chunks/{remote-C9RUiZxK.cjs → remote-ZHJUtx6l.cjs} +35 -32
  15. package/dist/cli-chunks/{runtime-gate-CfAkz0p-.cjs → runtime-gate-DedD3ynE.cjs} +2 -2
  16. package/dist/cli-chunks/{runtime-permission-env-L7OfyRcl.cjs → runtime-permission-env-DWaPlchd.cjs} +1 -1
  17. package/dist/cli-chunks/{skill-BHTVho1a.cjs → skill-D4z_a_BH.cjs} +14 -7
  18. package/dist/cli-chunks/{version-C_NaCZ8O.cjs → version-tzrFwpkl.cjs} +1 -1
  19. package/dist/cli.cjs +14 -6
  20. package/dist/devtools/browser-dev-host/assets/{browser-dev-host-KPFU0Lsa.js → browser-dev-host-BL1URvGR.js} +1 -1
  21. package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-BNF9Yk4P.js → desktop-app-launch-D6QZYpUq.js} +1 -1
  22. package/dist/devtools/browser-dev-host/assets/{index-DRRtB9Nm.js → index-Bqsp608m.js} +3 -3
  23. package/dist/devtools/browser-dev-host/index.html +2 -2
  24. package/dist/index.cjs.js +1 -1
  25. package/dist/index.esm.js +1 -1
  26. package/dist/vite.cjs.js +1 -1
  27. package/dist/vite.esm.js +1 -1
  28. package/package.json +3 -3
  29. package/skill/SKILL.md +15 -0
  30. package/skill/skill.json +5 -5
  31. package/dist/cli-chunks/browser-RAy8e8cV.cjs +0 -635
  32. package/dist/cli-chunks/session-DZrr6RYK.cjs +0 -3404
@@ -1,3404 +0,0 @@
1
- 'use strict';
2
-
3
- var index = require('./index-TQwjvNjL.cjs');
4
- var node_crypto = require('node:crypto');
5
- var path = require('node:path');
6
- var require$$0$2 = require('fs');
7
- var require$$0 = require('constants');
8
- var require$$0$1 = require('stream');
9
- var require$$1 = require('util');
10
- var require$$0$3 = require('assert');
11
- var require$$1$1 = require('path');
12
-
13
- const HEYBOX_API_BASE_URL = 'https://api.xiaoheihe.cn';
14
- const HEYBOX_LOGIN_BASE_URL = 'https://login.xiaoheihe.cn';
15
- const TRUSTED_HEYBOX_API_HOST_SUFFIXES = ['.xiaoheihe.cn', '.debugmode.cn'];
16
- function resolveHeyboxApiBaseUrl(options = {}) {
17
- const env = options.env;
18
- const baseUrl = normalizeHeyboxOriginUrl(options.apiBaseUrl ?? env?.HB_SDK_API_BASE_URL ?? HEYBOX_API_BASE_URL, 'Heybox API baseUrl');
19
- assertSafeHeyboxApiBaseUrl(baseUrl, {
20
- allowUnsafeApiBaseUrl: options.allowUnsafeApiBaseUrl === true || isTruthyEnvFlag(env?.HB_SDK_ALLOW_UNSAFE_API_BASE_URL),
21
- });
22
- return baseUrl;
23
- }
24
- function resolveHeyboxLoginBaseUrl(options = {}) {
25
- const env = options.env;
26
- return normalizeHeyboxOriginUrl(options.loginBaseUrl ?? env?.HB_SDK_LOGIN_BASE_URL ?? HEYBOX_LOGIN_BASE_URL, 'Heybox login baseUrl');
27
- }
28
- function normalizeHeyboxOriginUrl(value, label) {
29
- const raw = String(value ?? '').trim();
30
- if (!raw) {
31
- throw new Error(`${label} 不能为空`);
32
- }
33
- let url;
34
- try {
35
- url = new URL(raw);
36
- }
37
- catch {
38
- throw new Error(`${label} 必须是合法的 http(s) origin:${raw}`);
39
- }
40
- if (url.protocol !== 'http:' && url.protocol !== 'https:') {
41
- throw new Error(`${label} 只支持 http(s) 协议:${raw}`);
42
- }
43
- if (url.username || url.password) {
44
- throw new Error(`${label} 不允许包含用户名或密码:${raw}`);
45
- }
46
- const rawSuffix = raw.match(/^[a-z][a-z\d+.-]*:\/\/[^/?#]+(.*)$/i)?.[1] ?? '';
47
- if ((rawSuffix && rawSuffix !== '/') || url.search || url.hash) {
48
- throw new Error(`${label} 只支持 origin,不允许包含 path、query 或 hash:${raw}`);
49
- }
50
- return url.origin;
51
- }
52
- function assertSafeHeyboxApiBaseUrl(origin, options) {
53
- if (options.allowUnsafeApiBaseUrl) {
54
- return;
55
- }
56
- const url = new URL(origin);
57
- if (url.protocol !== 'https:' || !isTrustedHeyboxApiHost(url.hostname)) {
58
- throw new Error('Heybox API baseUrl 默认只允许 Heybox 受信 HTTPS origin;本地调试请显式使用 --allow-unsafe-api-base-url 或 HB_SDK_ALLOW_UNSAFE_API_BASE_URL=1');
59
- }
60
- }
61
- function isTrustedHeyboxApiHost(hostname) {
62
- return TRUSTED_HEYBOX_API_HOST_SUFFIXES.some((suffix) => hostname === suffix.slice(1) || hostname.endsWith(suffix));
63
- }
64
- function isTruthyEnvFlag(value) {
65
- return ['1', 'true', 'yes', 'on'].includes(String(value ?? '')
66
- .trim()
67
- .toLowerCase());
68
- }
69
- /** 开放平台网页地址独立于 API 地址,避免跨环境申请。 */
70
- function resolveHeyboxOpenPlatformBaseUrl(env = process.env) {
71
- return normalizeHeyboxOriginUrl(env.HB_SDK_OPEN_PLATFORM_BASE_URL ?? 'https://open.xiaoheihe.cn', '开放平台 baseUrl');
72
- }
73
-
74
- const SIGN_VERSION = '999.0.4';
75
- const SIGN_CHARSET = 'AB45STUVWZEFGJ6CH01D237IXYPQRKLMN89';
76
- function createHeyboxOpenPlatformSignParams(pathname, options = {}) {
77
- const now = options.now ?? new Date();
78
- const time = Math.trunc(now.getTime() / 1000);
79
- const nonce = options.nonce ?? md5(`${time}${Date.now()}${node_crypto.randomBytes(16).toString('hex')}`).toUpperCase();
80
- return {
81
- version: SIGN_VERSION,
82
- hkey: generateSignature(pathname, time + 1, nonce),
83
- _time: time,
84
- nonce,
85
- };
86
- }
87
- function generateSignature(path, time, nonce) {
88
- const normalizedPath = `/${path
89
- .split('/')
90
- .filter(Boolean)
91
- .join('/')}/`;
92
- const transformedTime = transformWithOffset(String(time), SIGN_CHARSET, -2);
93
- const transformedPath = transform(normalizedPath, SIGN_CHARSET);
94
- const transformedNonce = transform(nonce, SIGN_CHARSET);
95
- const combined = interleave([transformedTime, transformedPath, transformedNonce]).slice(0, 20);
96
- const hash = md5(combined);
97
- let sign = `${mixColumns(hash.slice(-6).split('').map((char) => char.charCodeAt(0))).reduce((sum, value) => sum + value, 0) % 100}`;
98
- sign = sign.length < 2 ? `0${sign}` : sign;
99
- return `${transformWithOffset(hash.substring(0, 5), SIGN_CHARSET, -4)}${sign}`;
100
- }
101
- function transformWithOffset(str, charset, offset) {
102
- return transform(str, charset.slice(0, offset));
103
- }
104
- function transform(str, charset) {
105
- let output = '';
106
- for (let index = 0; index < str.length; index += 1) {
107
- output += charset[str.charCodeAt(index) % charset.length];
108
- }
109
- return output;
110
- }
111
- function interleave(strings) {
112
- let output = '';
113
- const maxLength = Math.max(...strings.map((str) => str.length));
114
- for (let index = 0; index < maxLength; index += 1) {
115
- for (const str of strings) {
116
- if (index < str.length) {
117
- output += str[index];
118
- }
119
- }
120
- }
121
- return output;
122
- }
123
- function mixColumns(column) {
124
- const output = [...column];
125
- output[0] = multiplyE(column[0]) ^ multiply4(column[1]) ^ multiply3(column[2]) ^ multiply2(column[3]);
126
- output[1] = multiply2(column[0]) ^ multiplyE(column[1]) ^ multiply4(column[2]) ^ multiply3(column[3]);
127
- output[2] = multiply3(column[0]) ^ multiply2(column[1]) ^ multiplyE(column[2]) ^ multiply4(column[3]);
128
- output[3] = multiply4(column[0]) ^ multiply3(column[1]) ^ multiply2(column[2]) ^ multiplyE(column[3]);
129
- return output;
130
- }
131
- function multiply1(value) {
132
- if (value & 0x80) {
133
- return ((value << 1) ^ 0x1b) & 0xff;
134
- }
135
- return value << 1;
136
- }
137
- function multiply2(value) {
138
- return multiply1(value) ^ value;
139
- }
140
- function multiply3(value) {
141
- return multiply2(multiply1(value));
142
- }
143
- function multiply4(value) {
144
- return multiply3(multiply2(multiply1(value)));
145
- }
146
- function multiplyE(value) {
147
- return multiply4(value) ^ multiply3(value) ^ multiply2(value);
148
- }
149
- function md5(input) {
150
- return node_crypto.createHash('md5').update(input).digest('hex');
151
- }
152
-
153
- const DEFAULT_PLATFORM_PARAMS = {
154
- os_type: 'web',
155
- app: 'heybox',
156
- x_client_type: 'web',
157
- x_os_type: 'Mac',
158
- x_app: 'heybox',
159
- x_client_version: '999.999.999',
160
- };
161
- const HEYBOX_WEB_REFERER = 'https://www.xiaoheihe.cn/';
162
- function resolveHeyboxId(session) {
163
- if (session.heyboxId.trim()) {
164
- return session.heyboxId.trim();
165
- }
166
- return session.cookieHeader
167
- .split(';')
168
- .map((part) => part.trim())
169
- .find((part) => part.startsWith('heybox_id='))
170
- ?.slice('heybox_id='.length);
171
- }
172
- function createHeyboxAuthHeaders(session, options = {}) {
173
- const serviceTag = index.resolveHeyboxRylaiServiceTag(options.pathWithQuery);
174
- return {
175
- Cookie: session.cookieHeader,
176
- Referer: HEYBOX_WEB_REFERER,
177
- ...(options.contentType ? { 'Content-Type': options.contentType } : {}),
178
- ...(serviceTag ? { 'x-rylai-service-tag': serviceTag } : {}),
179
- };
180
- }
181
- function createHeyboxRequestContext(session, options = {}) {
182
- const heyboxId = resolveHeyboxId(session);
183
- const serviceTag = index.resolveHeyboxRylaiServiceTag(options.pathWithQuery);
184
- return {
185
- baseUrl: HEYBOX_API_BASE_URL,
186
- headers: createHeyboxAuthHeaders(session, options),
187
- platformParams: {
188
- ...DEFAULT_PLATFORM_PARAMS,
189
- ...options.platformParams,
190
- ...(heyboxId ? { heybox_id: heyboxId } : {}),
191
- ...(serviceTag ? { special_tag: serviceTag } : {}),
192
- },
193
- };
194
- }
195
- function createHeyboxOpenPlatformRequestContext(session, pathWithQuery, options = {}) {
196
- return createHeyboxRequestContext(session, {
197
- ...options,
198
- pathWithQuery,
199
- platformParams: {
200
- x_app: 'heybox_website',
201
- ...createHeyboxOpenPlatformSignParams(getApiPathname(pathWithQuery)),
202
- ...options.platformParams,
203
- },
204
- });
205
- }
206
- function createHeyboxApiUrl(baseUrl, pathWithQuery, params) {
207
- const url = new URL(pathWithQuery, baseUrl);
208
- for (const [key, value] of Object.entries(params)) {
209
- if (value !== '') {
210
- url.searchParams.set(key, String(value));
211
- }
212
- }
213
- return url.toString();
214
- }
215
- function getApiPathname(pathWithQuery) {
216
- return new URL(pathWithQuery, HEYBOX_API_BASE_URL).pathname;
217
- }
218
- const ENVELOPE_BODY_PREVIEW_LENGTH = 1000;
219
- /** 网关限流状态码;403(封禁)与 429(限速)走独立错误分支。 */
220
- const RATE_LIMIT_HTTP_STATUSES = new Set([403, 429]);
221
- /** HTTP-date 只接受以星期缩写开头的合法形态,避免宽松解析把垃圾值当日期。 */
222
- const HTTP_DATE_RE = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;
223
- /** 网关原文里的等待时长;例如 `43200s内请求 ... 6127次,限制访问 86400s`。 */
224
- const GATEWAY_RETRY_AFTER_PATTERNS = [
225
- /限制访问\s*(\d+(?:\.\d+)?)\s*s/i,
226
- /retry[\s_-]*after[^0-9]{0,12}(\d+(?:\.\d+)?)\s*s/i,
227
- /(\d+(?:\.\d+)?)\s*秒后/,
228
- ];
229
- async function readHeyboxApiEnvelope(response, options) {
230
- const rawBody = await response.text();
231
- let envelope = null;
232
- let parseError = null;
233
- if (rawBody) {
234
- try {
235
- envelope = JSON.parse(rawBody);
236
- }
237
- catch (error) {
238
- parseError = error;
239
- }
240
- }
241
- const envelopeOk = envelope?.status === 'ok' && (!options.requireResult || envelope?.result !== undefined);
242
- if (response.ok && envelopeOk) {
243
- return envelope.result;
244
- }
245
- const { message, verboseMessage } = formatHeyboxEnvelopeError({
246
- response,
247
- envelope,
248
- parseError,
249
- rawBody,
250
- pathWithQuery: options.pathWithQuery,
251
- });
252
- if (RATE_LIMIT_HTTP_STATUSES.has(response.status)) {
253
- const gatewayMessage = readGatewayRateLimitMessage(envelope, rawBody);
254
- const retryAfterMs = readRetryAfterMs(response, gatewayMessage);
255
- throw new index.CliRateLimitedError(message, {
256
- gatewayMessage,
257
- httpStatus: response.status,
258
- ...(retryAfterMs === undefined ? {} : { retryAfterMs }),
259
- verboseMessage,
260
- });
261
- }
262
- throw new index.CliError(message, verboseMessage, { httpStatus: response.status });
263
- }
264
- /**
265
- * 优先读 `Retry-After` 响应头,其次从网关原文解析等待时长。
266
- *
267
- * 只返回**正数毫秒**:`Retry-After: 0`、已过期的 HTTP-date、负数与非法值一律按「网关没有
268
- * 给出时长」处理,由消费方回落默认窗口(CLI 30s 起、宿主页 30s)。这样两端对同一个状态
269
- * 的解读一致,也不会出现「宿主页立即重连、CLI 仍在压制」的分歧。
270
- */
271
- function readRetryAfterMs(response, gatewayMessage) {
272
- const headerValue = response.headers?.get('retry-after')?.trim();
273
- if (headerValue) {
274
- // 纯数字才是 delta-seconds;其余按 HTTP-date 解析,避免 `Date.parse('-5')` 产出垃圾值。
275
- if (/^\d+$/.test(headerValue)) {
276
- const headerMs = Number(headerValue) * 1000;
277
- if (headerMs > 0)
278
- return Math.round(headerMs);
279
- }
280
- else if (HTTP_DATE_RE.test(headerValue)) {
281
- const headerDate = Date.parse(headerValue);
282
- if (Number.isFinite(headerDate) && headerDate > Date.now()) {
283
- return headerDate - Date.now();
284
- }
285
- }
286
- }
287
- for (const pattern of GATEWAY_RETRY_AFTER_PATTERNS) {
288
- const matched = gatewayMessage.match(pattern);
289
- const seconds = matched ? Number(matched[1]) : Number.NaN;
290
- if (Number.isFinite(seconds) && seconds > 0) {
291
- return Math.round(seconds * 1000);
292
- }
293
- }
294
- return undefined;
295
- }
296
- /** 网关原文:优先 envelope 的 msg,退化为响应体原文,最后回落到通用文案。 */
297
- function readGatewayRateLimitMessage(envelope, rawBody) {
298
- const msg = typeof envelope?.msg === 'string' ? envelope.msg.trim() : '';
299
- if (msg)
300
- return msg;
301
- const sbeUserMessage = readSbeUserMessage(envelope?.result);
302
- if (sbeUserMessage)
303
- return sbeUserMessage;
304
- return rawBody.trim() ? truncate(rawBody.trim(), ENVELOPE_BODY_PREVIEW_LENGTH) : '';
305
- }
306
- function formatHeyboxEnvelopeError(input) {
307
- const parts = [`Heybox API ${input.pathWithQuery} failed`, `HTTP ${input.response.status}`];
308
- if (input.envelope) {
309
- const msg = typeof input.envelope.msg === 'string' ? input.envelope.msg.trim() : '';
310
- const sbeUserMessage = readSbeUserMessage(input.envelope.result);
311
- parts.push(`msg=${msg || '(empty)'}`);
312
- if (typeof input.envelope.status === 'string') {
313
- parts.push(`envelope.status=${input.envelope.status}`);
314
- }
315
- const { status: _s, msg: _m, result: _r, ...extras } = input.envelope;
316
- if (Object.keys(extras).length > 0) {
317
- parts.push(`extras=${truncate(safeJsonStringify(extras), ENVELOPE_BODY_PREVIEW_LENGTH)}`);
318
- }
319
- if (input.envelope.result !== undefined) {
320
- parts.push(`result=${truncate(safeJsonStringify(input.envelope.result), ENVELOPE_BODY_PREVIEW_LENGTH)}`);
321
- }
322
- return {
323
- message: sbeUserMessage || msg || `Heybox API ${input.pathWithQuery} 请求失败`,
324
- verboseMessage: parts.join(' '),
325
- };
326
- }
327
- if (input.parseError) {
328
- const parseMsg = input.parseError instanceof Error ? input.parseError.message : String(input.parseError);
329
- parts.push(`parseError=${parseMsg}`);
330
- }
331
- parts.push(input.rawBody ? `body=${truncate(input.rawBody, ENVELOPE_BODY_PREVIEW_LENGTH)}` : 'body=(empty)');
332
- return {
333
- message: `Heybox API ${input.pathWithQuery} 请求失败`,
334
- verboseMessage: parts.join(' '),
335
- };
336
- }
337
- function readSbeUserMessage(result) {
338
- if (!result || typeof result !== 'object') {
339
- return '';
340
- }
341
- const sbe = result.sbe;
342
- if (!sbe || typeof sbe !== 'object') {
343
- return '';
344
- }
345
- const userMessage = sbe.user_message;
346
- return typeof userMessage === 'string' ? userMessage.trim() : '';
347
- }
348
- function truncate(value, max) {
349
- return value.length > max ? `${value.slice(0, max)}...(+${value.length - max} chars)` : value;
350
- }
351
- function safeJsonStringify(value) {
352
- try {
353
- return JSON.stringify(value);
354
- }
355
- catch {
356
- return String(value);
357
- }
358
- }
359
-
360
- var fs$1 = {};
361
-
362
- var universalify = {};
363
-
364
- var hasRequiredUniversalify;
365
-
366
- function requireUniversalify () {
367
- if (hasRequiredUniversalify) return universalify;
368
- hasRequiredUniversalify = 1;
369
-
370
- universalify.fromCallback = function (fn) {
371
- return Object.defineProperty(function (...args) {
372
- if (typeof args[args.length - 1] === 'function') fn.apply(this, args);
373
- else {
374
- return new Promise((resolve, reject) => {
375
- args.push((err, res) => (err != null) ? reject(err) : resolve(res));
376
- fn.apply(this, args);
377
- })
378
- }
379
- }, 'name', { value: fn.name })
380
- };
381
-
382
- universalify.fromPromise = function (fn) {
383
- return Object.defineProperty(function (...args) {
384
- const cb = args[args.length - 1];
385
- if (typeof cb !== 'function') return fn.apply(this, args)
386
- else {
387
- args.pop();
388
- fn.apply(this, args).then(r => cb(null, r), cb);
389
- }
390
- }, 'name', { value: fn.name })
391
- };
392
- return universalify;
393
- }
394
-
395
- var polyfills;
396
- var hasRequiredPolyfills;
397
-
398
- function requirePolyfills () {
399
- if (hasRequiredPolyfills) return polyfills;
400
- hasRequiredPolyfills = 1;
401
- var constants = require$$0;
402
-
403
- var origCwd = process.cwd;
404
- var cwd = null;
405
-
406
- var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
407
-
408
- process.cwd = function() {
409
- if (!cwd)
410
- cwd = origCwd.call(process);
411
- return cwd
412
- };
413
- try {
414
- process.cwd();
415
- } catch (er) {}
416
-
417
- // This check is needed until node.js 12 is required
418
- if (typeof process.chdir === 'function') {
419
- var chdir = process.chdir;
420
- process.chdir = function (d) {
421
- cwd = null;
422
- chdir.call(process, d);
423
- };
424
- if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
425
- }
426
-
427
- polyfills = patch;
428
-
429
- function patch (fs) {
430
- // (re-)implement some things that are known busted or missing.
431
-
432
- // lchmod, broken prior to 0.6.2
433
- // back-port the fix here.
434
- if (constants.hasOwnProperty('O_SYMLINK') &&
435
- process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
436
- patchLchmod(fs);
437
- }
438
-
439
- // lutimes implementation, or no-op
440
- if (!fs.lutimes) {
441
- patchLutimes(fs);
442
- }
443
-
444
- // https://github.com/isaacs/node-graceful-fs/issues/4
445
- // Chown should not fail on einval or eperm if non-root.
446
- // It should not fail on enosys ever, as this just indicates
447
- // that a fs doesn't support the intended operation.
448
-
449
- fs.chown = chownFix(fs.chown);
450
- fs.fchown = chownFix(fs.fchown);
451
- fs.lchown = chownFix(fs.lchown);
452
-
453
- fs.chmod = chmodFix(fs.chmod);
454
- fs.fchmod = chmodFix(fs.fchmod);
455
- fs.lchmod = chmodFix(fs.lchmod);
456
-
457
- fs.chownSync = chownFixSync(fs.chownSync);
458
- fs.fchownSync = chownFixSync(fs.fchownSync);
459
- fs.lchownSync = chownFixSync(fs.lchownSync);
460
-
461
- fs.chmodSync = chmodFixSync(fs.chmodSync);
462
- fs.fchmodSync = chmodFixSync(fs.fchmodSync);
463
- fs.lchmodSync = chmodFixSync(fs.lchmodSync);
464
-
465
- fs.stat = statFix(fs.stat);
466
- fs.fstat = statFix(fs.fstat);
467
- fs.lstat = statFix(fs.lstat);
468
-
469
- fs.statSync = statFixSync(fs.statSync);
470
- fs.fstatSync = statFixSync(fs.fstatSync);
471
- fs.lstatSync = statFixSync(fs.lstatSync);
472
-
473
- // if lchmod/lchown do not exist, then make them no-ops
474
- if (fs.chmod && !fs.lchmod) {
475
- fs.lchmod = function (path, mode, cb) {
476
- if (cb) process.nextTick(cb);
477
- };
478
- fs.lchmodSync = function () {};
479
- }
480
- if (fs.chown && !fs.lchown) {
481
- fs.lchown = function (path, uid, gid, cb) {
482
- if (cb) process.nextTick(cb);
483
- };
484
- fs.lchownSync = function () {};
485
- }
486
-
487
- // on Windows, A/V software can lock the directory, causing this
488
- // to fail with an EACCES or EPERM if the directory contains newly
489
- // created files. Try again on failure, for up to 60 seconds.
490
-
491
- // Set the timeout this long because some Windows Anti-Virus, such as Parity
492
- // bit9, may lock files for up to a minute, causing npm package install
493
- // failures. Also, take care to yield the scheduler. Windows scheduling gives
494
- // CPU to a busy looping process, which can cause the program causing the lock
495
- // contention to be starved of CPU by node, so the contention doesn't resolve.
496
- if (platform === "win32") {
497
- fs.rename = typeof fs.rename !== 'function' ? fs.rename
498
- : (function (fs$rename) {
499
- function rename (from, to, cb) {
500
- var start = Date.now();
501
- var backoff = 0;
502
- fs$rename(from, to, function CB (er) {
503
- if (er
504
- && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY")
505
- && Date.now() - start < 60000) {
506
- setTimeout(function() {
507
- fs.stat(to, function (stater, st) {
508
- if (stater && stater.code === "ENOENT")
509
- fs$rename(from, to, CB);
510
- else
511
- cb(er);
512
- });
513
- }, backoff);
514
- if (backoff < 100)
515
- backoff += 10;
516
- return;
517
- }
518
- if (cb) cb(er);
519
- });
520
- }
521
- if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
522
- return rename
523
- })(fs.rename);
524
- }
525
-
526
- // if read() returns EAGAIN, then just try it again.
527
- fs.read = typeof fs.read !== 'function' ? fs.read
528
- : (function (fs$read) {
529
- function read (fd, buffer, offset, length, position, callback_) {
530
- var callback;
531
- if (callback_ && typeof callback_ === 'function') {
532
- var eagCounter = 0;
533
- callback = function (er, _, __) {
534
- if (er && er.code === 'EAGAIN' && eagCounter < 10) {
535
- eagCounter ++;
536
- return fs$read.call(fs, fd, buffer, offset, length, position, callback)
537
- }
538
- callback_.apply(this, arguments);
539
- };
540
- }
541
- return fs$read.call(fs, fd, buffer, offset, length, position, callback)
542
- }
543
-
544
- // This ensures `util.promisify` works as it does for native `fs.read`.
545
- if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
546
- return read
547
- })(fs.read);
548
-
549
- fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync
550
- : (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
551
- var eagCounter = 0;
552
- while (true) {
553
- try {
554
- return fs$readSync.call(fs, fd, buffer, offset, length, position)
555
- } catch (er) {
556
- if (er.code === 'EAGAIN' && eagCounter < 10) {
557
- eagCounter ++;
558
- continue
559
- }
560
- throw er
561
- }
562
- }
563
- }})(fs.readSync);
564
-
565
- function patchLchmod (fs) {
566
- fs.lchmod = function (path, mode, callback) {
567
- fs.open( path
568
- , constants.O_WRONLY | constants.O_SYMLINK
569
- , mode
570
- , function (err, fd) {
571
- if (err) {
572
- if (callback) callback(err);
573
- return
574
- }
575
- // prefer to return the chmod error, if one occurs,
576
- // but still try to close, and report closing errors if they occur.
577
- fs.fchmod(fd, mode, function (err) {
578
- fs.close(fd, function(err2) {
579
- if (callback) callback(err || err2);
580
- });
581
- });
582
- });
583
- };
584
-
585
- fs.lchmodSync = function (path, mode) {
586
- var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
587
-
588
- // prefer to return the chmod error, if one occurs,
589
- // but still try to close, and report closing errors if they occur.
590
- var threw = true;
591
- var ret;
592
- try {
593
- ret = fs.fchmodSync(fd, mode);
594
- threw = false;
595
- } finally {
596
- if (threw) {
597
- try {
598
- fs.closeSync(fd);
599
- } catch (er) {}
600
- } else {
601
- fs.closeSync(fd);
602
- }
603
- }
604
- return ret
605
- };
606
- }
607
-
608
- function patchLutimes (fs) {
609
- if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) {
610
- fs.lutimes = function (path, at, mt, cb) {
611
- fs.open(path, constants.O_SYMLINK, function (er, fd) {
612
- if (er) {
613
- if (cb) cb(er);
614
- return
615
- }
616
- fs.futimes(fd, at, mt, function (er) {
617
- fs.close(fd, function (er2) {
618
- if (cb) cb(er || er2);
619
- });
620
- });
621
- });
622
- };
623
-
624
- fs.lutimesSync = function (path, at, mt) {
625
- var fd = fs.openSync(path, constants.O_SYMLINK);
626
- var ret;
627
- var threw = true;
628
- try {
629
- ret = fs.futimesSync(fd, at, mt);
630
- threw = false;
631
- } finally {
632
- if (threw) {
633
- try {
634
- fs.closeSync(fd);
635
- } catch (er) {}
636
- } else {
637
- fs.closeSync(fd);
638
- }
639
- }
640
- return ret
641
- };
642
-
643
- } else if (fs.futimes) {
644
- fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); };
645
- fs.lutimesSync = function () {};
646
- }
647
- }
648
-
649
- function chmodFix (orig) {
650
- if (!orig) return orig
651
- return function (target, mode, cb) {
652
- return orig.call(fs, target, mode, function (er) {
653
- if (chownErOk(er)) er = null;
654
- if (cb) cb.apply(this, arguments);
655
- })
656
- }
657
- }
658
-
659
- function chmodFixSync (orig) {
660
- if (!orig) return orig
661
- return function (target, mode) {
662
- try {
663
- return orig.call(fs, target, mode)
664
- } catch (er) {
665
- if (!chownErOk(er)) throw er
666
- }
667
- }
668
- }
669
-
670
-
671
- function chownFix (orig) {
672
- if (!orig) return orig
673
- return function (target, uid, gid, cb) {
674
- return orig.call(fs, target, uid, gid, function (er) {
675
- if (chownErOk(er)) er = null;
676
- if (cb) cb.apply(this, arguments);
677
- })
678
- }
679
- }
680
-
681
- function chownFixSync (orig) {
682
- if (!orig) return orig
683
- return function (target, uid, gid) {
684
- try {
685
- return orig.call(fs, target, uid, gid)
686
- } catch (er) {
687
- if (!chownErOk(er)) throw er
688
- }
689
- }
690
- }
691
-
692
- function statFix (orig) {
693
- if (!orig) return orig
694
- // Older versions of Node erroneously returned signed integers for
695
- // uid + gid.
696
- return function (target, options, cb) {
697
- if (typeof options === 'function') {
698
- cb = options;
699
- options = null;
700
- }
701
- function callback (er, stats) {
702
- if (stats) {
703
- if (stats.uid < 0) stats.uid += 0x100000000;
704
- if (stats.gid < 0) stats.gid += 0x100000000;
705
- }
706
- if (cb) cb.apply(this, arguments);
707
- }
708
- return options ? orig.call(fs, target, options, callback)
709
- : orig.call(fs, target, callback)
710
- }
711
- }
712
-
713
- function statFixSync (orig) {
714
- if (!orig) return orig
715
- // Older versions of Node erroneously returned signed integers for
716
- // uid + gid.
717
- return function (target, options) {
718
- var stats = options ? orig.call(fs, target, options)
719
- : orig.call(fs, target);
720
- if (stats) {
721
- if (stats.uid < 0) stats.uid += 0x100000000;
722
- if (stats.gid < 0) stats.gid += 0x100000000;
723
- }
724
- return stats;
725
- }
726
- }
727
-
728
- // ENOSYS means that the fs doesn't support the op. Just ignore
729
- // that, because it doesn't matter.
730
- //
731
- // if there's no getuid, or if getuid() is something other
732
- // than 0, and the error is EINVAL or EPERM, then just ignore
733
- // it.
734
- //
735
- // This specific case is a silent failure in cp, install, tar,
736
- // and most other unix tools that manage permissions.
737
- //
738
- // When running as root, or if other types of errors are
739
- // encountered, then it's strict.
740
- function chownErOk (er) {
741
- if (!er)
742
- return true
743
-
744
- if (er.code === "ENOSYS")
745
- return true
746
-
747
- var nonroot = !process.getuid || process.getuid() !== 0;
748
- if (nonroot) {
749
- if (er.code === "EINVAL" || er.code === "EPERM")
750
- return true
751
- }
752
-
753
- return false
754
- }
755
- }
756
- return polyfills;
757
- }
758
-
759
- var legacyStreams;
760
- var hasRequiredLegacyStreams;
761
-
762
- function requireLegacyStreams () {
763
- if (hasRequiredLegacyStreams) return legacyStreams;
764
- hasRequiredLegacyStreams = 1;
765
- var Stream = require$$0$1.Stream;
766
-
767
- legacyStreams = legacy;
768
-
769
- function legacy (fs) {
770
- return {
771
- ReadStream: ReadStream,
772
- WriteStream: WriteStream
773
- }
774
-
775
- function ReadStream (path, options) {
776
- if (!(this instanceof ReadStream)) return new ReadStream(path, options);
777
-
778
- Stream.call(this);
779
-
780
- var self = this;
781
-
782
- this.path = path;
783
- this.fd = null;
784
- this.readable = true;
785
- this.paused = false;
786
-
787
- this.flags = 'r';
788
- this.mode = 438; /*=0666*/
789
- this.bufferSize = 64 * 1024;
790
-
791
- options = options || {};
792
-
793
- // Mixin options into this
794
- var keys = Object.keys(options);
795
- for (var index = 0, length = keys.length; index < length; index++) {
796
- var key = keys[index];
797
- this[key] = options[key];
798
- }
799
-
800
- if (this.encoding) this.setEncoding(this.encoding);
801
-
802
- if (this.start !== undefined) {
803
- if ('number' !== typeof this.start) {
804
- throw TypeError('start must be a Number');
805
- }
806
- if (this.end === undefined) {
807
- this.end = Infinity;
808
- } else if ('number' !== typeof this.end) {
809
- throw TypeError('end must be a Number');
810
- }
811
-
812
- if (this.start > this.end) {
813
- throw new Error('start must be <= end');
814
- }
815
-
816
- this.pos = this.start;
817
- }
818
-
819
- if (this.fd !== null) {
820
- process.nextTick(function() {
821
- self._read();
822
- });
823
- return;
824
- }
825
-
826
- fs.open(this.path, this.flags, this.mode, function (err, fd) {
827
- if (err) {
828
- self.emit('error', err);
829
- self.readable = false;
830
- return;
831
- }
832
-
833
- self.fd = fd;
834
- self.emit('open', fd);
835
- self._read();
836
- });
837
- }
838
-
839
- function WriteStream (path, options) {
840
- if (!(this instanceof WriteStream)) return new WriteStream(path, options);
841
-
842
- Stream.call(this);
843
-
844
- this.path = path;
845
- this.fd = null;
846
- this.writable = true;
847
-
848
- this.flags = 'w';
849
- this.encoding = 'binary';
850
- this.mode = 438; /*=0666*/
851
- this.bytesWritten = 0;
852
-
853
- options = options || {};
854
-
855
- // Mixin options into this
856
- var keys = Object.keys(options);
857
- for (var index = 0, length = keys.length; index < length; index++) {
858
- var key = keys[index];
859
- this[key] = options[key];
860
- }
861
-
862
- if (this.start !== undefined) {
863
- if ('number' !== typeof this.start) {
864
- throw TypeError('start must be a Number');
865
- }
866
- if (this.start < 0) {
867
- throw new Error('start must be >= zero');
868
- }
869
-
870
- this.pos = this.start;
871
- }
872
-
873
- this.busy = false;
874
- this._queue = [];
875
-
876
- if (this.fd === null) {
877
- this._open = fs.open;
878
- this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
879
- this.flush();
880
- }
881
- }
882
- }
883
- return legacyStreams;
884
- }
885
-
886
- var clone_1;
887
- var hasRequiredClone;
888
-
889
- function requireClone () {
890
- if (hasRequiredClone) return clone_1;
891
- hasRequiredClone = 1;
892
-
893
- clone_1 = clone;
894
-
895
- var getPrototypeOf = Object.getPrototypeOf || function (obj) {
896
- return obj.__proto__
897
- };
898
-
899
- function clone (obj) {
900
- if (obj === null || typeof obj !== 'object')
901
- return obj
902
-
903
- if (obj instanceof Object)
904
- var copy = { __proto__: getPrototypeOf(obj) };
905
- else
906
- var copy = Object.create(null);
907
-
908
- Object.getOwnPropertyNames(obj).forEach(function (key) {
909
- Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
910
- });
911
-
912
- return copy
913
- }
914
- return clone_1;
915
- }
916
-
917
- var gracefulFs;
918
- var hasRequiredGracefulFs;
919
-
920
- function requireGracefulFs () {
921
- if (hasRequiredGracefulFs) return gracefulFs;
922
- hasRequiredGracefulFs = 1;
923
- var fs = require$$0$2;
924
- var polyfills = requirePolyfills();
925
- var legacy = requireLegacyStreams();
926
- var clone = requireClone();
927
-
928
- var util = require$$1;
929
-
930
- /* istanbul ignore next - node 0.x polyfill */
931
- var gracefulQueue;
932
- var previousSymbol;
933
-
934
- /* istanbul ignore else - node 0.x polyfill */
935
- if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
936
- gracefulQueue = Symbol.for('graceful-fs.queue');
937
- // This is used in testing by future versions
938
- previousSymbol = Symbol.for('graceful-fs.previous');
939
- } else {
940
- gracefulQueue = '___graceful-fs.queue';
941
- previousSymbol = '___graceful-fs.previous';
942
- }
943
-
944
- function noop () {}
945
-
946
- function publishQueue(context, queue) {
947
- Object.defineProperty(context, gracefulQueue, {
948
- get: function() {
949
- return queue
950
- }
951
- });
952
- }
953
-
954
- var debug = noop;
955
- if (util.debuglog)
956
- debug = util.debuglog('gfs4');
957
- else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
958
- debug = function() {
959
- var m = util.format.apply(util, arguments);
960
- m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ');
961
- console.error(m);
962
- };
963
-
964
- // Once time initialization
965
- if (!fs[gracefulQueue]) {
966
- // This queue can be shared by multiple loaded instances
967
- var queue = index.commonjsGlobal[gracefulQueue] || [];
968
- publishQueue(fs, queue);
969
-
970
- // Patch fs.close/closeSync to shared queue version, because we need
971
- // to retry() whenever a close happens *anywhere* in the program.
972
- // This is essential when multiple graceful-fs instances are
973
- // in play at the same time.
974
- fs.close = (function (fs$close) {
975
- function close (fd, cb) {
976
- return fs$close.call(fs, fd, function (err) {
977
- // This function uses the graceful-fs shared queue
978
- if (!err) {
979
- resetQueue();
980
- }
981
-
982
- if (typeof cb === 'function')
983
- cb.apply(this, arguments);
984
- })
985
- }
986
-
987
- Object.defineProperty(close, previousSymbol, {
988
- value: fs$close
989
- });
990
- return close
991
- })(fs.close);
992
-
993
- fs.closeSync = (function (fs$closeSync) {
994
- function closeSync (fd) {
995
- // This function uses the graceful-fs shared queue
996
- fs$closeSync.apply(fs, arguments);
997
- resetQueue();
998
- }
999
-
1000
- Object.defineProperty(closeSync, previousSymbol, {
1001
- value: fs$closeSync
1002
- });
1003
- return closeSync
1004
- })(fs.closeSync);
1005
-
1006
- if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
1007
- process.on('exit', function() {
1008
- debug(fs[gracefulQueue]);
1009
- require$$0$3.equal(fs[gracefulQueue].length, 0);
1010
- });
1011
- }
1012
- }
1013
-
1014
- if (!index.commonjsGlobal[gracefulQueue]) {
1015
- publishQueue(index.commonjsGlobal, fs[gracefulQueue]);
1016
- }
1017
-
1018
- gracefulFs = patch(clone(fs));
1019
- if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
1020
- gracefulFs = patch(fs);
1021
- fs.__patched = true;
1022
- }
1023
-
1024
- function patch (fs) {
1025
- // Everything that references the open() function needs to be in here
1026
- polyfills(fs);
1027
- fs.gracefulify = patch;
1028
-
1029
- fs.createReadStream = createReadStream;
1030
- fs.createWriteStream = createWriteStream;
1031
- var fs$readFile = fs.readFile;
1032
- fs.readFile = readFile;
1033
- function readFile (path, options, cb) {
1034
- if (typeof options === 'function')
1035
- cb = options, options = null;
1036
-
1037
- return go$readFile(path, options, cb)
1038
-
1039
- function go$readFile (path, options, cb, startTime) {
1040
- return fs$readFile(path, options, function (err) {
1041
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1042
- enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]);
1043
- else {
1044
- if (typeof cb === 'function')
1045
- cb.apply(this, arguments);
1046
- }
1047
- })
1048
- }
1049
- }
1050
-
1051
- var fs$writeFile = fs.writeFile;
1052
- fs.writeFile = writeFile;
1053
- function writeFile (path, data, options, cb) {
1054
- if (typeof options === 'function')
1055
- cb = options, options = null;
1056
-
1057
- return go$writeFile(path, data, options, cb)
1058
-
1059
- function go$writeFile (path, data, options, cb, startTime) {
1060
- return fs$writeFile(path, data, options, function (err) {
1061
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1062
- enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
1063
- else {
1064
- if (typeof cb === 'function')
1065
- cb.apply(this, arguments);
1066
- }
1067
- })
1068
- }
1069
- }
1070
-
1071
- var fs$appendFile = fs.appendFile;
1072
- if (fs$appendFile)
1073
- fs.appendFile = appendFile;
1074
- function appendFile (path, data, options, cb) {
1075
- if (typeof options === 'function')
1076
- cb = options, options = null;
1077
-
1078
- return go$appendFile(path, data, options, cb)
1079
-
1080
- function go$appendFile (path, data, options, cb, startTime) {
1081
- return fs$appendFile(path, data, options, function (err) {
1082
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1083
- enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
1084
- else {
1085
- if (typeof cb === 'function')
1086
- cb.apply(this, arguments);
1087
- }
1088
- })
1089
- }
1090
- }
1091
-
1092
- var fs$copyFile = fs.copyFile;
1093
- if (fs$copyFile)
1094
- fs.copyFile = copyFile;
1095
- function copyFile (src, dest, flags, cb) {
1096
- if (typeof flags === 'function') {
1097
- cb = flags;
1098
- flags = 0;
1099
- }
1100
- return go$copyFile(src, dest, flags, cb)
1101
-
1102
- function go$copyFile (src, dest, flags, cb, startTime) {
1103
- return fs$copyFile(src, dest, flags, function (err) {
1104
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1105
- enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]);
1106
- else {
1107
- if (typeof cb === 'function')
1108
- cb.apply(this, arguments);
1109
- }
1110
- })
1111
- }
1112
- }
1113
-
1114
- var fs$readdir = fs.readdir;
1115
- fs.readdir = readdir;
1116
- var noReaddirOptionVersions = /^v[0-5]\./;
1117
- function readdir (path, options, cb) {
1118
- if (typeof options === 'function')
1119
- cb = options, options = null;
1120
-
1121
- var go$readdir = noReaddirOptionVersions.test(process.version)
1122
- ? function go$readdir (path, options, cb, startTime) {
1123
- return fs$readdir(path, fs$readdirCallback(
1124
- path, options, cb, startTime
1125
- ))
1126
- }
1127
- : function go$readdir (path, options, cb, startTime) {
1128
- return fs$readdir(path, options, fs$readdirCallback(
1129
- path, options, cb, startTime
1130
- ))
1131
- };
1132
-
1133
- return go$readdir(path, options, cb)
1134
-
1135
- function fs$readdirCallback (path, options, cb, startTime) {
1136
- return function (err, files) {
1137
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1138
- enqueue([
1139
- go$readdir,
1140
- [path, options, cb],
1141
- err,
1142
- startTime || Date.now(),
1143
- Date.now()
1144
- ]);
1145
- else {
1146
- if (files && files.sort)
1147
- files.sort();
1148
-
1149
- if (typeof cb === 'function')
1150
- cb.call(this, err, files);
1151
- }
1152
- }
1153
- }
1154
- }
1155
-
1156
- if (process.version.substr(0, 4) === 'v0.8') {
1157
- var legStreams = legacy(fs);
1158
- ReadStream = legStreams.ReadStream;
1159
- WriteStream = legStreams.WriteStream;
1160
- }
1161
-
1162
- var fs$ReadStream = fs.ReadStream;
1163
- if (fs$ReadStream) {
1164
- ReadStream.prototype = Object.create(fs$ReadStream.prototype);
1165
- ReadStream.prototype.open = ReadStream$open;
1166
- }
1167
-
1168
- var fs$WriteStream = fs.WriteStream;
1169
- if (fs$WriteStream) {
1170
- WriteStream.prototype = Object.create(fs$WriteStream.prototype);
1171
- WriteStream.prototype.open = WriteStream$open;
1172
- }
1173
-
1174
- Object.defineProperty(fs, 'ReadStream', {
1175
- get: function () {
1176
- return ReadStream
1177
- },
1178
- set: function (val) {
1179
- ReadStream = val;
1180
- },
1181
- enumerable: true,
1182
- configurable: true
1183
- });
1184
- Object.defineProperty(fs, 'WriteStream', {
1185
- get: function () {
1186
- return WriteStream
1187
- },
1188
- set: function (val) {
1189
- WriteStream = val;
1190
- },
1191
- enumerable: true,
1192
- configurable: true
1193
- });
1194
-
1195
- // legacy names
1196
- var FileReadStream = ReadStream;
1197
- Object.defineProperty(fs, 'FileReadStream', {
1198
- get: function () {
1199
- return FileReadStream
1200
- },
1201
- set: function (val) {
1202
- FileReadStream = val;
1203
- },
1204
- enumerable: true,
1205
- configurable: true
1206
- });
1207
- var FileWriteStream = WriteStream;
1208
- Object.defineProperty(fs, 'FileWriteStream', {
1209
- get: function () {
1210
- return FileWriteStream
1211
- },
1212
- set: function (val) {
1213
- FileWriteStream = val;
1214
- },
1215
- enumerable: true,
1216
- configurable: true
1217
- });
1218
-
1219
- function ReadStream (path, options) {
1220
- if (this instanceof ReadStream)
1221
- return fs$ReadStream.apply(this, arguments), this
1222
- else
1223
- return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
1224
- }
1225
-
1226
- function ReadStream$open () {
1227
- var that = this;
1228
- open(that.path, that.flags, that.mode, function (err, fd) {
1229
- if (err) {
1230
- if (that.autoClose)
1231
- that.destroy();
1232
-
1233
- that.emit('error', err);
1234
- } else {
1235
- that.fd = fd;
1236
- that.emit('open', fd);
1237
- that.read();
1238
- }
1239
- });
1240
- }
1241
-
1242
- function WriteStream (path, options) {
1243
- if (this instanceof WriteStream)
1244
- return fs$WriteStream.apply(this, arguments), this
1245
- else
1246
- return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
1247
- }
1248
-
1249
- function WriteStream$open () {
1250
- var that = this;
1251
- open(that.path, that.flags, that.mode, function (err, fd) {
1252
- if (err) {
1253
- that.destroy();
1254
- that.emit('error', err);
1255
- } else {
1256
- that.fd = fd;
1257
- that.emit('open', fd);
1258
- }
1259
- });
1260
- }
1261
-
1262
- function createReadStream (path, options) {
1263
- return new fs.ReadStream(path, options)
1264
- }
1265
-
1266
- function createWriteStream (path, options) {
1267
- return new fs.WriteStream(path, options)
1268
- }
1269
-
1270
- var fs$open = fs.open;
1271
- fs.open = open;
1272
- function open (path, flags, mode, cb) {
1273
- if (typeof mode === 'function')
1274
- cb = mode, mode = null;
1275
-
1276
- return go$open(path, flags, mode, cb)
1277
-
1278
- function go$open (path, flags, mode, cb, startTime) {
1279
- return fs$open(path, flags, mode, function (err, fd) {
1280
- if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1281
- enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]);
1282
- else {
1283
- if (typeof cb === 'function')
1284
- cb.apply(this, arguments);
1285
- }
1286
- })
1287
- }
1288
- }
1289
-
1290
- return fs
1291
- }
1292
-
1293
- function enqueue (elem) {
1294
- debug('ENQUEUE', elem[0].name, elem[1]);
1295
- fs[gracefulQueue].push(elem);
1296
- retry();
1297
- }
1298
-
1299
- // keep track of the timeout between retry() calls
1300
- var retryTimer;
1301
-
1302
- // reset the startTime and lastTime to now
1303
- // this resets the start of the 60 second overall timeout as well as the
1304
- // delay between attempts so that we'll retry these jobs sooner
1305
- function resetQueue () {
1306
- var now = Date.now();
1307
- for (var i = 0; i < fs[gracefulQueue].length; ++i) {
1308
- // entries that are only a length of 2 are from an older version, don't
1309
- // bother modifying those since they'll be retried anyway.
1310
- if (fs[gracefulQueue][i].length > 2) {
1311
- fs[gracefulQueue][i][3] = now; // startTime
1312
- fs[gracefulQueue][i][4] = now; // lastTime
1313
- }
1314
- }
1315
- // call retry to make sure we're actively processing the queue
1316
- retry();
1317
- }
1318
-
1319
- function retry () {
1320
- // clear the timer and remove it to help prevent unintended concurrency
1321
- clearTimeout(retryTimer);
1322
- retryTimer = undefined;
1323
-
1324
- if (fs[gracefulQueue].length === 0)
1325
- return
1326
-
1327
- var elem = fs[gracefulQueue].shift();
1328
- var fn = elem[0];
1329
- var args = elem[1];
1330
- // these items may be unset if they were added by an older graceful-fs
1331
- var err = elem[2];
1332
- var startTime = elem[3];
1333
- var lastTime = elem[4];
1334
-
1335
- // if we don't have a startTime we have no way of knowing if we've waited
1336
- // long enough, so go ahead and retry this item now
1337
- if (startTime === undefined) {
1338
- debug('RETRY', fn.name, args);
1339
- fn.apply(null, args);
1340
- } else if (Date.now() - startTime >= 60000) {
1341
- // it's been more than 60 seconds total, bail now
1342
- debug('TIMEOUT', fn.name, args);
1343
- var cb = args.pop();
1344
- if (typeof cb === 'function')
1345
- cb.call(null, err);
1346
- } else {
1347
- // the amount of time between the last attempt and right now
1348
- var sinceAttempt = Date.now() - lastTime;
1349
- // the amount of time between when we first tried, and when we last tried
1350
- // rounded up to at least 1
1351
- var sinceStart = Math.max(lastTime - startTime, 1);
1352
- // backoff. wait longer than the total time we've been retrying, but only
1353
- // up to a maximum of 100ms
1354
- var desiredDelay = Math.min(sinceStart * 1.2, 100);
1355
- // it's been long enough since the last retry, do it again
1356
- if (sinceAttempt >= desiredDelay) {
1357
- debug('RETRY', fn.name, args);
1358
- fn.apply(null, args.concat([startTime]));
1359
- } else {
1360
- // if we can't do this job yet, push it to the end of the queue
1361
- // and let the next iteration check again
1362
- fs[gracefulQueue].push(elem);
1363
- }
1364
- }
1365
-
1366
- // schedule our next run if one isn't already scheduled
1367
- if (retryTimer === undefined) {
1368
- retryTimer = setTimeout(retry, 0);
1369
- }
1370
- }
1371
- return gracefulFs;
1372
- }
1373
-
1374
- var hasRequiredFs;
1375
-
1376
- function requireFs () {
1377
- if (hasRequiredFs) return fs$1;
1378
- hasRequiredFs = 1;
1379
- (function (exports) {
1380
- // This is adapted from https://github.com/normalize/mz
1381
- // Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
1382
- const u = requireUniversalify().fromCallback;
1383
- const fs = requireGracefulFs();
1384
-
1385
- const api = [
1386
- 'access',
1387
- 'appendFile',
1388
- 'chmod',
1389
- 'chown',
1390
- 'close',
1391
- 'copyFile',
1392
- 'cp',
1393
- 'fchmod',
1394
- 'fchown',
1395
- 'fdatasync',
1396
- 'fstat',
1397
- 'fsync',
1398
- 'ftruncate',
1399
- 'futimes',
1400
- 'glob',
1401
- 'lchmod',
1402
- 'lchown',
1403
- 'lutimes',
1404
- 'link',
1405
- 'lstat',
1406
- 'mkdir',
1407
- 'mkdtemp',
1408
- 'open',
1409
- 'opendir',
1410
- 'readdir',
1411
- 'readFile',
1412
- 'readlink',
1413
- 'realpath',
1414
- 'rename',
1415
- 'rm',
1416
- 'rmdir',
1417
- 'stat',
1418
- 'statfs',
1419
- 'symlink',
1420
- 'truncate',
1421
- 'unlink',
1422
- 'utimes',
1423
- 'writeFile'
1424
- ].filter(key => {
1425
- // Some commands are not available on some systems. Ex:
1426
- // fs.cp was added in Node.js v16.7.0
1427
- // fs.statfs was added in Node v19.6.0, v18.15.0
1428
- // fs.glob was added in Node.js v22.0.0
1429
- // fs.lchown is not available on at least some Linux
1430
- return typeof fs[key] === 'function'
1431
- });
1432
-
1433
- // Export cloned fs:
1434
- Object.assign(exports, fs);
1435
-
1436
- // Universalify async methods:
1437
- api.forEach(method => {
1438
- exports[method] = u(fs[method]);
1439
- });
1440
-
1441
- // We differ from mz/fs in that we still ship the old, broken, fs.exists()
1442
- // since we are a drop-in replacement for the native module
1443
- exports.exists = function (filename, callback) {
1444
- if (typeof callback === 'function') {
1445
- return fs.exists(filename, callback)
1446
- }
1447
- return new Promise(resolve => {
1448
- return fs.exists(filename, resolve)
1449
- })
1450
- };
1451
-
1452
- // fs.read(), fs.write(), fs.readv(), & fs.writev() need special treatment due to multiple callback args
1453
-
1454
- exports.read = function (fd, buffer, offset, length, position, callback) {
1455
- if (typeof callback === 'function') {
1456
- return fs.read(fd, buffer, offset, length, position, callback)
1457
- }
1458
- return new Promise((resolve, reject) => {
1459
- fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
1460
- if (err) return reject(err)
1461
- resolve({ bytesRead, buffer });
1462
- });
1463
- })
1464
- };
1465
-
1466
- // Function signature can be
1467
- // fs.write(fd, buffer[, offset[, length[, position]]], callback)
1468
- // OR
1469
- // fs.write(fd, string[, position[, encoding]], callback)
1470
- // We need to handle both cases, so we use ...args
1471
- exports.write = function (fd, buffer, ...args) {
1472
- if (typeof args[args.length - 1] === 'function') {
1473
- return fs.write(fd, buffer, ...args)
1474
- }
1475
-
1476
- return new Promise((resolve, reject) => {
1477
- fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {
1478
- if (err) return reject(err)
1479
- resolve({ bytesWritten, buffer });
1480
- });
1481
- })
1482
- };
1483
-
1484
- // Function signature is
1485
- // s.readv(fd, buffers[, position], callback)
1486
- // We need to handle the optional arg, so we use ...args
1487
- exports.readv = function (fd, buffers, ...args) {
1488
- if (typeof args[args.length - 1] === 'function') {
1489
- return fs.readv(fd, buffers, ...args)
1490
- }
1491
-
1492
- return new Promise((resolve, reject) => {
1493
- fs.readv(fd, buffers, ...args, (err, bytesRead, buffers) => {
1494
- if (err) return reject(err)
1495
- resolve({ bytesRead, buffers });
1496
- });
1497
- })
1498
- };
1499
-
1500
- // Function signature is
1501
- // s.writev(fd, buffers[, position], callback)
1502
- // We need to handle the optional arg, so we use ...args
1503
- exports.writev = function (fd, buffers, ...args) {
1504
- if (typeof args[args.length - 1] === 'function') {
1505
- return fs.writev(fd, buffers, ...args)
1506
- }
1507
-
1508
- return new Promise((resolve, reject) => {
1509
- fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => {
1510
- if (err) return reject(err)
1511
- resolve({ bytesWritten, buffers });
1512
- });
1513
- })
1514
- };
1515
-
1516
- // fs.realpath.native sometimes not available if fs is monkey-patched
1517
- if (typeof fs.realpath.native === 'function') {
1518
- exports.realpath.native = u(fs.realpath.native);
1519
- } else {
1520
- process.emitWarning(
1521
- 'fs.realpath.native is not a function. Is fs being monkey-patched?',
1522
- 'Warning', 'fs-extra-WARN0003'
1523
- );
1524
- }
1525
- } (fs$1));
1526
- return fs$1;
1527
- }
1528
-
1529
- var makeDir = {};
1530
-
1531
- var utils$1 = {};
1532
-
1533
- var hasRequiredUtils$1;
1534
-
1535
- function requireUtils$1 () {
1536
- if (hasRequiredUtils$1) return utils$1;
1537
- hasRequiredUtils$1 = 1;
1538
- const path = require$$1$1;
1539
-
1540
- // https://github.com/nodejs/node/issues/8987
1541
- // https://github.com/libuv/libuv/pull/1088
1542
- utils$1.checkPath = function checkPath (pth) {
1543
- if (process.platform === 'win32') {
1544
- const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, ''));
1545
-
1546
- if (pathHasInvalidWinCharacters) {
1547
- const error = new Error(`Path contains invalid characters: ${pth}`);
1548
- error.code = 'EINVAL';
1549
- throw error
1550
- }
1551
- }
1552
- };
1553
- return utils$1;
1554
- }
1555
-
1556
- var hasRequiredMakeDir;
1557
-
1558
- function requireMakeDir () {
1559
- if (hasRequiredMakeDir) return makeDir;
1560
- hasRequiredMakeDir = 1;
1561
- const fs = /*@__PURE__*/ requireFs();
1562
- const { checkPath } = /*@__PURE__*/ requireUtils$1();
1563
-
1564
- const getMode = options => {
1565
- const defaults = { mode: 0o777 };
1566
- if (typeof options === 'number') return options
1567
- return ({ ...defaults, ...options }).mode
1568
- };
1569
-
1570
- makeDir.makeDir = async (dir, options) => {
1571
- checkPath(dir);
1572
-
1573
- return fs.mkdir(dir, {
1574
- mode: getMode(options),
1575
- recursive: true
1576
- })
1577
- };
1578
-
1579
- makeDir.makeDirSync = (dir, options) => {
1580
- checkPath(dir);
1581
-
1582
- return fs.mkdirSync(dir, {
1583
- mode: getMode(options),
1584
- recursive: true
1585
- })
1586
- };
1587
- return makeDir;
1588
- }
1589
-
1590
- var mkdirs;
1591
- var hasRequiredMkdirs;
1592
-
1593
- function requireMkdirs () {
1594
- if (hasRequiredMkdirs) return mkdirs;
1595
- hasRequiredMkdirs = 1;
1596
- const u = requireUniversalify().fromPromise;
1597
- const { makeDir: _makeDir, makeDirSync } = /*@__PURE__*/ requireMakeDir();
1598
- const makeDir = u(_makeDir);
1599
-
1600
- mkdirs = {
1601
- mkdirs: makeDir,
1602
- mkdirsSync: makeDirSync,
1603
- // alias
1604
- mkdirp: makeDir,
1605
- mkdirpSync: makeDirSync,
1606
- ensureDir: makeDir,
1607
- ensureDirSync: makeDirSync
1608
- };
1609
- return mkdirs;
1610
- }
1611
-
1612
- var pathExists_1;
1613
- var hasRequiredPathExists;
1614
-
1615
- function requirePathExists () {
1616
- if (hasRequiredPathExists) return pathExists_1;
1617
- hasRequiredPathExists = 1;
1618
- const u = requireUniversalify().fromPromise;
1619
- const fs = /*@__PURE__*/ requireFs();
1620
-
1621
- function pathExists (path) {
1622
- return fs.access(path).then(() => true).catch(() => false)
1623
- }
1624
-
1625
- pathExists_1 = {
1626
- pathExists: u(pathExists),
1627
- pathExistsSync: fs.existsSync
1628
- };
1629
- return pathExists_1;
1630
- }
1631
-
1632
- var utimes;
1633
- var hasRequiredUtimes;
1634
-
1635
- function requireUtimes () {
1636
- if (hasRequiredUtimes) return utimes;
1637
- hasRequiredUtimes = 1;
1638
-
1639
- const fs = /*@__PURE__*/ requireFs();
1640
- const u = requireUniversalify().fromPromise;
1641
-
1642
- async function utimesMillis (path, atime, mtime) {
1643
- const fd = await fs.open(path, 'r+');
1644
-
1645
- let error = null;
1646
-
1647
- try {
1648
- await fs.futimes(fd, atime, mtime);
1649
- } catch (futimesErr) {
1650
- error = futimesErr;
1651
- } finally {
1652
- try {
1653
- await fs.close(fd);
1654
- } catch (closeErr) {
1655
- if (!error) error = closeErr;
1656
- }
1657
- }
1658
-
1659
- if (error) {
1660
- throw error
1661
- }
1662
- }
1663
-
1664
- function utimesMillisSync (path, atime, mtime) {
1665
- const fd = fs.openSync(path, 'r+');
1666
-
1667
- let error = null;
1668
-
1669
- try {
1670
- fs.futimesSync(fd, atime, mtime);
1671
- } catch (futimesErr) {
1672
- error = futimesErr;
1673
- } finally {
1674
- try {
1675
- fs.closeSync(fd);
1676
- } catch (closeErr) {
1677
- if (!error) error = closeErr;
1678
- }
1679
- }
1680
-
1681
- if (error) {
1682
- throw error
1683
- }
1684
- }
1685
-
1686
- utimes = {
1687
- utimesMillis: u(utimesMillis),
1688
- utimesMillisSync
1689
- };
1690
- return utimes;
1691
- }
1692
-
1693
- var stat;
1694
- var hasRequiredStat;
1695
-
1696
- function requireStat () {
1697
- if (hasRequiredStat) return stat;
1698
- hasRequiredStat = 1;
1699
-
1700
- const fs = /*@__PURE__*/ requireFs();
1701
- const path = require$$1$1;
1702
- const u = requireUniversalify().fromPromise;
1703
-
1704
- function getStats (src, dest, opts) {
1705
- const statFunc = opts.dereference
1706
- ? (file) => fs.stat(file, { bigint: true })
1707
- : (file) => fs.lstat(file, { bigint: true });
1708
- return Promise.all([
1709
- statFunc(src),
1710
- statFunc(dest).catch(err => {
1711
- if (err.code === 'ENOENT') return null
1712
- throw err
1713
- })
1714
- ]).then(([srcStat, destStat]) => ({ srcStat, destStat }))
1715
- }
1716
-
1717
- function getStatsSync (src, dest, opts) {
1718
- let destStat;
1719
- const statFunc = opts.dereference
1720
- ? (file) => fs.statSync(file, { bigint: true })
1721
- : (file) => fs.lstatSync(file, { bigint: true });
1722
- const srcStat = statFunc(src);
1723
- try {
1724
- destStat = statFunc(dest);
1725
- } catch (err) {
1726
- if (err.code === 'ENOENT') return { srcStat, destStat: null }
1727
- throw err
1728
- }
1729
- return { srcStat, destStat }
1730
- }
1731
-
1732
- async function checkPaths (src, dest, funcName, opts) {
1733
- const { srcStat, destStat } = await getStats(src, dest, opts);
1734
- if (destStat) {
1735
- if (areIdentical(srcStat, destStat)) {
1736
- const srcBaseName = path.basename(src);
1737
- const destBaseName = path.basename(dest);
1738
- if (funcName === 'move' &&
1739
- srcBaseName !== destBaseName &&
1740
- srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
1741
- return { srcStat, destStat, isChangingCase: true }
1742
- }
1743
- throw new Error('Source and destination must not be the same.')
1744
- }
1745
- if (srcStat.isDirectory() && !destStat.isDirectory()) {
1746
- throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
1747
- }
1748
- if (!srcStat.isDirectory() && destStat.isDirectory()) {
1749
- throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)
1750
- }
1751
- }
1752
-
1753
- if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
1754
- throw new Error(errMsg(src, dest, funcName))
1755
- }
1756
-
1757
- return { srcStat, destStat }
1758
- }
1759
-
1760
- function checkPathsSync (src, dest, funcName, opts) {
1761
- const { srcStat, destStat } = getStatsSync(src, dest, opts);
1762
-
1763
- if (destStat) {
1764
- if (areIdentical(srcStat, destStat)) {
1765
- const srcBaseName = path.basename(src);
1766
- const destBaseName = path.basename(dest);
1767
- if (funcName === 'move' &&
1768
- srcBaseName !== destBaseName &&
1769
- srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
1770
- return { srcStat, destStat, isChangingCase: true }
1771
- }
1772
- throw new Error('Source and destination must not be the same.')
1773
- }
1774
- if (srcStat.isDirectory() && !destStat.isDirectory()) {
1775
- throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
1776
- }
1777
- if (!srcStat.isDirectory() && destStat.isDirectory()) {
1778
- throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)
1779
- }
1780
- }
1781
-
1782
- if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
1783
- throw new Error(errMsg(src, dest, funcName))
1784
- }
1785
- return { srcStat, destStat }
1786
- }
1787
-
1788
- // recursively check if dest parent is a subdirectory of src.
1789
- // It works for all file types including symlinks since it
1790
- // checks the src and dest inodes. It starts from the deepest
1791
- // parent and stops once it reaches the src parent or the root path.
1792
- async function checkParentPaths (src, srcStat, dest, funcName) {
1793
- const srcParent = path.resolve(path.dirname(src));
1794
- const destParent = path.resolve(path.dirname(dest));
1795
- if (destParent === srcParent || destParent === path.parse(destParent).root) return
1796
-
1797
- let destStat;
1798
- try {
1799
- destStat = await fs.stat(destParent, { bigint: true });
1800
- } catch (err) {
1801
- if (err.code === 'ENOENT') return
1802
- throw err
1803
- }
1804
-
1805
- if (areIdentical(srcStat, destStat)) {
1806
- throw new Error(errMsg(src, dest, funcName))
1807
- }
1808
-
1809
- return checkParentPaths(src, srcStat, destParent, funcName)
1810
- }
1811
-
1812
- function checkParentPathsSync (src, srcStat, dest, funcName) {
1813
- const srcParent = path.resolve(path.dirname(src));
1814
- const destParent = path.resolve(path.dirname(dest));
1815
- if (destParent === srcParent || destParent === path.parse(destParent).root) return
1816
- let destStat;
1817
- try {
1818
- destStat = fs.statSync(destParent, { bigint: true });
1819
- } catch (err) {
1820
- if (err.code === 'ENOENT') return
1821
- throw err
1822
- }
1823
- if (areIdentical(srcStat, destStat)) {
1824
- throw new Error(errMsg(src, dest, funcName))
1825
- }
1826
- return checkParentPathsSync(src, srcStat, destParent, funcName)
1827
- }
1828
-
1829
- function areIdentical (srcStat, destStat) {
1830
- // stat.dev can be 0n on windows when node version >= 22.x.x
1831
- return destStat.ino !== undefined && destStat.dev !== undefined && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev
1832
- }
1833
-
1834
- // return true if dest is a subdir of src, otherwise false.
1835
- // It only checks the path strings.
1836
- function isSrcSubdir (src, dest) {
1837
- const srcArr = path.resolve(src).split(path.sep).filter(i => i);
1838
- const destArr = path.resolve(dest).split(path.sep).filter(i => i);
1839
- return srcArr.every((cur, i) => destArr[i] === cur)
1840
- }
1841
-
1842
- function errMsg (src, dest, funcName) {
1843
- return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`
1844
- }
1845
-
1846
- stat = {
1847
- // checkPaths
1848
- checkPaths: u(checkPaths),
1849
- checkPathsSync,
1850
- // checkParent
1851
- checkParentPaths: u(checkParentPaths),
1852
- checkParentPathsSync,
1853
- // Misc
1854
- isSrcSubdir,
1855
- areIdentical
1856
- };
1857
- return stat;
1858
- }
1859
-
1860
- var async;
1861
- var hasRequiredAsync;
1862
-
1863
- function requireAsync () {
1864
- if (hasRequiredAsync) return async;
1865
- hasRequiredAsync = 1;
1866
-
1867
- // https://github.com/jprichardson/node-fs-extra/issues/1056
1868
- // Performing parallel operations on each item of an async iterator is
1869
- // surprisingly hard; you need to have handlers in place to avoid getting an
1870
- // UnhandledPromiseRejectionWarning.
1871
- // NOTE: This function does not presently handle return values, only errors
1872
- async function asyncIteratorConcurrentProcess (iterator, fn) {
1873
- const promises = [];
1874
- for await (const item of iterator) {
1875
- promises.push(
1876
- fn(item).then(
1877
- () => null,
1878
- (err) => err ?? new Error('unknown error')
1879
- )
1880
- );
1881
- }
1882
- await Promise.all(
1883
- promises.map((promise) =>
1884
- promise.then((possibleErr) => {
1885
- if (possibleErr !== null) throw possibleErr
1886
- })
1887
- )
1888
- );
1889
- }
1890
-
1891
- async = {
1892
- asyncIteratorConcurrentProcess
1893
- };
1894
- return async;
1895
- }
1896
-
1897
- var copy_1;
1898
- var hasRequiredCopy$1;
1899
-
1900
- function requireCopy$1 () {
1901
- if (hasRequiredCopy$1) return copy_1;
1902
- hasRequiredCopy$1 = 1;
1903
-
1904
- const fs = /*@__PURE__*/ requireFs();
1905
- const path = require$$1$1;
1906
- const { mkdirs } = /*@__PURE__*/ requireMkdirs();
1907
- const { pathExists } = /*@__PURE__*/ requirePathExists();
1908
- const { utimesMillis } = /*@__PURE__*/ requireUtimes();
1909
- const stat = /*@__PURE__*/ requireStat();
1910
- const { asyncIteratorConcurrentProcess } = /*@__PURE__*/ requireAsync();
1911
-
1912
- async function copy (src, dest, opts = {}) {
1913
- if (typeof opts === 'function') {
1914
- opts = { filter: opts };
1915
- }
1916
-
1917
- opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now
1918
- opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber
1919
-
1920
- // Warn about using preserveTimestamps on 32-bit node
1921
- if (opts.preserveTimestamps && process.arch === 'ia32') {
1922
- process.emitWarning(
1923
- 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' +
1924
- '\tsee https://github.com/jprichardson/node-fs-extra/issues/269',
1925
- 'Warning', 'fs-extra-WARN0001'
1926
- );
1927
- }
1928
-
1929
- const { srcStat, destStat } = await stat.checkPaths(src, dest, 'copy', opts);
1930
-
1931
- await stat.checkParentPaths(src, srcStat, dest, 'copy');
1932
-
1933
- const include = await runFilter(src, dest, opts);
1934
-
1935
- if (!include) return
1936
-
1937
- // check if the parent of dest exists, and create it if it doesn't exist
1938
- const destParent = path.dirname(dest);
1939
- const dirExists = await pathExists(destParent);
1940
- if (!dirExists) {
1941
- await mkdirs(destParent);
1942
- }
1943
-
1944
- await getStatsAndPerformCopy(destStat, src, dest, opts);
1945
- }
1946
-
1947
- async function runFilter (src, dest, opts) {
1948
- if (!opts.filter) return true
1949
- return opts.filter(src, dest)
1950
- }
1951
-
1952
- async function getStatsAndPerformCopy (destStat, src, dest, opts) {
1953
- const statFn = opts.dereference ? fs.stat : fs.lstat;
1954
- const srcStat = await statFn(src);
1955
-
1956
- if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
1957
-
1958
- if (
1959
- srcStat.isFile() ||
1960
- srcStat.isCharacterDevice() ||
1961
- srcStat.isBlockDevice()
1962
- ) return onFile(srcStat, destStat, src, dest, opts)
1963
-
1964
- if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
1965
- if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)
1966
- if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)
1967
- throw new Error(`Unknown file: ${src}`)
1968
- }
1969
-
1970
- async function onFile (srcStat, destStat, src, dest, opts) {
1971
- if (!destStat) return copyFile(srcStat, src, dest, opts)
1972
-
1973
- if (opts.overwrite) {
1974
- await fs.unlink(dest);
1975
- return copyFile(srcStat, src, dest, opts)
1976
- }
1977
- if (opts.errorOnExist) {
1978
- throw new Error(`'${dest}' already exists`)
1979
- }
1980
- }
1981
-
1982
- async function copyFile (srcStat, src, dest, opts) {
1983
- await fs.copyFile(src, dest);
1984
- if (opts.preserveTimestamps) {
1985
- // Make sure the file is writable before setting the timestamp
1986
- // otherwise open fails with EPERM when invoked with 'r+'
1987
- // (through utimes call)
1988
- if (fileIsNotWritable(srcStat.mode)) {
1989
- await makeFileWritable(dest, srcStat.mode);
1990
- }
1991
-
1992
- // Set timestamps and mode correspondingly
1993
-
1994
- // Note that The initial srcStat.atime cannot be trusted
1995
- // because it is modified by the read(2) system call
1996
- // (See https://nodejs.org/api/fs.html#fs_stat_time_values)
1997
- const updatedSrcStat = await fs.stat(src);
1998
- await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime);
1999
- }
2000
-
2001
- return fs.chmod(dest, srcStat.mode)
2002
- }
2003
-
2004
- function fileIsNotWritable (srcMode) {
2005
- return (srcMode & 0o200) === 0
2006
- }
2007
-
2008
- function makeFileWritable (dest, srcMode) {
2009
- return fs.chmod(dest, srcMode | 0o200)
2010
- }
2011
-
2012
- async function onDir (srcStat, destStat, src, dest, opts) {
2013
- // the dest directory might not exist, create it
2014
- if (!destStat) {
2015
- await fs.mkdir(dest);
2016
- }
2017
-
2018
- // iterate through the files in the current directory to copy everything
2019
- await asyncIteratorConcurrentProcess(await fs.opendir(src), async (item) => {
2020
- const srcItem = path.join(src, item.name);
2021
- const destItem = path.join(dest, item.name);
2022
-
2023
- const include = await runFilter(srcItem, destItem, opts);
2024
- // only copy the item if it matches the filter function
2025
- if (include) {
2026
- const { destStat } = await stat.checkPaths(srcItem, destItem, 'copy', opts);
2027
- // If the item is a copyable file, `getStatsAndPerformCopy` will copy it
2028
- // If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively
2029
- await getStatsAndPerformCopy(destStat, srcItem, destItem, opts);
2030
- }
2031
- });
2032
-
2033
- if (!destStat) {
2034
- await fs.chmod(dest, srcStat.mode);
2035
- }
2036
- }
2037
-
2038
- async function onLink (destStat, src, dest, opts) {
2039
- let resolvedSrc = await fs.readlink(src);
2040
- if (opts.dereference) {
2041
- resolvedSrc = path.resolve(process.cwd(), resolvedSrc);
2042
- }
2043
- if (!destStat) {
2044
- return fs.symlink(resolvedSrc, dest)
2045
- }
2046
-
2047
- let resolvedDest = null;
2048
- try {
2049
- resolvedDest = await fs.readlink(dest);
2050
- } catch (e) {
2051
- // dest exists and is a regular file or directory,
2052
- // Windows may throw UNKNOWN error. If dest already exists,
2053
- // fs throws error anyway, so no need to guard against it here.
2054
- if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest)
2055
- throw e
2056
- }
2057
- if (opts.dereference) {
2058
- resolvedDest = path.resolve(process.cwd(), resolvedDest);
2059
- }
2060
- // If both symlinks resolve to the same target, they are still distinct symlinks
2061
- // that can be copied/overwritten. Only check subdirectory constraints when
2062
- // the resolved paths are different.
2063
- if (resolvedSrc !== resolvedDest) {
2064
- if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
2065
- throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
2066
- }
2067
-
2068
- // do not copy if src is a subdir of dest since unlinking
2069
- // dest in this case would result in removing src contents
2070
- // and therefore a broken symlink would be created.
2071
- if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
2072
- throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
2073
- }
2074
- }
2075
-
2076
- // copy the link
2077
- await fs.unlink(dest);
2078
- return fs.symlink(resolvedSrc, dest)
2079
- }
2080
-
2081
- copy_1 = copy;
2082
- return copy_1;
2083
- }
2084
-
2085
- var copySync_1;
2086
- var hasRequiredCopySync;
2087
-
2088
- function requireCopySync () {
2089
- if (hasRequiredCopySync) return copySync_1;
2090
- hasRequiredCopySync = 1;
2091
-
2092
- const fs = requireGracefulFs();
2093
- const path = require$$1$1;
2094
- const mkdirsSync = /*@__PURE__*/ requireMkdirs().mkdirsSync;
2095
- const utimesMillisSync = /*@__PURE__*/ requireUtimes().utimesMillisSync;
2096
- const stat = /*@__PURE__*/ requireStat();
2097
-
2098
- function copySync (src, dest, opts) {
2099
- if (typeof opts === 'function') {
2100
- opts = { filter: opts };
2101
- }
2102
-
2103
- opts = opts || {};
2104
- opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now
2105
- opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber
2106
-
2107
- // Warn about using preserveTimestamps on 32-bit node
2108
- if (opts.preserveTimestamps && process.arch === 'ia32') {
2109
- process.emitWarning(
2110
- 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' +
2111
- '\tsee https://github.com/jprichardson/node-fs-extra/issues/269',
2112
- 'Warning', 'fs-extra-WARN0002'
2113
- );
2114
- }
2115
-
2116
- const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts);
2117
- stat.checkParentPathsSync(src, srcStat, dest, 'copy');
2118
- if (opts.filter && !opts.filter(src, dest)) return
2119
- const destParent = path.dirname(dest);
2120
- if (!fs.existsSync(destParent)) mkdirsSync(destParent);
2121
- return getStats(destStat, src, dest, opts)
2122
- }
2123
-
2124
- function getStats (destStat, src, dest, opts) {
2125
- const statSync = opts.dereference ? fs.statSync : fs.lstatSync;
2126
- const srcStat = statSync(src);
2127
-
2128
- if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
2129
- else if (srcStat.isFile() ||
2130
- srcStat.isCharacterDevice() ||
2131
- srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)
2132
- else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
2133
- else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)
2134
- else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)
2135
- throw new Error(`Unknown file: ${src}`)
2136
- }
2137
-
2138
- function onFile (srcStat, destStat, src, dest, opts) {
2139
- if (!destStat) return copyFile(srcStat, src, dest, opts)
2140
- return mayCopyFile(srcStat, src, dest, opts)
2141
- }
2142
-
2143
- function mayCopyFile (srcStat, src, dest, opts) {
2144
- if (opts.overwrite) {
2145
- fs.unlinkSync(dest);
2146
- return copyFile(srcStat, src, dest, opts)
2147
- } else if (opts.errorOnExist) {
2148
- throw new Error(`'${dest}' already exists`)
2149
- }
2150
- }
2151
-
2152
- function copyFile (srcStat, src, dest, opts) {
2153
- fs.copyFileSync(src, dest);
2154
- if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest);
2155
- return setDestMode(dest, srcStat.mode)
2156
- }
2157
-
2158
- function handleTimestamps (srcMode, src, dest) {
2159
- // Make sure the file is writable before setting the timestamp
2160
- // otherwise open fails with EPERM when invoked with 'r+'
2161
- // (through utimes call)
2162
- if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode);
2163
- return setDestTimestamps(src, dest)
2164
- }
2165
-
2166
- function fileIsNotWritable (srcMode) {
2167
- return (srcMode & 0o200) === 0
2168
- }
2169
-
2170
- function makeFileWritable (dest, srcMode) {
2171
- return setDestMode(dest, srcMode | 0o200)
2172
- }
2173
-
2174
- function setDestMode (dest, srcMode) {
2175
- return fs.chmodSync(dest, srcMode)
2176
- }
2177
-
2178
- function setDestTimestamps (src, dest) {
2179
- // The initial srcStat.atime cannot be trusted
2180
- // because it is modified by the read(2) system call
2181
- // (See https://nodejs.org/api/fs.html#fs_stat_time_values)
2182
- const updatedSrcStat = fs.statSync(src);
2183
- return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime)
2184
- }
2185
-
2186
- function onDir (srcStat, destStat, src, dest, opts) {
2187
- if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts)
2188
- return copyDir(src, dest, opts)
2189
- }
2190
-
2191
- function mkDirAndCopy (srcMode, src, dest, opts) {
2192
- fs.mkdirSync(dest);
2193
- copyDir(src, dest, opts);
2194
- return setDestMode(dest, srcMode)
2195
- }
2196
-
2197
- function copyDir (src, dest, opts) {
2198
- const dir = fs.opendirSync(src);
2199
-
2200
- try {
2201
- let dirent;
2202
-
2203
- while ((dirent = dir.readSync()) !== null) {
2204
- copyDirItem(dirent.name, src, dest, opts);
2205
- }
2206
- } finally {
2207
- dir.closeSync();
2208
- }
2209
- }
2210
-
2211
- function copyDirItem (item, src, dest, opts) {
2212
- const srcItem = path.join(src, item);
2213
- const destItem = path.join(dest, item);
2214
- if (opts.filter && !opts.filter(srcItem, destItem)) return
2215
- const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts);
2216
- return getStats(destStat, srcItem, destItem, opts)
2217
- }
2218
-
2219
- function onLink (destStat, src, dest, opts) {
2220
- let resolvedSrc = fs.readlinkSync(src);
2221
- if (opts.dereference) {
2222
- resolvedSrc = path.resolve(process.cwd(), resolvedSrc);
2223
- }
2224
-
2225
- if (!destStat) {
2226
- return fs.symlinkSync(resolvedSrc, dest)
2227
- } else {
2228
- let resolvedDest;
2229
- try {
2230
- resolvedDest = fs.readlinkSync(dest);
2231
- } catch (err) {
2232
- // dest exists and is a regular file or directory,
2233
- // Windows may throw UNKNOWN error. If dest already exists,
2234
- // fs throws error anyway, so no need to guard against it here.
2235
- if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest)
2236
- throw err
2237
- }
2238
- if (opts.dereference) {
2239
- resolvedDest = path.resolve(process.cwd(), resolvedDest);
2240
- }
2241
- // If both symlinks resolve to the same target, they are still distinct symlinks
2242
- // that can be copied/overwritten. Only check subdirectory constraints when
2243
- // the resolved paths are different.
2244
- if (resolvedSrc !== resolvedDest) {
2245
- if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
2246
- throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
2247
- }
2248
-
2249
- // prevent copy if src is a subdir of dest since unlinking
2250
- // dest in this case would result in removing src contents
2251
- // and therefore a broken symlink would be created.
2252
- if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
2253
- throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
2254
- }
2255
- }
2256
- return copyLink(resolvedSrc, dest)
2257
- }
2258
- }
2259
-
2260
- function copyLink (resolvedSrc, dest) {
2261
- fs.unlinkSync(dest);
2262
- return fs.symlinkSync(resolvedSrc, dest)
2263
- }
2264
-
2265
- copySync_1 = copySync;
2266
- return copySync_1;
2267
- }
2268
-
2269
- var copy;
2270
- var hasRequiredCopy;
2271
-
2272
- function requireCopy () {
2273
- if (hasRequiredCopy) return copy;
2274
- hasRequiredCopy = 1;
2275
-
2276
- const u = requireUniversalify().fromPromise;
2277
- copy = {
2278
- copy: u(/*@__PURE__*/ requireCopy$1()),
2279
- copySync: /*@__PURE__*/ requireCopySync()
2280
- };
2281
- return copy;
2282
- }
2283
-
2284
- var remove_1;
2285
- var hasRequiredRemove;
2286
-
2287
- function requireRemove () {
2288
- if (hasRequiredRemove) return remove_1;
2289
- hasRequiredRemove = 1;
2290
-
2291
- const fs = requireGracefulFs();
2292
- const u = requireUniversalify().fromCallback;
2293
-
2294
- function remove (path, callback) {
2295
- fs.rm(path, { recursive: true, force: true }, callback);
2296
- }
2297
-
2298
- function removeSync (path) {
2299
- fs.rmSync(path, { recursive: true, force: true });
2300
- }
2301
-
2302
- remove_1 = {
2303
- remove: u(remove),
2304
- removeSync
2305
- };
2306
- return remove_1;
2307
- }
2308
-
2309
- var empty;
2310
- var hasRequiredEmpty;
2311
-
2312
- function requireEmpty () {
2313
- if (hasRequiredEmpty) return empty;
2314
- hasRequiredEmpty = 1;
2315
-
2316
- const u = requireUniversalify().fromPromise;
2317
- const fs = /*@__PURE__*/ requireFs();
2318
- const path = require$$1$1;
2319
- const mkdir = /*@__PURE__*/ requireMkdirs();
2320
- const remove = /*@__PURE__*/ requireRemove();
2321
-
2322
- const emptyDir = u(async function emptyDir (dir) {
2323
- let items;
2324
- try {
2325
- items = await fs.readdir(dir);
2326
- } catch {
2327
- return mkdir.mkdirs(dir)
2328
- }
2329
-
2330
- return Promise.all(items.map(item => remove.remove(path.join(dir, item))))
2331
- });
2332
-
2333
- function emptyDirSync (dir) {
2334
- let items;
2335
- try {
2336
- items = fs.readdirSync(dir);
2337
- } catch {
2338
- return mkdir.mkdirsSync(dir)
2339
- }
2340
-
2341
- items.forEach(item => {
2342
- item = path.join(dir, item);
2343
- remove.removeSync(item);
2344
- });
2345
- }
2346
-
2347
- empty = {
2348
- emptyDirSync,
2349
- emptydirSync: emptyDirSync,
2350
- emptyDir,
2351
- emptydir: emptyDir
2352
- };
2353
- return empty;
2354
- }
2355
-
2356
- var file;
2357
- var hasRequiredFile;
2358
-
2359
- function requireFile () {
2360
- if (hasRequiredFile) return file;
2361
- hasRequiredFile = 1;
2362
-
2363
- const u = requireUniversalify().fromPromise;
2364
- const path = require$$1$1;
2365
- const fs = /*@__PURE__*/ requireFs();
2366
- const mkdir = /*@__PURE__*/ requireMkdirs();
2367
-
2368
- async function createFile (file) {
2369
- let stats;
2370
- try {
2371
- stats = await fs.stat(file);
2372
- } catch { }
2373
- if (stats && stats.isFile()) return
2374
-
2375
- const dir = path.dirname(file);
2376
-
2377
- let dirStats = null;
2378
- try {
2379
- dirStats = await fs.stat(dir);
2380
- } catch (err) {
2381
- // if the directory doesn't exist, make it
2382
- if (err.code === 'ENOENT') {
2383
- await mkdir.mkdirs(dir);
2384
- await fs.writeFile(file, '');
2385
- return
2386
- } else {
2387
- throw err
2388
- }
2389
- }
2390
-
2391
- if (dirStats.isDirectory()) {
2392
- await fs.writeFile(file, '');
2393
- } else {
2394
- // parent is not a directory
2395
- // This is just to cause an internal ENOTDIR error to be thrown
2396
- await fs.readdir(dir);
2397
- }
2398
- }
2399
-
2400
- function createFileSync (file) {
2401
- let stats;
2402
- try {
2403
- stats = fs.statSync(file);
2404
- } catch { }
2405
- if (stats && stats.isFile()) return
2406
-
2407
- const dir = path.dirname(file);
2408
- try {
2409
- if (!fs.statSync(dir).isDirectory()) {
2410
- // parent is not a directory
2411
- // This is just to cause an internal ENOTDIR error to be thrown
2412
- fs.readdirSync(dir);
2413
- }
2414
- } catch (err) {
2415
- // If the stat call above failed because the directory doesn't exist, create it
2416
- if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir);
2417
- else throw err
2418
- }
2419
-
2420
- fs.writeFileSync(file, '');
2421
- }
2422
-
2423
- file = {
2424
- createFile: u(createFile),
2425
- createFileSync
2426
- };
2427
- return file;
2428
- }
2429
-
2430
- var link;
2431
- var hasRequiredLink;
2432
-
2433
- function requireLink () {
2434
- if (hasRequiredLink) return link;
2435
- hasRequiredLink = 1;
2436
-
2437
- const u = requireUniversalify().fromPromise;
2438
- const path = require$$1$1;
2439
- const fs = /*@__PURE__*/ requireFs();
2440
- const mkdir = /*@__PURE__*/ requireMkdirs();
2441
- const { pathExists } = /*@__PURE__*/ requirePathExists();
2442
- const { areIdentical } = /*@__PURE__*/ requireStat();
2443
-
2444
- async function createLink (srcpath, dstpath) {
2445
- let dstStat;
2446
- try {
2447
- dstStat = await fs.lstat(dstpath, { bigint: true });
2448
- } catch {
2449
- // ignore error
2450
- }
2451
-
2452
- let srcStat;
2453
- try {
2454
- srcStat = await fs.lstat(srcpath, { bigint: true });
2455
- } catch (err) {
2456
- err.message = err.message.replace('lstat', 'ensureLink');
2457
- throw err
2458
- }
2459
-
2460
- if (dstStat && areIdentical(srcStat, dstStat)) return
2461
-
2462
- const dir = path.dirname(dstpath);
2463
-
2464
- const dirExists = await pathExists(dir);
2465
-
2466
- if (!dirExists) {
2467
- await mkdir.mkdirs(dir);
2468
- }
2469
-
2470
- await fs.link(srcpath, dstpath);
2471
- }
2472
-
2473
- function createLinkSync (srcpath, dstpath) {
2474
- let dstStat;
2475
- try {
2476
- dstStat = fs.lstatSync(dstpath, { bigint: true });
2477
- } catch {}
2478
-
2479
- try {
2480
- const srcStat = fs.lstatSync(srcpath, { bigint: true });
2481
- if (dstStat && areIdentical(srcStat, dstStat)) return
2482
- } catch (err) {
2483
- err.message = err.message.replace('lstat', 'ensureLink');
2484
- throw err
2485
- }
2486
-
2487
- const dir = path.dirname(dstpath);
2488
- const dirExists = fs.existsSync(dir);
2489
- if (dirExists) return fs.linkSync(srcpath, dstpath)
2490
- mkdir.mkdirsSync(dir);
2491
-
2492
- return fs.linkSync(srcpath, dstpath)
2493
- }
2494
-
2495
- link = {
2496
- createLink: u(createLink),
2497
- createLinkSync
2498
- };
2499
- return link;
2500
- }
2501
-
2502
- var symlinkPaths_1;
2503
- var hasRequiredSymlinkPaths;
2504
-
2505
- function requireSymlinkPaths () {
2506
- if (hasRequiredSymlinkPaths) return symlinkPaths_1;
2507
- hasRequiredSymlinkPaths = 1;
2508
-
2509
- const path = require$$1$1;
2510
- const fs = /*@__PURE__*/ requireFs();
2511
- const { pathExists } = /*@__PURE__*/ requirePathExists();
2512
-
2513
- const u = requireUniversalify().fromPromise;
2514
-
2515
- /**
2516
- * Function that returns two types of paths, one relative to symlink, and one
2517
- * relative to the current working directory. Checks if path is absolute or
2518
- * relative. If the path is relative, this function checks if the path is
2519
- * relative to symlink or relative to current working directory. This is an
2520
- * initiative to find a smarter `srcpath` to supply when building symlinks.
2521
- * This allows you to determine which path to use out of one of three possible
2522
- * types of source paths. The first is an absolute path. This is detected by
2523
- * `path.isAbsolute()`. When an absolute path is provided, it is checked to
2524
- * see if it exists. If it does it's used, if not an error is returned
2525
- * (callback)/ thrown (sync). The other two options for `srcpath` are a
2526
- * relative url. By default Node's `fs.symlink` works by creating a symlink
2527
- * using `dstpath` and expects the `srcpath` to be relative to the newly
2528
- * created symlink. If you provide a `srcpath` that does not exist on the file
2529
- * system it results in a broken symlink. To minimize this, the function
2530
- * checks to see if the 'relative to symlink' source file exists, and if it
2531
- * does it will use it. If it does not, it checks if there's a file that
2532
- * exists that is relative to the current working directory, if does its used.
2533
- * This preserves the expectations of the original fs.symlink spec and adds
2534
- * the ability to pass in `relative to current working direcotry` paths.
2535
- */
2536
-
2537
- async function symlinkPaths (srcpath, dstpath) {
2538
- if (path.isAbsolute(srcpath)) {
2539
- try {
2540
- await fs.lstat(srcpath);
2541
- } catch (err) {
2542
- err.message = err.message.replace('lstat', 'ensureSymlink');
2543
- throw err
2544
- }
2545
-
2546
- return {
2547
- toCwd: srcpath,
2548
- toDst: srcpath
2549
- }
2550
- }
2551
-
2552
- const dstdir = path.dirname(dstpath);
2553
- const relativeToDst = path.join(dstdir, srcpath);
2554
-
2555
- const exists = await pathExists(relativeToDst);
2556
- if (exists) {
2557
- return {
2558
- toCwd: relativeToDst,
2559
- toDst: srcpath
2560
- }
2561
- }
2562
-
2563
- try {
2564
- await fs.lstat(srcpath);
2565
- } catch (err) {
2566
- err.message = err.message.replace('lstat', 'ensureSymlink');
2567
- throw err
2568
- }
2569
-
2570
- return {
2571
- toCwd: srcpath,
2572
- toDst: path.relative(dstdir, srcpath)
2573
- }
2574
- }
2575
-
2576
- function symlinkPathsSync (srcpath, dstpath) {
2577
- if (path.isAbsolute(srcpath)) {
2578
- const exists = fs.existsSync(srcpath);
2579
- if (!exists) throw new Error('absolute srcpath does not exist')
2580
- return {
2581
- toCwd: srcpath,
2582
- toDst: srcpath
2583
- }
2584
- }
2585
-
2586
- const dstdir = path.dirname(dstpath);
2587
- const relativeToDst = path.join(dstdir, srcpath);
2588
- const exists = fs.existsSync(relativeToDst);
2589
- if (exists) {
2590
- return {
2591
- toCwd: relativeToDst,
2592
- toDst: srcpath
2593
- }
2594
- }
2595
-
2596
- const srcExists = fs.existsSync(srcpath);
2597
- if (!srcExists) throw new Error('relative srcpath does not exist')
2598
- return {
2599
- toCwd: srcpath,
2600
- toDst: path.relative(dstdir, srcpath)
2601
- }
2602
- }
2603
-
2604
- symlinkPaths_1 = {
2605
- symlinkPaths: u(symlinkPaths),
2606
- symlinkPathsSync
2607
- };
2608
- return symlinkPaths_1;
2609
- }
2610
-
2611
- var symlinkType_1;
2612
- var hasRequiredSymlinkType;
2613
-
2614
- function requireSymlinkType () {
2615
- if (hasRequiredSymlinkType) return symlinkType_1;
2616
- hasRequiredSymlinkType = 1;
2617
-
2618
- const fs = /*@__PURE__*/ requireFs();
2619
- const u = requireUniversalify().fromPromise;
2620
-
2621
- async function symlinkType (srcpath, type) {
2622
- if (type) return type
2623
-
2624
- let stats;
2625
- try {
2626
- stats = await fs.lstat(srcpath);
2627
- } catch {
2628
- return 'file'
2629
- }
2630
-
2631
- return (stats && stats.isDirectory()) ? 'dir' : 'file'
2632
- }
2633
-
2634
- function symlinkTypeSync (srcpath, type) {
2635
- if (type) return type
2636
-
2637
- let stats;
2638
- try {
2639
- stats = fs.lstatSync(srcpath);
2640
- } catch {
2641
- return 'file'
2642
- }
2643
- return (stats && stats.isDirectory()) ? 'dir' : 'file'
2644
- }
2645
-
2646
- symlinkType_1 = {
2647
- symlinkType: u(symlinkType),
2648
- symlinkTypeSync
2649
- };
2650
- return symlinkType_1;
2651
- }
2652
-
2653
- var symlink;
2654
- var hasRequiredSymlink;
2655
-
2656
- function requireSymlink () {
2657
- if (hasRequiredSymlink) return symlink;
2658
- hasRequiredSymlink = 1;
2659
-
2660
- const u = requireUniversalify().fromPromise;
2661
- const path = require$$1$1;
2662
- const fs = /*@__PURE__*/ requireFs();
2663
-
2664
- const { mkdirs, mkdirsSync } = /*@__PURE__*/ requireMkdirs();
2665
-
2666
- const { symlinkPaths, symlinkPathsSync } = /*@__PURE__*/ requireSymlinkPaths();
2667
- const { symlinkType, symlinkTypeSync } = /*@__PURE__*/ requireSymlinkType();
2668
-
2669
- const { pathExists } = /*@__PURE__*/ requirePathExists();
2670
-
2671
- const { areIdentical } = /*@__PURE__*/ requireStat();
2672
-
2673
- async function createSymlink (srcpath, dstpath, type) {
2674
- let stats;
2675
- try {
2676
- stats = await fs.lstat(dstpath);
2677
- } catch { }
2678
-
2679
- if (stats && stats.isSymbolicLink()) {
2680
- // When srcpath is relative, resolve it relative to dstpath's directory
2681
- // (standard symlink behavior) or fall back to cwd if that doesn't exist
2682
- let srcStat;
2683
- if (path.isAbsolute(srcpath)) {
2684
- srcStat = await fs.stat(srcpath, { bigint: true });
2685
- } else {
2686
- const dstdir = path.dirname(dstpath);
2687
- const relativeToDst = path.join(dstdir, srcpath);
2688
- try {
2689
- srcStat = await fs.stat(relativeToDst, { bigint: true });
2690
- } catch {
2691
- srcStat = await fs.stat(srcpath, { bigint: true });
2692
- }
2693
- }
2694
-
2695
- const dstStat = await fs.stat(dstpath, { bigint: true });
2696
- if (areIdentical(srcStat, dstStat)) return
2697
- }
2698
-
2699
- const relative = await symlinkPaths(srcpath, dstpath);
2700
- srcpath = relative.toDst;
2701
- const toType = await symlinkType(relative.toCwd, type);
2702
- const dir = path.dirname(dstpath);
2703
-
2704
- if (!(await pathExists(dir))) {
2705
- await mkdirs(dir);
2706
- }
2707
-
2708
- return fs.symlink(srcpath, dstpath, toType)
2709
- }
2710
-
2711
- function createSymlinkSync (srcpath, dstpath, type) {
2712
- let stats;
2713
- try {
2714
- stats = fs.lstatSync(dstpath);
2715
- } catch { }
2716
- if (stats && stats.isSymbolicLink()) {
2717
- // When srcpath is relative, resolve it relative to dstpath's directory
2718
- // (standard symlink behavior) or fall back to cwd if that doesn't exist
2719
- let srcStat;
2720
- if (path.isAbsolute(srcpath)) {
2721
- srcStat = fs.statSync(srcpath, { bigint: true });
2722
- } else {
2723
- const dstdir = path.dirname(dstpath);
2724
- const relativeToDst = path.join(dstdir, srcpath);
2725
- try {
2726
- srcStat = fs.statSync(relativeToDst, { bigint: true });
2727
- } catch {
2728
- srcStat = fs.statSync(srcpath, { bigint: true });
2729
- }
2730
- }
2731
-
2732
- const dstStat = fs.statSync(dstpath, { bigint: true });
2733
- if (areIdentical(srcStat, dstStat)) return
2734
- }
2735
-
2736
- const relative = symlinkPathsSync(srcpath, dstpath);
2737
- srcpath = relative.toDst;
2738
- type = symlinkTypeSync(relative.toCwd, type);
2739
- const dir = path.dirname(dstpath);
2740
- const exists = fs.existsSync(dir);
2741
- if (exists) return fs.symlinkSync(srcpath, dstpath, type)
2742
- mkdirsSync(dir);
2743
- return fs.symlinkSync(srcpath, dstpath, type)
2744
- }
2745
-
2746
- symlink = {
2747
- createSymlink: u(createSymlink),
2748
- createSymlinkSync
2749
- };
2750
- return symlink;
2751
- }
2752
-
2753
- var ensure;
2754
- var hasRequiredEnsure;
2755
-
2756
- function requireEnsure () {
2757
- if (hasRequiredEnsure) return ensure;
2758
- hasRequiredEnsure = 1;
2759
-
2760
- const { createFile, createFileSync } = /*@__PURE__*/ requireFile();
2761
- const { createLink, createLinkSync } = /*@__PURE__*/ requireLink();
2762
- const { createSymlink, createSymlinkSync } = /*@__PURE__*/ requireSymlink();
2763
-
2764
- ensure = {
2765
- // file
2766
- createFile,
2767
- createFileSync,
2768
- ensureFile: createFile,
2769
- ensureFileSync: createFileSync,
2770
- // link
2771
- createLink,
2772
- createLinkSync,
2773
- ensureLink: createLink,
2774
- ensureLinkSync: createLinkSync,
2775
- // symlink
2776
- createSymlink,
2777
- createSymlinkSync,
2778
- ensureSymlink: createSymlink,
2779
- ensureSymlinkSync: createSymlinkSync
2780
- };
2781
- return ensure;
2782
- }
2783
-
2784
- var utils;
2785
- var hasRequiredUtils;
2786
-
2787
- function requireUtils () {
2788
- if (hasRequiredUtils) return utils;
2789
- hasRequiredUtils = 1;
2790
- function stringify (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) {
2791
- const EOF = finalEOL ? EOL : '';
2792
- const str = JSON.stringify(obj, replacer, spaces);
2793
-
2794
- if (str === undefined) {
2795
- throw new TypeError(`Converting ${typeof obj} value to JSON is not supported`)
2796
- }
2797
-
2798
- return str.replace(/\n/g, EOL) + EOF
2799
- }
2800
-
2801
- function stripBom (content) {
2802
- // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified
2803
- if (Buffer.isBuffer(content)) content = content.toString('utf8');
2804
- return content.replace(/^\uFEFF/, '')
2805
- }
2806
-
2807
- utils = { stringify, stripBom };
2808
- return utils;
2809
- }
2810
-
2811
- var jsonfile$1;
2812
- var hasRequiredJsonfile$1;
2813
-
2814
- function requireJsonfile$1 () {
2815
- if (hasRequiredJsonfile$1) return jsonfile$1;
2816
- hasRequiredJsonfile$1 = 1;
2817
- let _fs;
2818
- try {
2819
- _fs = requireGracefulFs();
2820
- } catch (_) {
2821
- _fs = require$$0$2;
2822
- }
2823
- const universalify = requireUniversalify();
2824
- const { stringify, stripBom } = requireUtils();
2825
-
2826
- async function _readFile (file, options = {}) {
2827
- if (typeof options === 'string') {
2828
- options = { encoding: options };
2829
- }
2830
-
2831
- const fs = options.fs || _fs;
2832
-
2833
- const shouldThrow = 'throws' in options ? options.throws : true;
2834
-
2835
- let data = await universalify.fromCallback(fs.readFile)(file, options);
2836
-
2837
- data = stripBom(data);
2838
-
2839
- let obj;
2840
- try {
2841
- obj = JSON.parse(data, options ? options.reviver : null);
2842
- } catch (err) {
2843
- if (shouldThrow) {
2844
- err.message = `${file}: ${err.message}`;
2845
- throw err
2846
- } else {
2847
- return null
2848
- }
2849
- }
2850
-
2851
- return obj
2852
- }
2853
-
2854
- const readFile = universalify.fromPromise(_readFile);
2855
-
2856
- function readFileSync (file, options = {}) {
2857
- if (typeof options === 'string') {
2858
- options = { encoding: options };
2859
- }
2860
-
2861
- const fs = options.fs || _fs;
2862
-
2863
- const shouldThrow = 'throws' in options ? options.throws : true;
2864
-
2865
- try {
2866
- let content = fs.readFileSync(file, options);
2867
- content = stripBom(content);
2868
- return JSON.parse(content, options.reviver)
2869
- } catch (err) {
2870
- if (shouldThrow) {
2871
- err.message = `${file}: ${err.message}`;
2872
- throw err
2873
- } else {
2874
- return null
2875
- }
2876
- }
2877
- }
2878
-
2879
- async function _writeFile (file, obj, options = {}) {
2880
- const fs = options.fs || _fs;
2881
-
2882
- const str = stringify(obj, options);
2883
-
2884
- await universalify.fromCallback(fs.writeFile)(file, str, options);
2885
- }
2886
-
2887
- const writeFile = universalify.fromPromise(_writeFile);
2888
-
2889
- function writeFileSync (file, obj, options = {}) {
2890
- const fs = options.fs || _fs;
2891
-
2892
- const str = stringify(obj, options);
2893
- // not sure if fs.writeFileSync returns anything, but just in case
2894
- return fs.writeFileSync(file, str, options)
2895
- }
2896
-
2897
- // NOTE: do not change this export format; required for ESM compat
2898
- // see https://github.com/jprichardson/node-jsonfile/pull/162 for details
2899
- jsonfile$1 = {
2900
- readFile,
2901
- readFileSync,
2902
- writeFile,
2903
- writeFileSync
2904
- };
2905
- return jsonfile$1;
2906
- }
2907
-
2908
- var jsonfile;
2909
- var hasRequiredJsonfile;
2910
-
2911
- function requireJsonfile () {
2912
- if (hasRequiredJsonfile) return jsonfile;
2913
- hasRequiredJsonfile = 1;
2914
-
2915
- const jsonFile = requireJsonfile$1();
2916
-
2917
- jsonfile = {
2918
- // jsonfile exports
2919
- readJson: jsonFile.readFile,
2920
- readJsonSync: jsonFile.readFileSync,
2921
- writeJson: jsonFile.writeFile,
2922
- writeJsonSync: jsonFile.writeFileSync
2923
- };
2924
- return jsonfile;
2925
- }
2926
-
2927
- var outputFile_1;
2928
- var hasRequiredOutputFile;
2929
-
2930
- function requireOutputFile () {
2931
- if (hasRequiredOutputFile) return outputFile_1;
2932
- hasRequiredOutputFile = 1;
2933
-
2934
- const u = requireUniversalify().fromPromise;
2935
- const fs = /*@__PURE__*/ requireFs();
2936
- const path = require$$1$1;
2937
- const mkdir = /*@__PURE__*/ requireMkdirs();
2938
- const pathExists = /*@__PURE__*/ requirePathExists().pathExists;
2939
-
2940
- async function outputFile (file, data, encoding = 'utf-8') {
2941
- const dir = path.dirname(file);
2942
-
2943
- if (!(await pathExists(dir))) {
2944
- await mkdir.mkdirs(dir);
2945
- }
2946
-
2947
- return fs.writeFile(file, data, encoding)
2948
- }
2949
-
2950
- function outputFileSync (file, ...args) {
2951
- const dir = path.dirname(file);
2952
- if (!fs.existsSync(dir)) {
2953
- mkdir.mkdirsSync(dir);
2954
- }
2955
-
2956
- fs.writeFileSync(file, ...args);
2957
- }
2958
-
2959
- outputFile_1 = {
2960
- outputFile: u(outputFile),
2961
- outputFileSync
2962
- };
2963
- return outputFile_1;
2964
- }
2965
-
2966
- var outputJson_1;
2967
- var hasRequiredOutputJson;
2968
-
2969
- function requireOutputJson () {
2970
- if (hasRequiredOutputJson) return outputJson_1;
2971
- hasRequiredOutputJson = 1;
2972
-
2973
- const { stringify } = requireUtils();
2974
- const { outputFile } = /*@__PURE__*/ requireOutputFile();
2975
-
2976
- async function outputJson (file, data, options = {}) {
2977
- const str = stringify(data, options);
2978
-
2979
- await outputFile(file, str, options);
2980
- }
2981
-
2982
- outputJson_1 = outputJson;
2983
- return outputJson_1;
2984
- }
2985
-
2986
- var outputJsonSync_1;
2987
- var hasRequiredOutputJsonSync;
2988
-
2989
- function requireOutputJsonSync () {
2990
- if (hasRequiredOutputJsonSync) return outputJsonSync_1;
2991
- hasRequiredOutputJsonSync = 1;
2992
-
2993
- const { stringify } = requireUtils();
2994
- const { outputFileSync } = /*@__PURE__*/ requireOutputFile();
2995
-
2996
- function outputJsonSync (file, data, options) {
2997
- const str = stringify(data, options);
2998
-
2999
- outputFileSync(file, str, options);
3000
- }
3001
-
3002
- outputJsonSync_1 = outputJsonSync;
3003
- return outputJsonSync_1;
3004
- }
3005
-
3006
- var json;
3007
- var hasRequiredJson;
3008
-
3009
- function requireJson () {
3010
- if (hasRequiredJson) return json;
3011
- hasRequiredJson = 1;
3012
-
3013
- const u = requireUniversalify().fromPromise;
3014
- const jsonFile = /*@__PURE__*/ requireJsonfile();
3015
-
3016
- jsonFile.outputJson = u(/*@__PURE__*/ requireOutputJson());
3017
- jsonFile.outputJsonSync = /*@__PURE__*/ requireOutputJsonSync();
3018
- // aliases
3019
- jsonFile.outputJSON = jsonFile.outputJson;
3020
- jsonFile.outputJSONSync = jsonFile.outputJsonSync;
3021
- jsonFile.writeJSON = jsonFile.writeJson;
3022
- jsonFile.writeJSONSync = jsonFile.writeJsonSync;
3023
- jsonFile.readJSON = jsonFile.readJson;
3024
- jsonFile.readJSONSync = jsonFile.readJsonSync;
3025
-
3026
- json = jsonFile;
3027
- return json;
3028
- }
3029
-
3030
- var move_1;
3031
- var hasRequiredMove$1;
3032
-
3033
- function requireMove$1 () {
3034
- if (hasRequiredMove$1) return move_1;
3035
- hasRequiredMove$1 = 1;
3036
-
3037
- const fs = /*@__PURE__*/ requireFs();
3038
- const path = require$$1$1;
3039
- const { copy } = /*@__PURE__*/ requireCopy();
3040
- const { remove } = /*@__PURE__*/ requireRemove();
3041
- const { mkdirp } = /*@__PURE__*/ requireMkdirs();
3042
- const { pathExists } = /*@__PURE__*/ requirePathExists();
3043
- const stat = /*@__PURE__*/ requireStat();
3044
-
3045
- async function move (src, dest, opts = {}) {
3046
- const overwrite = opts.overwrite || opts.clobber || false;
3047
-
3048
- const { srcStat, isChangingCase = false } = await stat.checkPaths(src, dest, 'move', opts);
3049
-
3050
- await stat.checkParentPaths(src, srcStat, dest, 'move');
3051
-
3052
- // If the parent of dest is not root, make sure it exists before proceeding
3053
- const destParent = path.dirname(dest);
3054
- const parsedParentPath = path.parse(destParent);
3055
- if (parsedParentPath.root !== destParent) {
3056
- await mkdirp(destParent);
3057
- }
3058
-
3059
- return doRename(src, dest, overwrite, isChangingCase)
3060
- }
3061
-
3062
- async function doRename (src, dest, overwrite, isChangingCase) {
3063
- if (!isChangingCase) {
3064
- if (overwrite) {
3065
- await remove(dest);
3066
- } else if (await pathExists(dest)) {
3067
- throw new Error('dest already exists.')
3068
- }
3069
- }
3070
-
3071
- try {
3072
- // Try w/ rename first, and try copy + remove if EXDEV
3073
- await fs.rename(src, dest);
3074
- } catch (err) {
3075
- if (err.code !== 'EXDEV') {
3076
- throw err
3077
- }
3078
- await moveAcrossDevice(src, dest, overwrite);
3079
- }
3080
- }
3081
-
3082
- async function moveAcrossDevice (src, dest, overwrite) {
3083
- const opts = {
3084
- overwrite,
3085
- errorOnExist: true,
3086
- preserveTimestamps: true
3087
- };
3088
-
3089
- await copy(src, dest, opts);
3090
- return remove(src)
3091
- }
3092
-
3093
- move_1 = move;
3094
- return move_1;
3095
- }
3096
-
3097
- var moveSync_1;
3098
- var hasRequiredMoveSync;
3099
-
3100
- function requireMoveSync () {
3101
- if (hasRequiredMoveSync) return moveSync_1;
3102
- hasRequiredMoveSync = 1;
3103
-
3104
- const fs = requireGracefulFs();
3105
- const path = require$$1$1;
3106
- const copySync = /*@__PURE__*/ requireCopy().copySync;
3107
- const removeSync = /*@__PURE__*/ requireRemove().removeSync;
3108
- const mkdirpSync = /*@__PURE__*/ requireMkdirs().mkdirpSync;
3109
- const stat = /*@__PURE__*/ requireStat();
3110
-
3111
- function moveSync (src, dest, opts) {
3112
- opts = opts || {};
3113
- const overwrite = opts.overwrite || opts.clobber || false;
3114
-
3115
- const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts);
3116
- stat.checkParentPathsSync(src, srcStat, dest, 'move');
3117
- if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest));
3118
- return doRename(src, dest, overwrite, isChangingCase)
3119
- }
3120
-
3121
- function isParentRoot (dest) {
3122
- const parent = path.dirname(dest);
3123
- const parsedPath = path.parse(parent);
3124
- return parsedPath.root === parent
3125
- }
3126
-
3127
- function doRename (src, dest, overwrite, isChangingCase) {
3128
- if (isChangingCase) return rename(src, dest, overwrite)
3129
- if (overwrite) {
3130
- removeSync(dest);
3131
- return rename(src, dest, overwrite)
3132
- }
3133
- if (fs.existsSync(dest)) throw new Error('dest already exists.')
3134
- return rename(src, dest, overwrite)
3135
- }
3136
-
3137
- function rename (src, dest, overwrite) {
3138
- try {
3139
- fs.renameSync(src, dest);
3140
- } catch (err) {
3141
- if (err.code !== 'EXDEV') throw err
3142
- return moveAcrossDevice(src, dest, overwrite)
3143
- }
3144
- }
3145
-
3146
- function moveAcrossDevice (src, dest, overwrite) {
3147
- const opts = {
3148
- overwrite,
3149
- errorOnExist: true,
3150
- preserveTimestamps: true
3151
- };
3152
- copySync(src, dest, opts);
3153
- return removeSync(src)
3154
- }
3155
-
3156
- moveSync_1 = moveSync;
3157
- return moveSync_1;
3158
- }
3159
-
3160
- var move;
3161
- var hasRequiredMove;
3162
-
3163
- function requireMove () {
3164
- if (hasRequiredMove) return move;
3165
- hasRequiredMove = 1;
3166
-
3167
- const u = requireUniversalify().fromPromise;
3168
- move = {
3169
- move: u(/*@__PURE__*/ requireMove$1()),
3170
- moveSync: /*@__PURE__*/ requireMoveSync()
3171
- };
3172
- return move;
3173
- }
3174
-
3175
- var lib;
3176
- var hasRequiredLib;
3177
-
3178
- function requireLib () {
3179
- if (hasRequiredLib) return lib;
3180
- hasRequiredLib = 1;
3181
-
3182
- lib = {
3183
- // Export promiseified graceful-fs:
3184
- .../*@__PURE__*/ requireFs(),
3185
- // Export extra methods:
3186
- .../*@__PURE__*/ requireCopy(),
3187
- .../*@__PURE__*/ requireEmpty(),
3188
- .../*@__PURE__*/ requireEnsure(),
3189
- .../*@__PURE__*/ requireJson(),
3190
- .../*@__PURE__*/ requireMkdirs(),
3191
- .../*@__PURE__*/ requireMove(),
3192
- .../*@__PURE__*/ requireOutputFile(),
3193
- .../*@__PURE__*/ requirePathExists(),
3194
- .../*@__PURE__*/ requireRemove()
3195
- };
3196
- return lib;
3197
- }
3198
-
3199
- var libExports = /*@__PURE__*/ requireLib();
3200
- var fs = /*@__PURE__*/index.getDefaultExportFromCjs(libExports);
3201
-
3202
- class AuthSessionError extends Error {
3203
- code;
3204
- constructor(message, code) {
3205
- super(message);
3206
- this.code = code;
3207
- this.name = 'AuthSessionError';
3208
- }
3209
- }
3210
- const AUTH_CACHE_VERSION = 1;
3211
- const paths = index.envPaths('hb-sdk', { suffix: '' });
3212
- function getAuthCacheFilePath(options = {}) {
3213
- return options.cacheFile ?? path.join(paths.cache, 'auth.json');
3214
- }
3215
- function createHeyboxAuthSession(payload, options = {}) {
3216
- return {
3217
- heyboxId: payload.heyboxId,
3218
- pkey: payload.pkey,
3219
- xXhhHeyboxId: payload.xXhhHeyboxId,
3220
- cookieHeader: createHeyboxCookieHeader(payload),
3221
- loginBaseUrl: resolveHeyboxLoginBaseUrl(options),
3222
- loggedInAt: (options.now?.() ?? new Date()).toISOString(),
3223
- };
3224
- }
3225
- async function readAuthCache(options = {}) {
3226
- const cacheFile = getAuthCacheFilePath(options);
3227
- if (!(await fs.pathExists(cacheFile))) {
3228
- return createEmptyAuthCache(options);
3229
- }
3230
- const parsed = (await fs.readJson(cacheFile));
3231
- if (parsed.version !== AUTH_CACHE_VERSION) {
3232
- throw new Error(`hb-sdk 登录缓存格式不受支持: version=${String(parsed.version)}`);
3233
- }
3234
- return {
3235
- version: AUTH_CACHE_VERSION,
3236
- updatedAt: typeof parsed.updatedAt === 'string' ? parsed.updatedAt : new Date(0).toISOString(),
3237
- ...(isHeyboxAuthSession(parsed.heybox) ? { heybox: normalizeHeyboxAuthSession(parsed.heybox) } : {}),
3238
- };
3239
- }
3240
- async function readHeyboxAuthSession(options = {}) {
3241
- const cache = await readAuthCache(options);
3242
- return cache.heybox;
3243
- }
3244
- async function requireHeyboxAuthSession(options = {}) {
3245
- const session = await readHeyboxAuthSession(options);
3246
- if (!session) {
3247
- throw new AuthSessionError('未发现 Heybox 登录态,请先运行 hb-sdk login', 'AUTH_SESSION_MISSING');
3248
- }
3249
- const expectedLoginBaseUrl = resolveHeyboxLoginBaseUrl(options);
3250
- if (session.loginBaseUrl !== expectedLoginBaseUrl) {
3251
- throw new Error([
3252
- 'Heybox CLI 登录环境不匹配。',
3253
- `当前登录态: ${session.loginBaseUrl}`,
3254
- `当前命令期望: ${expectedLoginBaseUrl}`,
3255
- `请运行: hb-sdk login --login-base-url ${expectedLoginBaseUrl}`,
3256
- ].join('\n'));
3257
- }
3258
- return session;
3259
- }
3260
- async function writeHeyboxAuthSession(session, options = {}) {
3261
- const cache = {
3262
- version: AUTH_CACHE_VERSION,
3263
- updatedAt: (options.now?.() ?? new Date()).toISOString(),
3264
- heybox: session,
3265
- };
3266
- return writeAuthCache(cache, options);
3267
- }
3268
- async function clearHeyboxAuthSession(options = {}) {
3269
- await fs.remove(getAuthCacheFilePath(options));
3270
- }
3271
- function createSelectedDeveloperEntitySnapshot(input, options = {}) {
3272
- return {
3273
- entityId: input.entityId,
3274
- entityName: input.entityName,
3275
- ...(input.ownerHeyboxId === undefined ? {} : { ownerHeyboxId: input.ownerHeyboxId }),
3276
- selectedAt: (options.now?.() ?? new Date()).toISOString(),
3277
- };
3278
- }
3279
- async function setSelectedDeveloperEntitySnapshot(input, options = {}) {
3280
- const cache = await readAuthCache(options);
3281
- if (!cache.heybox) {
3282
- throw new AuthSessionError('未发现 Heybox 登录态,请先运行 hb-sdk login', 'AUTH_SESSION_MISSING');
3283
- }
3284
- const selectedEntity = createSelectedDeveloperEntitySnapshot(input, options);
3285
- return writeAuthCache({
3286
- version: AUTH_CACHE_VERSION,
3287
- updatedAt: (options.now?.() ?? new Date()).toISOString(),
3288
- heybox: {
3289
- ...cache.heybox,
3290
- selectedEntity,
3291
- },
3292
- }, options);
3293
- }
3294
- async function readRedactedHeyboxAuthStatus(options = {}) {
3295
- const cacheFile = getAuthCacheFilePath(options);
3296
- const session = await readHeyboxAuthSession(options);
3297
- if (!session) {
3298
- return {
3299
- cacheFile,
3300
- loggedIn: false,
3301
- };
3302
- }
3303
- return {
3304
- cacheFile,
3305
- heyboxId: session.heyboxId,
3306
- loginBaseUrl: session.loginBaseUrl,
3307
- loggedIn: true,
3308
- loggedInAt: session.loggedInAt,
3309
- ...(session.selectedEntity ? { selectedEntity: session.selectedEntity } : {}),
3310
- };
3311
- }
3312
- async function writeAuthCache(cache, options = {}) {
3313
- const cacheFile = getAuthCacheFilePath(options);
3314
- await fs.ensureDir(path.dirname(cacheFile));
3315
- await fs.writeJson(cacheFile, cache, { spaces: 2 });
3316
- await fs.chmod(cacheFile, 0o600);
3317
- return cache;
3318
- }
3319
- function createEmptyAuthCache(options = {}) {
3320
- return {
3321
- version: AUTH_CACHE_VERSION,
3322
- updatedAt: (options.now?.() ?? new Date(0)).toISOString(),
3323
- };
3324
- }
3325
- function createHeyboxCookieHeader(payload) {
3326
- return [
3327
- createCookie('heybox_id', payload.heyboxId),
3328
- createCookie('user_heybox_id', payload.heyboxId),
3329
- createCookie('pkey', payload.pkey),
3330
- createCookie('user_pkey', payload.pkey),
3331
- createCookie('x_xhh_heyboxid', payload.xXhhHeyboxId),
3332
- ].join('; ');
3333
- }
3334
- function createCookie(name, value) {
3335
- return `${name}=${value}`;
3336
- }
3337
- function isHeyboxAuthSession(value) {
3338
- if (!isRecord(value)) {
3339
- return false;
3340
- }
3341
- return (typeof value.heyboxId === 'string' &&
3342
- typeof value.pkey === 'string' &&
3343
- typeof value.xXhhHeyboxId === 'string' &&
3344
- typeof value.cookieHeader === 'string' &&
3345
- (value.loginBaseUrl === undefined || typeof value.loginBaseUrl === 'string') &&
3346
- typeof value.loggedInAt === 'string');
3347
- }
3348
- function normalizeHeyboxAuthSession(session) {
3349
- const normalized = {
3350
- heyboxId: session.heyboxId,
3351
- pkey: session.pkey,
3352
- xXhhHeyboxId: session.xXhhHeyboxId,
3353
- cookieHeader: session.cookieHeader,
3354
- loggedInAt: session.loggedInAt,
3355
- loginBaseUrl: resolveHeyboxLoginBaseUrl({ loginBaseUrl: session.loginBaseUrl }),
3356
- };
3357
- const selectedEntity = normalizeSelectedDeveloperEntitySnapshot(session.selectedEntity);
3358
- if (selectedEntity) {
3359
- normalized.selectedEntity = selectedEntity;
3360
- }
3361
- return normalized;
3362
- }
3363
- function normalizeSelectedDeveloperEntitySnapshot(value) {
3364
- if (!isRecord(value)) {
3365
- return undefined;
3366
- }
3367
- if (typeof value.entityId !== 'number' || !Number.isFinite(value.entityId)) {
3368
- return undefined;
3369
- }
3370
- if (typeof value.entityName !== 'string' || value.entityName.length === 0) {
3371
- return undefined;
3372
- }
3373
- if (value.ownerHeyboxId !== undefined && (typeof value.ownerHeyboxId !== 'number' || !Number.isFinite(value.ownerHeyboxId))) {
3374
- return undefined;
3375
- }
3376
- if (typeof value.selectedAt !== 'string' || value.selectedAt.length === 0) {
3377
- return undefined;
3378
- }
3379
- return {
3380
- entityId: value.entityId,
3381
- entityName: value.entityName,
3382
- ...(value.ownerHeyboxId === undefined ? {} : { ownerHeyboxId: value.ownerHeyboxId }),
3383
- selectedAt: value.selectedAt,
3384
- };
3385
- }
3386
- function isRecord(value) {
3387
- return Object.prototype.toString.call(value) === '[object Object]';
3388
- }
3389
-
3390
- exports.HEYBOX_API_BASE_URL = HEYBOX_API_BASE_URL;
3391
- exports.clearHeyboxAuthSession = clearHeyboxAuthSession;
3392
- exports.createHeyboxApiUrl = createHeyboxApiUrl;
3393
- exports.createHeyboxAuthSession = createHeyboxAuthSession;
3394
- exports.createHeyboxOpenPlatformRequestContext = createHeyboxOpenPlatformRequestContext;
3395
- exports.getAuthCacheFilePath = getAuthCacheFilePath;
3396
- exports.readHeyboxApiEnvelope = readHeyboxApiEnvelope;
3397
- exports.readHeyboxAuthSession = readHeyboxAuthSession;
3398
- exports.readRedactedHeyboxAuthStatus = readRedactedHeyboxAuthStatus;
3399
- exports.requireHeyboxAuthSession = requireHeyboxAuthSession;
3400
- exports.resolveHeyboxApiBaseUrl = resolveHeyboxApiBaseUrl;
3401
- exports.resolveHeyboxLoginBaseUrl = resolveHeyboxLoginBaseUrl;
3402
- exports.resolveHeyboxOpenPlatformBaseUrl = resolveHeyboxOpenPlatformBaseUrl;
3403
- exports.setSelectedDeveloperEntitySnapshot = setSelectedDeveloperEntitySnapshot;
3404
- exports.writeHeyboxAuthSession = writeHeyboxAuthSession;