-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutil.modules.js
More file actions
285 lines (233 loc) · 8.15 KB
/
util.modules.js
File metadata and controls
285 lines (233 loc) · 8.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// util.modules.js
const fs = require("node:fs");
const path = require("node:path");
const { execSync } = require("node:child_process");
const git = require("./util.git");
// global waw root (where waw is installed)
const wawRoot = path.dirname(require.resolve("waw"));
const j = (p) => {
try {
return JSON.parse(fs.readFileSync(p, "utf8"));
} catch {
return {};
}
};
const walk = (dir, out = []) => {
for (const n of fs.readdirSync(dir)) {
if (n === "node_modules" || n === ".git") continue;
const p = path.join(dir, n);
const s = fs.lstatSync(p);
s.isDirectory() ? walk(p, out) : out.push(p);
}
return out;
};
// --- tiny semver helpers (enough for waw-style deps) ---
const parseVer = (v) => {
const m = ("" + v).trim().match(/^(\d+)\.(\d+)\.(\d+)/);
return m ? [parseInt(m[1]), parseInt(m[2]), parseInt(m[3])] : null;
};
const cmp = (a, b) => {
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
return 0;
};
const satisfies = (installed, wanted) => {
if (!wanted || wanted === "*" || wanted === "latest") return true;
const i = parseVer(installed);
if (!i) return false;
const w = ("" + wanted).trim();
if (/^\d+\.\d+\.\d+$/.test(w)) return installed.startsWith(w);
const wv = parseVer(w.replace(/^[^\d]*/, ""));
if (!wv) return false;
if (w.startsWith("^")) {
// ^1.2.3 => same major, >= 1.2.3
return i[0] === wv[0] && cmp(i, wv) >= 0;
}
if (w.startsWith("~")) {
// ~1.2.3 => same major+minor, >= 1.2.3
return i[0] === wv[0] && i[1] === wv[1] && cmp(i, wv) >= 0;
}
if (w.startsWith(">=")) return cmp(i, wv) >= 0;
// fallback: if it contains a number, treat it as exact prefix match
return installed.startsWith(wv.join("."));
};
const installedVersion = (moduleRoot, name) => {
try {
const pj = path.join(moduleRoot, "node_modules", name, "package.json");
return j(pj).version || "";
} catch {
return "";
}
};
const orange = (s) => `\x1b[38;2;255;165;0m${s}\x1b[0m`;
const ensureDeps = (moduleRoot, deps) => {
if (!deps || typeof deps !== "object") return;
let needsInstall = false;
// 1) detect if anything is missing / incompatible
for (const name of Object.keys(deps)) {
const wanted = deps[name];
const has = installedVersion(moduleRoot, name);
if (!has || !satisfies(has, wanted)) {
needsInstall = true;
break;
}
}
if (!needsInstall) return;
// 2) install ALL declared deps in one shot (stable resolution)
const installAll = [];
const namesPretty = [];
for (const name of Object.keys(deps)) {
const wanted = deps[name];
namesPretty.push(name);
if (!wanted || wanted === "*" || wanted === "latest") installAll.push(name);
else installAll.push(`${name}@${wanted}`);
}
console.log(
`Installing node module${namesPretty.length ? "s" : ''} ${orange(namesPretty.join(", "))} at module ${orange(
path.basename(moduleRoot)
)}`
);
const cmd =
`npm i --prefix ${JSON.stringify(moduleRoot)} ` +
`--workspaces=false --include-workspace-root=false ` +
`--legacy-peer-deps --no-save --no-package-lock --no-fund --no-audit --loglevel=error ` +
installAll.join(" ");
execSync(cmd, { cwd: moduleRoot, stdio: "inherit" });
};
const load = (dir, name, isGlobal) => {
const part = path.join(dir, "part.json");
const mod = path.join(dir, "module.json");
if (fs.existsSync(part) && !fs.existsSync(mod)) try { fs.renameSync(part, mod); } catch {}
if (!fs.existsSync(mod)) return;
const m = j(mod);
m.rootPath = m.__root = path.normalize(dir);
m.__name = name;
m.__global = !!isGlobal;
// install deps declared by module itself
ensureDeps(m.__root, m.dependencies);
// files snapshot (after install; still excludes node_modules)
m.files = walk(m.__root);
return m;
};
const orderModules = (modules) => {
// case-insensitive names
const by = Object.fromEntries(modules.map((m) => [(m.__name || "").toLowerCase(), m]));
const names = Object.keys(by);
const adj = Object.fromEntries(names.map((n) => [n, new Set()]));
const indeg = Object.fromEntries(names.map((n) => [n, 0]));
const add = (a, b) => {
if (a === b) return;
if (!adj[a].has(b)) {
adj[a].add(b);
indeg[b]++;
}
};
const norm = (v) => (v ? (Array.isArray(v) ? v : [v]) : []);
const normNames = (v) => norm(v).map((x) => ("" + x).toLowerCase()).filter(Boolean);
// explicit constraints (used to prevent "*" creating cycles)
const expAfter = {}, expBefore = {};
for (const me of names) {
const m = by[me];
expAfter[me] = new Set(normNames(m.after).filter((x) => x !== "*"));
expBefore[me] = new Set(normNames(m.before).filter((x) => x !== "*"));
}
for (const me of names) {
const m = by[me];
for (const x of normNames(m.before)) {
if (x === "*") {
// before everyone except those I'm explicitly after
for (const other of names) if (other !== me && !expAfter[me].has(other)) add(me, other);
} else if (by[x]) add(me, x);
}
for (const x of normNames(m.after)) {
if (x === "*") {
// after everyone except those I'm explicitly before
for (const other of names) if (other !== me && !expBefore[me].has(other)) add(other, me);
} else if (by[x]) add(x, me);
}
}
// stable topo queue: keep discovery order
const original = modules
.map((m) => (m.__name || "").toLowerCase())
.filter((n) => by[n]);
const q = [];
const seen = new Set();
for (const n of original) if (indeg[n] === 0 && !seen.has(n)) q.push(n), seen.add(n);
for (const n of names) if (indeg[n] === 0 && !seen.has(n)) q.push(n), seen.add(n);
const out = [];
for (let i = 0; i < q.length; i++) {
const n = q[i];
out.push(n);
for (const to of adj[n]) if (--indeg[to] === 0) q.push(to);
}
// cycle fallback: old priority
if (out.length !== names.length) {
return modules.slice().sort((a, b) => (b.priority || 0) - (a.priority || 0));
}
const idx = Object.fromEntries(out.map((n, i) => [n, i]));
return modules.slice().sort(
(a, b) => idx[(a.__name || "").toLowerCase()] - idx[(b.__name || "").toLowerCase()]
);
};
// ---- ensure global module exists (installs from github if missing) ----
const ensureGlobalModuleExists = (name, repo, branch = "master") => {
const dir = path.join(wawRoot, "server", name);
if (fs.existsSync(dir) && fs.lstatSync(dir).isDirectory()) return dir;
git.forceSync(dir, { repo, branch, silent: true });
return dir;
};
// ---- read project config ----
const cwd = process.cwd();
const config = Object.assign(j(path.join(cwd, "config.json")), j(path.join(cwd, "server.json")));
if (typeof config.server !== "string" && fs.existsSync(path.join(cwd, "server"))) config.server = "server";
const modules = [];
// local modules
const localRoot = path.join(cwd, config.server || "");
if (fs.existsSync(localRoot)) {
for (const n of fs.readdirSync(localRoot)) {
if (n === "node_modules" || n === ".git") continue;
const dir = path.join(localRoot, n);
if (!fs.existsSync(dir) || !fs.lstatSync(dir).isDirectory()) continue;
const m = load(dir, n, false);
if (m) modules.push(m);
}
}
// required global modules (your config.modules object map)
const orgMocks = {
waw: 'https://github.com/WebArtWork/waw-{NAME}.git',
itkp: 'git@github.com:IT-Kamianets/waw-{NAME}.git'
};
config.modules ||= {};
for (const name in config.modules) {
if (!orgMocks[config.modules[name]]) {
continue;
}
const dir = ensureGlobalModuleExists(name, orgMocks[config.modules[name]].replace('{NAME}', name));
if (fs.existsSync(dir) && fs.lstatSync(dir).isDirectory()) {
const m = load(dir, name, true);
if (m) modules.push(m);
}
}
if (!modules.length) {
const dir = ensureGlobalModuleExists('core', orgMocks['waw'].replace('{NAME}', 'core'));
if (fs.existsSync(dir) && fs.lstatSync(dir).isDirectory()) {
const core = load(dir, "core", true);
if (core) modules.push(core);
}
}
const projectTypes = {
'angular.json': 'angular',
'react.json': 'react',
'vue.json': 'vue',
'wjst.json': 'wjst',
}
for (const jsonName in projectTypes) {
const name = projectTypes[jsonName];
if (fs.existsSync(path.join(cwd, jsonName)) && !modules.find(m => m.name === name)) {
const dir = ensureGlobalModuleExists(name, orgMocks['waw'].replace('{NAME}', name));
if (fs.existsSync(dir) && fs.lstatSync(dir).isDirectory()) {
const core = load(dir, name, true);
if (core) modules.push(core);
}
}
}
module.exports = orderModules(modules);