@e-mc/task 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,11 @@
1
+ Copyright 2023 An Pham
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4
+
5
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
6
+
7
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8
+
9
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
10
+
11
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ ### @e-mc/task
2
+
3
+ ### LICENSE
4
+
5
+ BSD 3-Clause
@@ -0,0 +1,5 @@
1
+ import type { TaskConstructor } from '../../types/lib';
2
+
3
+ declare const Gulp: TaskConstructor;
4
+
5
+ export = Gulp;
package/gulp/index.js ADDED
@@ -0,0 +1,333 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const path = require("path");
4
+ const fs = require("fs");
5
+ const child_process = require("child_process");
6
+ const stripansi = require("strip-ansi");
7
+ const which = require("which");
8
+ const types_1 = require("../../types");
9
+ const index_1 = require("../index");
10
+ const BIN_NPX = index_1.default.sanitizeCmd(which.sync('npx', { nothrow: true }) || 'npx');
11
+ const BIN_GULP = index_1.default.sanitizeCmd(which.sync("gulp" /* STRINGS.MODULE_NAME */, { nothrow: true }) || '');
12
+ const REGEXP_TIMESTAMP = /^\[\d+:\d+:\d+\]$/;
13
+ function executeTasks(assets, preceding, host) {
14
+ if (this.aborted) {
15
+ return Promise.reject((0, types_1.createAbortError)());
16
+ }
17
+ return this.allSettled(this.collate(assets, preceding), ['Execute tasks', "gulp" /* STRINGS.MODULE_NAME */]).then(result => {
18
+ if (host) {
19
+ for (const output of result) {
20
+ if (output.status === 'fulfilled') {
21
+ const { added, deleted } = output.value;
22
+ if (deleted) {
23
+ deleted.forEach(file => host.deleteFile(file));
24
+ }
25
+ if (added) {
26
+ added.forEach(file => host.add(file));
27
+ }
28
+ }
29
+ }
30
+ }
31
+ });
32
+ }
33
+ const normalizePath = (value) => process.platform === 'win32' ? '"' + value.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"' : index_1.default.sanitizeArgs(value);
34
+ class Gulp extends index_1.default {
35
+ constructor() {
36
+ super(...arguments);
37
+ this._moduleName = "gulp" /* STRINGS.MODULE_NAME */;
38
+ }
39
+ static finalize(instance, assets) {
40
+ return executeTasks.call(instance, assets, false, this);
41
+ }
42
+ using(data) {
43
+ return executeTasks.call(this, [data.file], true, data.host);
44
+ }
45
+ collate(assets, isPreceding = false) {
46
+ const settings = this.settings;
47
+ const taskMap = new Map();
48
+ const origMap = new Map();
49
+ const username = this.host?.username || '';
50
+ for (const item of assets) {
51
+ const localUri = item.localUri;
52
+ if (!localUri || !item.tasks || (0, types_1.ignoreFlag)(item.flags) || !this.canWrite(localUri, { ownPermissionOnly: true })) {
53
+ continue;
54
+ }
55
+ const origDir = path.dirname(localUri);
56
+ const scheduled = new Set();
57
+ for (let { task, handler, preceding } of item.tasks) {
58
+ if (task && handler === "gulp" /* STRINGS.MODULE_NAME */ && !!preceding === isPreceding) {
59
+ let gulpfile = (0, types_1.isString)(task) ? username && (0, types_1.isObject)(settings.users) && settings.users[username]?.[task] || settings[task] : task, tasks, opts;
60
+ if ((0, types_1.isObject)(gulpfile)) {
61
+ ({ path: gulpfile, tasks, opts } = gulpfile);
62
+ }
63
+ if ((0, types_1.isString)(gulpfile) && index_1.default.isPath(gulpfile = path.resolve(gulpfile), true) && ((0, types_1.isString)(task) || !this.canRead(gulpfile, { ownPermissionOnly: true }))) {
64
+ if (!scheduled.has((0, types_1.isString)(task) ? task : task = JSON.stringify(task))) {
65
+ let dirMap = taskMap.get(task);
66
+ if (!dirMap) {
67
+ taskMap.set(task, dirMap = new Map());
68
+ }
69
+ let sourceDir = dirMap.get(origDir);
70
+ if (!sourceDir) {
71
+ dirMap.set(origDir, sourceDir = { path: gulpfile, tasks, opts, items: [] });
72
+ }
73
+ sourceDir.items.push(localUri);
74
+ scheduled.add(task);
75
+ delete item.sourceUTF8;
76
+ delete item.buffer;
77
+ }
78
+ }
79
+ else {
80
+ if (!(0, types_1.isString)(task)) {
81
+ task = gulpfile && path.basename(gulpfile);
82
+ }
83
+ this.writeFail(["Unable to perform task" /* ERR_MESSAGE.PERFORM_TASK */, task ? "gulp" /* STRINGS.MODULE_NAME */ + ': ' + task : ''], (0, types_1.errorMessage)(task || "gulp" /* STRINGS.MODULE_NAME */, "Unknown" /* ERR_MESSAGE.UNKNOWN */, username), 4 /* LOG_TYPE.PROCESS */);
84
+ }
85
+ }
86
+ }
87
+ if (scheduled.size) {
88
+ const stored = origMap.get(origDir);
89
+ const items = Array.from(scheduled);
90
+ if (!stored) {
91
+ origMap.set(origDir, items);
92
+ continue;
93
+ }
94
+ let previous = -1;
95
+ for (const task of items.reverse()) {
96
+ const index = stored.indexOf(task);
97
+ if (index !== -1) {
98
+ if (index <= previous) {
99
+ previous = index;
100
+ continue;
101
+ }
102
+ stored.splice(index, 1);
103
+ }
104
+ if (previous !== -1) {
105
+ stored.splice(previous--, 0, task);
106
+ }
107
+ else {
108
+ stored.push(task);
109
+ previous = stored.length - 1;
110
+ }
111
+ }
112
+ }
113
+ }
114
+ const series = [];
115
+ const parallel = [];
116
+ for (const [task, dirMap] of taskMap) {
117
+ for (const [origDir, data] of dirMap) {
118
+ const item = origMap.get(origDir);
119
+ (item && item.length > 1 ? series : parallel).push({ task, origDir, data });
120
+ }
121
+ }
122
+ series.sort((a, b) => {
123
+ if (a.origDir === b.origDir && a.task !== b.task) {
124
+ const taskData = origMap.get(a.origDir);
125
+ const indexA = taskData.indexOf(a.task);
126
+ const indexB = taskData.indexOf(b.task);
127
+ if (indexA !== -1 && indexB !== -1) {
128
+ if (indexA < indexB) {
129
+ return -1;
130
+ }
131
+ if (indexB < indexA) {
132
+ return 1;
133
+ }
134
+ }
135
+ }
136
+ return 0;
137
+ });
138
+ const result = [];
139
+ if (series.length) {
140
+ result.push(this.series(series));
141
+ }
142
+ if (parallel.length) {
143
+ result.push(this.parallel(parallel));
144
+ }
145
+ return result;
146
+ }
147
+ queue(tasks) {
148
+ return tasks.map(item => new Promise(resolve => { this.spawn(item, (result) => { resolve(result); }); }));
149
+ }
150
+ async series(tasks) {
151
+ let added, deleted;
152
+ for await (const output of this.queue(tasks)) {
153
+ if (output) {
154
+ if (output.added) {
155
+ (added || (added = [])).push(...output.added);
156
+ }
157
+ if (output.deleted) {
158
+ (deleted || (deleted = [])).push(...output.deleted);
159
+ }
160
+ }
161
+ }
162
+ return { added, deleted };
163
+ }
164
+ parallel(tasks) {
165
+ return Promise.allSettled(this.queue(tasks)).then(result => {
166
+ let added, deleted, value;
167
+ for (const item of result) {
168
+ if (item.status === 'fulfilled' && (value = item.value)) {
169
+ if (value.added) {
170
+ (added || (added = [])).push(...value.added);
171
+ }
172
+ if (value.deleted) {
173
+ (deleted || (deleted = [])).push(...value.deleted);
174
+ }
175
+ }
176
+ }
177
+ return { added, deleted };
178
+ });
179
+ }
180
+ spawn(gulp, callback) {
181
+ const { task, origDir, data } = gulp;
182
+ const tempDir = this.getTempDir({ uuidDir: true });
183
+ const writeError = (value, err, hint, type = 32 /* LOG_TYPE.FILE */) => {
184
+ if (err) {
185
+ this.writeFail([value, hint || (this.moduleName + ': ' + task)], err, { type, startTime });
186
+ }
187
+ if (hint !== false) {
188
+ queueMicrotask(() => index_1.default.removeDir(tempDir));
189
+ callback();
190
+ }
191
+ };
192
+ if (!tempDir) {
193
+ writeError("Unable to create temp directory" /* ERR_MESSAGE.TEMP_DIRECTORY */, null, this.getTempDir());
194
+ return;
195
+ }
196
+ let { path: gulpfile, tasks, opts, items } = data;
197
+ if (!Array.isArray(tasks)) {
198
+ tasks = (0, types_1.isString)(tasks) ? [tasks] : [task];
199
+ }
200
+ if (!Array.isArray(opts)) {
201
+ opts = (0, types_1.isString)(opts) ? [opts] : [];
202
+ }
203
+ for (let i = 0; i < opts.length; ++i) {
204
+ switch (opts[i]) {
205
+ case '--verify':
206
+ case '--compact-tasks':
207
+ case '--sort-tasks':
208
+ case '--color':
209
+ case '--no-color':
210
+ case '--silent':
211
+ case '--continue':
212
+ case '--series':
213
+ case '--log-level':
214
+ case '-S':
215
+ case '-L':
216
+ case '-LL':
217
+ case '-LLL':
218
+ case '-LLLL':
219
+ continue;
220
+ case '--require':
221
+ if (i < opts.length - 1) {
222
+ ++i;
223
+ continue;
224
+ }
225
+ break;
226
+ case '--tasks-depth':
227
+ case '--depth':
228
+ if (!isNaN(+opts[i + 1])) {
229
+ ++i;
230
+ continue;
231
+ }
232
+ break;
233
+ }
234
+ opts.splice(i--, 1);
235
+ }
236
+ const startTime = process.hrtime();
237
+ const broadcastId = this.broadcastId;
238
+ this.formatMessage(4 /* LOG_TYPE.PROCESS */, "gulp" /* STRINGS.MODULE_NAME */, ['Executing task...', task], gulpfile);
239
+ Promise.all(items.map(src => fs.promises.copyFile(src, path.join(tempDir, path.basename(src)))))
240
+ .then(() => {
241
+ try {
242
+ const args = [...index_1.default.sanitizeArgs(tasks), ...opts, '--gulpfile', `${normalizePath(gulpfile)}`, '--cwd', `${normalizePath(tempDir)}`];
243
+ if (!BIN_GULP) {
244
+ args.unshift('gulp');
245
+ }
246
+ let out = '', timeStamp = '', message = '';
247
+ const setMessage = (type, value) => {
248
+ if (REGEXP_TIMESTAMP.test(stripansi(value = value.trim()))) {
249
+ timeStamp = value + ' ';
250
+ }
251
+ else {
252
+ this.formatMessage(type, '', timeStamp + value, null, { sessionId: '' });
253
+ timeStamp = '';
254
+ }
255
+ };
256
+ const { stdout, stderr } = child_process.spawn(BIN_GULP || BIN_NPX, args, { cwd: process.cwd(), shell: true, stdio: index_1.default.hasLogType(32768 /* LOG_TYPE.STDOUT */) && !broadcastId ? 'inherit' : undefined, signal: this.signal })
257
+ .on('exit', code => {
258
+ if (!code) {
259
+ this.addLog(types_1.STATUS_TYPE.INFO, out);
260
+ const result = new Set();
261
+ let added, deleted;
262
+ try {
263
+ const files = fs.readdirSync(tempDir);
264
+ for (let i = 0, copy; i < files.length; ++i) {
265
+ const filename = files[i];
266
+ try {
267
+ const dest = path.join(origDir, filename);
268
+ if (!result.has(dest)) {
269
+ const src = path.join(tempDir, filename);
270
+ if (copy) {
271
+ fs.copyFileSync(src, dest);
272
+ }
273
+ else {
274
+ fs.renameSync(src, dest);
275
+ }
276
+ result.add(dest);
277
+ }
278
+ }
279
+ catch (err) {
280
+ if (!copy && index_1.default.isErrorCode(err, 'EXDEV')) {
281
+ copy = true;
282
+ --i;
283
+ }
284
+ else {
285
+ this.writeFail(["Unable to rename file" /* ERR_MESSAGE.RENAME_FILE */, filename], err, 32 /* LOG_TYPE.FILE */);
286
+ }
287
+ }
288
+ }
289
+ this.writeTimeProcess("gulp" /* STRINGS.MODULE_NAME */, task + ' -> ' + path.basename(items[0]), startTime);
290
+ }
291
+ catch (err) {
292
+ writeError("Unable to read directory" /* ERR_MESSAGE.READ_DIRECTORY */, err, false);
293
+ }
294
+ items.forEach(value => !result.has(value) && (deleted || (deleted = [])).push(value));
295
+ result.forEach(value => !items.includes(value) && (added || (added = [])).push(value));
296
+ queueMicrotask(() => index_1.default.removeDir(tempDir));
297
+ callback({ added, deleted });
298
+ }
299
+ else {
300
+ writeError("Unable to execute file" /* ERR_MESSAGE.EXECUTE_FILE */, new Error(message || "Unknown" /* ERR_MESSAGE.UNKNOWN */), '', 4 /* LOG_TYPE.PROCESS */);
301
+ }
302
+ })
303
+ .on('error', err => writeError("Unknown" /* ERR_MESSAGE.UNKNOWN */, err, false, 4 /* LOG_TYPE.PROCESS */));
304
+ if (stdout) {
305
+ stdout.setEncoding('utf-8').on('data', (value) => {
306
+ if (broadcastId) {
307
+ setMessage(types_1.STATUS_TYPE.INFO, value);
308
+ }
309
+ out += value;
310
+ });
311
+ }
312
+ if (stderr) {
313
+ stderr.setEncoding('utf-8').on('data', (value) => {
314
+ if (broadcastId) {
315
+ setMessage(types_1.STATUS_TYPE.ERROR, value);
316
+ }
317
+ message += value;
318
+ });
319
+ }
320
+ }
321
+ catch (err) {
322
+ writeError("Unable to execute file" /* ERR_MESSAGE.EXECUTE_FILE */, err);
323
+ }
324
+ })
325
+ .catch(err => writeError("Unable to copy file" /* ERR_MESSAGE.COPY_FILE */, err, tempDir));
326
+ }
327
+ }
328
+ exports.default = Gulp;
329
+
330
+ if (exports.default) {
331
+ module.exports = exports.default;
332
+ module.exports.default = exports.default;
333
+ }
package/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { TaskConstructor } from '../types/lib';
2
+
3
+ declare const Task: TaskConstructor;
4
+
5
+ export = Task;
package/index.js ADDED
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const core_1 = require("../core");
4
+ class Task extends core_1.Client {
5
+ static finalize(instance, assets) {
6
+ return Promise.resolve();
7
+ }
8
+ }
9
+ exports.default = Task;
10
+
11
+ if (exports.default) {
12
+ module.exports = exports.default;
13
+ module.exports.default = exports.default;
14
+ }
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "@e-mc/task",
3
+ "version": "0.0.1",
4
+ "description": "Task constructor for e-mc.",
5
+ "main": "index.js",
6
+ "types": "index.d.ts",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/anpham6/e-mc.git",
13
+ "directory": "src/task"
14
+ },
15
+ "keywords": [
16
+ "squared",
17
+ "squared-functions"
18
+ ],
19
+ "author": "An Pham <anpham6@gmail.com>",
20
+ "license": "BSD 3-Clause",
21
+ "homepage": "https://github.com/anpham6/e-mc#readme",
22
+ "dependencies": {
23
+ "@e-mc/core": "0.0.1",
24
+ "strip-ansi": "6.0.1",
25
+ "which": "^2.0.2"
26
+ }
27
+ }