funkophile 0.0.6 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ import { createSelector } from "reselect";
2
+ export const contentsOfFiles = (selector) => {
3
+ return createSelector([selector], (selected) => {
4
+ return Object.keys(selected).reduce((mm, k) => mm + selected[k], "");
5
+ });
6
+ };
7
+ export const contentOfFile = (selector) => {
8
+ return createSelector([selector], (selected) => {
9
+ try {
10
+ return selected[Object.keys(selected)[0]];
11
+ }
12
+ catch (e) {
13
+ console.error("error in contentOfFile", e);
14
+ console.error("selected", selected);
15
+ console.error("selector", selector);
16
+ process.exit(-1);
17
+ }
18
+ });
19
+ };
20
+ export const srcAndContentOfFile = (selector, key) => {
21
+ return createSelector([selector], (selected) => {
22
+ return {
23
+ src: key,
24
+ content: selected[key],
25
+ };
26
+ });
27
+ };
28
+ export const srcAndContentOfFiles = (selector) => {
29
+ return createSelector([selector], (selected) => {
30
+ const keys = Object.keys(selected);
31
+ return keys.map((key) => {
32
+ return {
33
+ src: key,
34
+ content: selected[key],
35
+ };
36
+ });
37
+ });
38
+ };
@@ -0,0 +1,2 @@
1
+ declare const _default: (funkophileConfig: any) => void;
2
+ export default _default;
@@ -0,0 +1,305 @@
1
+ import chokidar from "chokidar";
2
+ import { createSelector } from "reselect";
3
+ import { createStore } from "redux";
4
+ import fs from "fs";
5
+ import fse from "fs-extra";
6
+ import glob from "glob-promise";
7
+ import path from "path";
8
+ import Promise from "bluebird";
9
+ export default (funkophileConfig) => {
10
+ Promise.config({
11
+ cancellation: true,
12
+ });
13
+ const INITIALIZE = "INITIALIZE";
14
+ const UPSERT = "UPSERT";
15
+ const REMOVE = "REMOVE";
16
+ const previousState = {};
17
+ let outputPromise = Promise.resolve();
18
+ const logger = {
19
+ watchError: (p) => console.log("\u001b[7m ! \u001b[0m" + p),
20
+ watchReady: (p) => console.log("\u001b[7m\u001b[36m < \u001b[0m" + p),
21
+ watchAdd: (p) => console.log("\u001b[7m\u001b[34m + \u001b[0m./" + p),
22
+ watchChange: (p) => console.log("\u001b[7m\u001b[35m * \u001b[0m" + p),
23
+ watchUnlink: (p) => console.log("\u001b[7m\u001b[31m - \u001b[0m./" + p),
24
+ stateChange: () => console.log("\u001b[7m\u001b[31m --- Redux state changed --- \u001b[0m"),
25
+ cleaningEmptyfolder: (p) => console.log("\u001b[31m\u001b[7m XXX! \u001b[0m" + p),
26
+ readingFile: (p) => console.log("\u001b[31m <-- \u001b[0m" + p),
27
+ removedFile: (p) => console.log("\u001b[31m\u001b[7m ??? \u001b[0m./" + p),
28
+ writingString: (p) => console.log("\u001b[32m --> \u001b[0m" + p),
29
+ writingFunction: (p) => console.log("\u001b[33m ... \u001b[0m" + p),
30
+ writingPromise: (p) => console.log("\u001b[33m ... \u001b[0m" + p),
31
+ writingError: (p, message) => console.log("\u001b[31m !!! \u001b[0m" + p + " " + message),
32
+ waiting: () => console.log("\u001b[7m Funkophile is done for now but waiting on changes...\u001b[0m "),
33
+ done: () => console.log("\u001b[7m Funkophile is done!\u001b[0m "),
34
+ };
35
+ function cleanEmptyFoldersRecursively(folder) {
36
+ var isDir = fs.statSync(folder).isDirectory();
37
+ if (!isDir) {
38
+ return;
39
+ }
40
+ var files = fs.readdirSync(folder);
41
+ if (files.length > 0) {
42
+ files.forEach(function (file) {
43
+ var fullPath = path.join(folder, file);
44
+ });
45
+ // re-evaluate files; after deleting subfolder
46
+ // we may have parent folder empty now
47
+ files = fs.readdirSync(folder);
48
+ }
49
+ if (files.length == 0) {
50
+ logger.cleaningEmptyfolder(folder);
51
+ fs.rmdirSync(folder);
52
+ return;
53
+ }
54
+ }
55
+ const dispatchUpsert = (store, key, file, encodings) => {
56
+ const fileType = file.split(".").slice(-2, -1)[0];
57
+ let encoding = Object.keys(encodings).find((e) => encodings[e].includes(fileType));
58
+ if (!fileType || !encoding) {
59
+ console.log(`Unknown file type for `, file, `Defaulting to utf8`);
60
+ encoding = "utf8";
61
+ }
62
+ // console.log("dispatchUpsert", encoding, file)
63
+ logger.readingFile(file);
64
+ store.dispatch({
65
+ type: UPSERT,
66
+ payload: {
67
+ key: key,
68
+ src: file,
69
+ contents: fse.readFileSync(file, encoding),
70
+ },
71
+ });
72
+ };
73
+ function omit(key, obj) {
74
+ const { [key]: omitted, ...rest } = obj;
75
+ return rest;
76
+ }
77
+ const store = createStore((state = {
78
+ initialLoad: true,
79
+ ...funkophileConfig.initialState,
80
+ timestamp: Date.now(),
81
+ }, action) => {
82
+ // console.log("\u001b[7m\u001b[35m ||| Redux recieved action \u001b[0m", action.type)
83
+ if (!action.type.includes("@@redux")) {
84
+ if (action.type === INITIALIZE) {
85
+ return {
86
+ ...state,
87
+ initialLoad: false,
88
+ timestamp: Date.now(),
89
+ };
90
+ }
91
+ else if (action.type === UPSERT) {
92
+ return {
93
+ ...state,
94
+ [action["payload"].key]: {
95
+ ...state[action.payload.key],
96
+ ...{
97
+ [action["payload"].src]: action["payload"].contents,
98
+ },
99
+ },
100
+ timestamp: Date.now(),
101
+ };
102
+ }
103
+ else if (action.type === REMOVE) {
104
+ return {
105
+ ...state,
106
+ [action["payload"].key]: omit(action["payload"].file, state[action["payload"].key]),
107
+ timestamp: Date.now(),
108
+ };
109
+ }
110
+ else {
111
+ console.error("Redux was asked to handle an unknown action type: " +
112
+ action.type);
113
+ process.exit(-1);
114
+ }
115
+ // return state
116
+ }
117
+ });
118
+ const finalSelector = funkophileConfig.outputs(Object.keys(funkophileConfig.inputs).reduce((mm, inputKey) => {
119
+ return {
120
+ ...mm,
121
+ [inputKey]: createSelector([(x) => x], (root) => root[inputKey]),
122
+ };
123
+ }, {}));
124
+ // Wait for all the file watchers to check in
125
+ Promise.all(Object.keys(funkophileConfig.inputs)
126
+ .map((inputRuleKey) => {
127
+ const p = path.resolve(`./${funkophileConfig.options.inFolder}/${funkophileConfig.inputs[inputRuleKey] || ""}`);
128
+ return new Promise((fulfill, reject) => {
129
+ if (mode === "build") {
130
+ glob(p, {})
131
+ .then((files) => {
132
+ files.forEach((file) => {
133
+ dispatchUpsert(store, inputRuleKey, file, funkophileConfig.encodings);
134
+ });
135
+ })
136
+ .then(() => {
137
+ fulfill();
138
+ });
139
+ }
140
+ else if (mode === "watch") {
141
+ chokidar
142
+ .watch(p, {})
143
+ .on("error", (error) => {
144
+ logger.watchError(p);
145
+ })
146
+ .on("ready", () => {
147
+ logger.watchReady(p);
148
+ fulfill();
149
+ })
150
+ .on("add", (p) => {
151
+ logger.watchAdd(p);
152
+ dispatchUpsert(store, inputRuleKey, "./" + p, funkophileConfig.encodings);
153
+ })
154
+ .on("change", (p) => {
155
+ logger.watchChange(p);
156
+ dispatchUpsert(store, inputRuleKey, "./" + p, funkophileConfig.encodings);
157
+ })
158
+ .on("unlink", (p) => {
159
+ logger.watchUnlink(p);
160
+ store.dispatch({
161
+ type: REMOVE,
162
+ payload: {
163
+ key: inputRuleKey,
164
+ file: "./" + p,
165
+ },
166
+ });
167
+ })
168
+ .on("unlinkDir", (p) => {
169
+ logger.watchUnlink(p);
170
+ });
171
+ // .on('raw', (event, p, details) => { // internal
172
+ // log('Raw event info:', event, p, details);
173
+ // })
174
+ }
175
+ else {
176
+ console.error(`The 3rd argument should be 'watch' or 'build', not "${mode}"`);
177
+ process.exit(-1);
178
+ }
179
+ });
180
+ })).then(function () {
181
+ // listen for changes to the store
182
+ store.subscribe(() => {
183
+ const s = store.getState();
184
+ logger.stateChange();
185
+ const outputs = finalSelector(s);
186
+ if (outputPromise.isPending()) {
187
+ console.log("cancelling previous write!");
188
+ outputPromise.cancel();
189
+ }
190
+ outputPromise = Promise.all(Array.from(new Set(Object.keys(previousState).concat(Object.keys(outputs)))).map((key) => {
191
+ return new Promise((fulfill, reject) => {
192
+ if (!outputs[key]) {
193
+ const file = funkophileConfig.options.outFolder + "/" + key;
194
+ logger.removedFile(file);
195
+ try {
196
+ fse.unlinkSync("./" + file);
197
+ cleanEmptyFoldersRecursively("./" + file.substring(0, file.lastIndexOf("/")));
198
+ }
199
+ catch (ex) {
200
+ // console.error('inner', ex.message);
201
+ // throw ex;
202
+ }
203
+ finally {
204
+ // console.log('finally');
205
+ return;
206
+ }
207
+ // delete previousState[key]
208
+ // fulfill()
209
+ }
210
+ else {
211
+ if (outputs[key] !== previousState[key]) {
212
+ previousState[key] = outputs[key];
213
+ const relativeFilePath = "./" + funkophileConfig.options.outFolder + "/" + key;
214
+ const contents = outputs[key];
215
+ if (typeof contents === "function") {
216
+ logger.writingFunction(relativeFilePath);
217
+ contents((err, res) => {
218
+ fse.outputFile(relativeFilePath, res, fulfill);
219
+ logger.writingString(relativeFilePath);
220
+ });
221
+ }
222
+ else if (typeof contents === "string") {
223
+ fse.outputFile(relativeFilePath, contents, fulfill);
224
+ logger.writingString(relativeFilePath);
225
+ }
226
+ else if (Buffer.isBuffer(contents)) {
227
+ fse.outputFile(relativeFilePath, contents, fulfill);
228
+ logger.writingString(relativeFilePath);
229
+ }
230
+ else if (Array.isArray(contents)) {
231
+ fse.outputFile(relativeFilePath, JSON.stringify(contents), fulfill);
232
+ logger.writingString(relativeFilePath);
233
+ }
234
+ else if (typeof contents.then === "function") {
235
+ logger.writingPromise(relativeFilePath);
236
+ Promise.resolve(contents).then(function (value) {
237
+ if (value instanceof Error) {
238
+ logger.writingError(relativeFilePath, value.message);
239
+ }
240
+ else {
241
+ fse.outputFile(relativeFilePath, value, fulfill);
242
+ logger.writingString(relativeFilePath);
243
+ }
244
+ }, function (value) {
245
+ // not called
246
+ });
247
+ }
248
+ else if (typeof contents === "object") {
249
+ fse.outputFile(relativeFilePath, JSON.stringify(contents), fulfill);
250
+ logger.writingString(relativeFilePath);
251
+ }
252
+ else {
253
+ console.log(`I don't recognize what this is but I will try to write it to a file: ` +
254
+ relativeFilePath, typeof contents, contents);
255
+ fse.outputFile(relativeFilePath, contents, fulfill);
256
+ logger.writingString(relativeFilePath);
257
+ }
258
+ }
259
+ else {
260
+ fulfill();
261
+ }
262
+ }
263
+ });
264
+ })).then(() => {
265
+ cleanEmptyFoldersRecursively(funkophileConfig.options.outFolder);
266
+ if (mode === "build") {
267
+ logger.done();
268
+ }
269
+ else if (mode === "watch") {
270
+ logger.waiting();
271
+ }
272
+ else {
273
+ console.error(`The 3rd argument should be 'watch' or 'build', not "${mode}"`);
274
+ process.exit(-1);
275
+ }
276
+ });
277
+ });
278
+ // lastly, turn the store `on`.
279
+ // This is to prevent unecessary recomputations when initialy adding files to redux
280
+ store.dispatch({
281
+ type: INITIALIZE,
282
+ payload: true,
283
+ });
284
+ });
285
+ };
286
+ // export default () => {
287
+ // if (
288
+ // process.argv[2] &&
289
+ // (process.argv[3] === "watch" || process.argv[3] === "build")
290
+ // ) {
291
+ // const configFile = path.resolve(process.argv[2]);
292
+ // const mode = process.argv[3];
293
+ // // console.log("configfile", configFile);
294
+ // import(configFile).then((funkophileConfigModule) => {
295
+ // const funkophileConfig = funkophileConfigModule.default;
296
+ // // console.log("funkophileConfig", (funkophileConfig));
297
+ // });
298
+ // } else {
299
+ // console.error("command line arguments do not make sense");
300
+ // console.error("first argument should be a funkophile config file");
301
+ // console.error("second argument should be a 'build' or 'watch'");
302
+ // console.error("You passed", process.argv);
303
+ // process.exit(-1);
304
+ // }
305
+ // };