@timeax/scaffold 0.0.5 → 0.0.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.
- package/.idea/dictionaries/project.xml +7 -0
- package/.idea/modules.xml +8 -0
- package/.idea/php.xml +34 -0
- package/.idea/scaffold.iml +8 -0
- package/.idea/vcs.xml +6 -0
- package/dist/ast.d.cts +4 -2
- package/dist/ast.d.ts +4 -2
- package/dist/cli.cjs +1673 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.mjs +1662 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/config-C0067l3c.d.cts +383 -0
- package/dist/config-C0067l3c.d.ts +383 -0
- package/dist/index.cjs +1311 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +8 -347
- package/dist/index.d.ts +8 -347
- package/dist/index.mjs +1295 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +1 -1
- package/src/cli/main.ts +3 -1
- package/tsup.config.ts +24 -60
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1311 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var path2 = require('path');
|
|
4
|
+
var fs2 = require('fs');
|
|
5
|
+
var os = require('os');
|
|
6
|
+
var crypto = require('crypto');
|
|
7
|
+
var url = require('url');
|
|
8
|
+
var esbuild = require('esbuild');
|
|
9
|
+
var minimatch = require('minimatch');
|
|
10
|
+
|
|
11
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
12
|
+
|
|
13
|
+
var path2__default = /*#__PURE__*/_interopDefault(path2);
|
|
14
|
+
var fs2__default = /*#__PURE__*/_interopDefault(fs2);
|
|
15
|
+
var os__default = /*#__PURE__*/_interopDefault(os);
|
|
16
|
+
var crypto__default = /*#__PURE__*/_interopDefault(crypto);
|
|
17
|
+
|
|
18
|
+
// src/schema/index.ts
|
|
19
|
+
var SCAFFOLD_ROOT_DIR = ".scaffold";
|
|
20
|
+
|
|
21
|
+
// src/util/logger.ts
|
|
22
|
+
var supportsColor = typeof process !== "undefined" && process.stdout && process.stdout.isTTY && process.env.NO_COLOR !== "1";
|
|
23
|
+
function wrap(code) {
|
|
24
|
+
const open = `\x1B[${code}m`;
|
|
25
|
+
const close = `\x1B[0m`;
|
|
26
|
+
return (text) => supportsColor ? `${open}${text}${close}` : text;
|
|
27
|
+
}
|
|
28
|
+
var color = {
|
|
29
|
+
red: wrap(31),
|
|
30
|
+
yellow: wrap(33),
|
|
31
|
+
green: wrap(32),
|
|
32
|
+
cyan: wrap(36),
|
|
33
|
+
magenta: wrap(35),
|
|
34
|
+
dim: wrap(2),
|
|
35
|
+
bold: wrap(1),
|
|
36
|
+
gray: wrap(90)
|
|
37
|
+
};
|
|
38
|
+
function colorForLevel(level) {
|
|
39
|
+
switch (level) {
|
|
40
|
+
case "error":
|
|
41
|
+
return color.red;
|
|
42
|
+
case "warn":
|
|
43
|
+
return color.yellow;
|
|
44
|
+
case "info":
|
|
45
|
+
return color.cyan;
|
|
46
|
+
case "debug":
|
|
47
|
+
return color.gray;
|
|
48
|
+
default:
|
|
49
|
+
return (s) => s;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
var Logger = class _Logger {
|
|
53
|
+
level;
|
|
54
|
+
prefix;
|
|
55
|
+
constructor(options = {}) {
|
|
56
|
+
this.level = options.level ?? "info";
|
|
57
|
+
this.prefix = options.prefix;
|
|
58
|
+
}
|
|
59
|
+
setLevel(level) {
|
|
60
|
+
this.level = level;
|
|
61
|
+
}
|
|
62
|
+
getLevel() {
|
|
63
|
+
return this.level;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Create a child logger with an additional prefix.
|
|
67
|
+
*/
|
|
68
|
+
child(prefix) {
|
|
69
|
+
const combined = this.prefix ? `${this.prefix}${prefix}` : prefix;
|
|
70
|
+
return new _Logger({ level: this.level, prefix: combined });
|
|
71
|
+
}
|
|
72
|
+
formatMessage(msg, lvl) {
|
|
73
|
+
const text = typeof msg === "string" ? msg : msg instanceof Error ? msg.message : String(msg);
|
|
74
|
+
const levelColor = colorForLevel(lvl);
|
|
75
|
+
const prefixColored = this.prefix ? color.magenta(this.prefix) : void 0;
|
|
76
|
+
const textColored = lvl === "debug" ? color.dim(text) : levelColor(text);
|
|
77
|
+
if (prefixColored) {
|
|
78
|
+
return `${prefixColored} ${textColored}`;
|
|
79
|
+
}
|
|
80
|
+
return textColored;
|
|
81
|
+
}
|
|
82
|
+
shouldLog(targetLevel) {
|
|
83
|
+
const order = ["silent", "error", "warn", "info", "debug"];
|
|
84
|
+
const currentIdx = order.indexOf(this.level);
|
|
85
|
+
const targetIdx = order.indexOf(targetLevel);
|
|
86
|
+
if (currentIdx === -1 || targetIdx === -1) return true;
|
|
87
|
+
if (this.level === "silent") return false;
|
|
88
|
+
return targetIdx <= currentIdx || targetLevel === "error";
|
|
89
|
+
}
|
|
90
|
+
error(msg, ...rest) {
|
|
91
|
+
if (!this.shouldLog("error")) return;
|
|
92
|
+
console.error(this.formatMessage(msg, "error"), ...rest);
|
|
93
|
+
}
|
|
94
|
+
warn(msg, ...rest) {
|
|
95
|
+
if (!this.shouldLog("warn")) return;
|
|
96
|
+
console.warn(this.formatMessage(msg, "warn"), ...rest);
|
|
97
|
+
}
|
|
98
|
+
info(msg, ...rest) {
|
|
99
|
+
if (!this.shouldLog("info")) return;
|
|
100
|
+
console.log(this.formatMessage(msg, "info"), ...rest);
|
|
101
|
+
}
|
|
102
|
+
debug(msg, ...rest) {
|
|
103
|
+
if (!this.shouldLog("debug")) return;
|
|
104
|
+
console.debug(this.formatMessage(msg, "debug"), ...rest);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
var defaultLogger = new Logger({
|
|
108
|
+
level: process.env.SCAFFOLD_LOG_LEVEL ?? "info",
|
|
109
|
+
prefix: "[scaffold]"
|
|
110
|
+
});
|
|
111
|
+
function toPosixPath(p) {
|
|
112
|
+
return p.replace(/\\/g, "/");
|
|
113
|
+
}
|
|
114
|
+
function ensureDirSync(dirPath) {
|
|
115
|
+
if (!fs2__default.default.existsSync(dirPath)) {
|
|
116
|
+
fs2__default.default.mkdirSync(dirPath, { recursive: true });
|
|
117
|
+
}
|
|
118
|
+
return dirPath;
|
|
119
|
+
}
|
|
120
|
+
function statSafeSync(targetPath) {
|
|
121
|
+
try {
|
|
122
|
+
return fs2__default.default.statSync(targetPath);
|
|
123
|
+
} catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function toProjectRelativePath(projectRoot, absolutePath) {
|
|
128
|
+
const absRoot = path2__default.default.resolve(projectRoot);
|
|
129
|
+
const absTarget = path2__default.default.resolve(absolutePath);
|
|
130
|
+
const rootWithSep = absRoot.endsWith(path2__default.default.sep) ? absRoot : absRoot + path2__default.default.sep;
|
|
131
|
+
if (!absTarget.startsWith(rootWithSep) && absTarget !== absRoot) {
|
|
132
|
+
throw new Error(
|
|
133
|
+
`Path "${absTarget}" is not inside project root "${absRoot}".`
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
const rel = path2__default.default.relative(absRoot, absTarget);
|
|
137
|
+
return toPosixPath(rel);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// src/core/config-loader.ts
|
|
141
|
+
var logger = defaultLogger.child("[config]");
|
|
142
|
+
async function loadScaffoldConfig(cwd, options = {}) {
|
|
143
|
+
const absCwd = path2__default.default.resolve(cwd);
|
|
144
|
+
const initialScaffoldDir = options.scaffoldDir ? path2__default.default.resolve(absCwd, options.scaffoldDir) : path2__default.default.join(absCwd, SCAFFOLD_ROOT_DIR);
|
|
145
|
+
const configPath = options.configPath ?? resolveConfigPath(initialScaffoldDir);
|
|
146
|
+
const config = await importConfig(configPath);
|
|
147
|
+
let configRoot = absCwd;
|
|
148
|
+
if (config.root) {
|
|
149
|
+
configRoot = path2__default.default.resolve(absCwd, config.root);
|
|
150
|
+
}
|
|
151
|
+
const scaffoldDir = options.scaffoldDir ? path2__default.default.resolve(absCwd, options.scaffoldDir) : path2__default.default.join(configRoot, SCAFFOLD_ROOT_DIR);
|
|
152
|
+
const baseRoot = config.base ? path2__default.default.resolve(configRoot, config.base) : configRoot;
|
|
153
|
+
logger.debug(
|
|
154
|
+
`Loaded config: configRoot=${configRoot}, baseRoot=${baseRoot}, scaffoldDir=${scaffoldDir}`
|
|
155
|
+
);
|
|
156
|
+
return {
|
|
157
|
+
config,
|
|
158
|
+
scaffoldDir,
|
|
159
|
+
projectRoot: baseRoot
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
function resolveConfigPath(scaffoldDir) {
|
|
163
|
+
const candidates = [
|
|
164
|
+
"config.ts",
|
|
165
|
+
"config.mts",
|
|
166
|
+
"config.mjs",
|
|
167
|
+
"config.js",
|
|
168
|
+
"config.cjs"
|
|
169
|
+
];
|
|
170
|
+
for (const file of candidates) {
|
|
171
|
+
const full = path2__default.default.join(scaffoldDir, file);
|
|
172
|
+
if (fs2__default.default.existsSync(full)) {
|
|
173
|
+
return full;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
throw new Error(
|
|
177
|
+
`Could not find scaffold config in ${scaffoldDir}. Looked for: ${candidates.join(
|
|
178
|
+
", "
|
|
179
|
+
)}`
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
async function importConfig(configPath) {
|
|
183
|
+
const ext = path2__default.default.extname(configPath).toLowerCase();
|
|
184
|
+
if (ext === ".ts" || ext === ".tsx") {
|
|
185
|
+
return importTsConfig(configPath);
|
|
186
|
+
}
|
|
187
|
+
const url$1 = url.pathToFileURL(configPath).href;
|
|
188
|
+
const mod = await import(url$1);
|
|
189
|
+
return mod.default ?? mod;
|
|
190
|
+
}
|
|
191
|
+
async function importTsConfig(configPath) {
|
|
192
|
+
const source = fs2__default.default.readFileSync(configPath, "utf8");
|
|
193
|
+
const stat = fs2__default.default.statSync(configPath);
|
|
194
|
+
const hash = crypto__default.default.createHash("sha1").update(configPath).update(String(stat.mtimeMs)).digest("hex");
|
|
195
|
+
const tmpDir = path2__default.default.join(os__default.default.tmpdir(), "timeax-scaffold-config");
|
|
196
|
+
ensureDirSync(tmpDir);
|
|
197
|
+
const tmpFile = path2__default.default.join(tmpDir, `${hash}.mjs`);
|
|
198
|
+
if (!fs2__default.default.existsSync(tmpFile)) {
|
|
199
|
+
const result = await esbuild.transform(source, {
|
|
200
|
+
loader: "ts",
|
|
201
|
+
format: "esm",
|
|
202
|
+
sourcemap: "inline",
|
|
203
|
+
target: "ESNext",
|
|
204
|
+
tsconfigRaw: {
|
|
205
|
+
compilerOptions: {}
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
fs2__default.default.writeFileSync(tmpFile, result.code, "utf8");
|
|
209
|
+
}
|
|
210
|
+
const url$1 = url.pathToFileURL(tmpFile).href;
|
|
211
|
+
const mod = await import(url$1);
|
|
212
|
+
return mod.default ?? mod;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/ast/parser.ts
|
|
216
|
+
function parseStructureAst(text, opts = {}) {
|
|
217
|
+
const indentStep = opts.indentStep ?? 2;
|
|
218
|
+
const mode = opts.mode ?? "loose";
|
|
219
|
+
const diagnostics = [];
|
|
220
|
+
const lines = [];
|
|
221
|
+
const rawLines = text.split(/\r?\n/);
|
|
222
|
+
for (let i = 0; i < rawLines.length; i++) {
|
|
223
|
+
const raw = rawLines[i];
|
|
224
|
+
const lineNo = i + 1;
|
|
225
|
+
const m = raw.match(/^(\s*)(.*)$/);
|
|
226
|
+
const indentRaw = m ? m[1] : "";
|
|
227
|
+
const content = m ? m[2] : "";
|
|
228
|
+
const { indentSpaces, hasTabs } = measureIndent(indentRaw, indentStep);
|
|
229
|
+
if (hasTabs) {
|
|
230
|
+
diagnostics.push({
|
|
231
|
+
line: lineNo,
|
|
232
|
+
message: "Tabs detected in indentation. Consider using spaces only for consistent levels.",
|
|
233
|
+
severity: mode === "strict" ? "warning" : "info",
|
|
234
|
+
code: "indent-tabs"
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
const trimmed = content.trim();
|
|
238
|
+
let kind;
|
|
239
|
+
if (!trimmed) {
|
|
240
|
+
kind = "blank";
|
|
241
|
+
} else if (trimmed.startsWith("#") || trimmed.startsWith("//")) {
|
|
242
|
+
kind = "comment";
|
|
243
|
+
} else {
|
|
244
|
+
kind = "entry";
|
|
245
|
+
}
|
|
246
|
+
lines.push({
|
|
247
|
+
index: i,
|
|
248
|
+
lineNo,
|
|
249
|
+
raw,
|
|
250
|
+
kind,
|
|
251
|
+
indentSpaces,
|
|
252
|
+
content
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
const rootNodes = [];
|
|
256
|
+
const stack = [];
|
|
257
|
+
const depthCtx = {
|
|
258
|
+
lastIndentSpaces: null,
|
|
259
|
+
lastDepth: null,
|
|
260
|
+
lastWasFile: false
|
|
261
|
+
};
|
|
262
|
+
for (const line of lines) {
|
|
263
|
+
if (line.kind !== "entry") continue;
|
|
264
|
+
const { entry, depth, diags } = parseEntryLine(
|
|
265
|
+
line,
|
|
266
|
+
indentStep,
|
|
267
|
+
mode,
|
|
268
|
+
depthCtx
|
|
269
|
+
);
|
|
270
|
+
diagnostics.push(...diags);
|
|
271
|
+
if (!entry) {
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
attachNode(entry, depth, line, rootNodes, stack, diagnostics, mode);
|
|
275
|
+
depthCtx.lastWasFile = !entry.isDir;
|
|
276
|
+
}
|
|
277
|
+
return {
|
|
278
|
+
rootNodes,
|
|
279
|
+
lines,
|
|
280
|
+
diagnostics,
|
|
281
|
+
options: {
|
|
282
|
+
indentStep,
|
|
283
|
+
mode
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
function measureIndent(rawIndent, indentStep) {
|
|
288
|
+
let spaces = 0;
|
|
289
|
+
let hasTabs = false;
|
|
290
|
+
for (const ch of rawIndent) {
|
|
291
|
+
if (ch === " ") {
|
|
292
|
+
spaces += 1;
|
|
293
|
+
} else if (ch === " ") {
|
|
294
|
+
hasTabs = true;
|
|
295
|
+
spaces += indentStep;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return { indentSpaces: spaces, hasTabs };
|
|
299
|
+
}
|
|
300
|
+
function computeDepth(line, indentStep, mode, ctx, diagnostics) {
|
|
301
|
+
let spaces = line.indentSpaces;
|
|
302
|
+
if (spaces < 0) spaces = 0;
|
|
303
|
+
let depth;
|
|
304
|
+
if (ctx.lastIndentSpaces == null || ctx.lastDepth == null) {
|
|
305
|
+
depth = 0;
|
|
306
|
+
} else {
|
|
307
|
+
const prevSpaces = ctx.lastIndentSpaces;
|
|
308
|
+
const prevDepth = ctx.lastDepth;
|
|
309
|
+
if (spaces > prevSpaces) {
|
|
310
|
+
const diff = spaces - prevSpaces;
|
|
311
|
+
if (ctx.lastWasFile) {
|
|
312
|
+
diagnostics.push({
|
|
313
|
+
line: line.lineNo,
|
|
314
|
+
message: "Entry appears indented under a file; treating it as a sibling of the file instead of a child.",
|
|
315
|
+
severity: mode === "strict" ? "error" : "warning",
|
|
316
|
+
code: "child-of-file-loose"
|
|
317
|
+
});
|
|
318
|
+
depth = prevDepth;
|
|
319
|
+
} else {
|
|
320
|
+
if (diff > indentStep) {
|
|
321
|
+
diagnostics.push({
|
|
322
|
+
line: line.lineNo,
|
|
323
|
+
message: `Indentation jumps from ${prevSpaces} to ${spaces} spaces; treating as one level deeper.`,
|
|
324
|
+
severity: mode === "strict" ? "error" : "warning",
|
|
325
|
+
code: "indent-skip-level"
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
depth = prevDepth + 1;
|
|
329
|
+
}
|
|
330
|
+
} else if (spaces === prevSpaces) {
|
|
331
|
+
depth = prevDepth;
|
|
332
|
+
} else {
|
|
333
|
+
const diff = prevSpaces - spaces;
|
|
334
|
+
const steps = Math.round(diff / indentStep);
|
|
335
|
+
if (diff % indentStep !== 0) {
|
|
336
|
+
diagnostics.push({
|
|
337
|
+
line: line.lineNo,
|
|
338
|
+
message: `Indentation decreases from ${prevSpaces} to ${spaces} spaces, which is not a multiple of indent step (${indentStep}).`,
|
|
339
|
+
severity: mode === "strict" ? "error" : "warning",
|
|
340
|
+
code: "indent-misaligned"
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
depth = Math.max(prevDepth - steps, 0);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
ctx.lastIndentSpaces = spaces;
|
|
347
|
+
ctx.lastDepth = depth;
|
|
348
|
+
return depth;
|
|
349
|
+
}
|
|
350
|
+
function parseEntryLine(line, indentStep, mode, ctx) {
|
|
351
|
+
const diags = [];
|
|
352
|
+
const depth = computeDepth(line, indentStep, mode, ctx, diags);
|
|
353
|
+
const { contentWithoutComment } = extractInlineCommentParts(line.content);
|
|
354
|
+
const trimmed = contentWithoutComment.trim();
|
|
355
|
+
if (!trimmed) {
|
|
356
|
+
return { entry: null, depth, diags };
|
|
357
|
+
}
|
|
358
|
+
const parts = trimmed.split(/\s+/);
|
|
359
|
+
const pathToken = parts[0];
|
|
360
|
+
const annotationTokens = parts.slice(1);
|
|
361
|
+
if (pathToken.includes(":")) {
|
|
362
|
+
diags.push({
|
|
363
|
+
line: line.lineNo,
|
|
364
|
+
message: 'Path token contains ":" which is reserved for annotations. This is likely a mistake.',
|
|
365
|
+
severity: mode === "strict" ? "error" : "warning",
|
|
366
|
+
code: "path-colon"
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
const isDir = pathToken.endsWith("/");
|
|
370
|
+
const segmentName = pathToken;
|
|
371
|
+
let stub;
|
|
372
|
+
const include = [];
|
|
373
|
+
const exclude = [];
|
|
374
|
+
for (const token of annotationTokens) {
|
|
375
|
+
if (token.startsWith("@stub:")) {
|
|
376
|
+
stub = token.slice("@stub:".length);
|
|
377
|
+
} else if (token.startsWith("@include:")) {
|
|
378
|
+
const val = token.slice("@include:".length);
|
|
379
|
+
if (val) {
|
|
380
|
+
include.push(
|
|
381
|
+
...val.split(",").map((s) => s.trim()).filter(Boolean)
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
} else if (token.startsWith("@exclude:")) {
|
|
385
|
+
const val = token.slice("@exclude:".length);
|
|
386
|
+
if (val) {
|
|
387
|
+
exclude.push(
|
|
388
|
+
...val.split(",").map((s) => s.trim()).filter(Boolean)
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
} else if (token.startsWith("@")) {
|
|
392
|
+
diags.push({
|
|
393
|
+
line: line.lineNo,
|
|
394
|
+
message: `Unknown annotation token "${token}".`,
|
|
395
|
+
severity: "info",
|
|
396
|
+
code: "unknown-annotation"
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
const entry = {
|
|
401
|
+
segmentName,
|
|
402
|
+
isDir,
|
|
403
|
+
stub,
|
|
404
|
+
include: include.length ? include : void 0,
|
|
405
|
+
exclude: exclude.length ? exclude : void 0
|
|
406
|
+
};
|
|
407
|
+
return { entry, depth, diags };
|
|
408
|
+
}
|
|
409
|
+
function mapThrough(content) {
|
|
410
|
+
let cutIndex = -1;
|
|
411
|
+
const len = content.length;
|
|
412
|
+
for (let i = 0; i < len; i++) {
|
|
413
|
+
const ch = content[i];
|
|
414
|
+
const prev = i > 0 ? content[i - 1] : "";
|
|
415
|
+
if (ch === "#") {
|
|
416
|
+
if (i === 0) {
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
if (prev === " " || prev === " ") {
|
|
420
|
+
cutIndex = i;
|
|
421
|
+
break;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
if (ch === "/" && i + 1 < len && content[i + 1] === "/" && (prev === " " || prev === " ")) {
|
|
425
|
+
cutIndex = i;
|
|
426
|
+
break;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
return cutIndex;
|
|
430
|
+
}
|
|
431
|
+
function extractInlineCommentParts(content) {
|
|
432
|
+
const cutIndex = mapThrough(content);
|
|
433
|
+
if (cutIndex === -1) {
|
|
434
|
+
return {
|
|
435
|
+
contentWithoutComment: content,
|
|
436
|
+
inlineComment: null
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
return {
|
|
440
|
+
contentWithoutComment: content.slice(0, cutIndex),
|
|
441
|
+
inlineComment: content.slice(cutIndex)
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
function attachNode(entry, depth, line, rootNodes, stack, diagnostics, mode) {
|
|
445
|
+
const lineNo = line.lineNo;
|
|
446
|
+
while (stack.length > depth) {
|
|
447
|
+
stack.pop();
|
|
448
|
+
}
|
|
449
|
+
let parent = null;
|
|
450
|
+
if (depth > 0) {
|
|
451
|
+
const candidate = stack[depth - 1];
|
|
452
|
+
if (!candidate) {
|
|
453
|
+
diagnostics.push({
|
|
454
|
+
line: lineNo,
|
|
455
|
+
message: `Entry has indent depth ${depth} but no parent at depth ${depth - 1}. Treating as root.`,
|
|
456
|
+
severity: mode === "strict" ? "error" : "warning",
|
|
457
|
+
code: "missing-parent"
|
|
458
|
+
});
|
|
459
|
+
} else if (candidate.type === "file") {
|
|
460
|
+
if (mode === "strict") {
|
|
461
|
+
diagnostics.push({
|
|
462
|
+
line: lineNo,
|
|
463
|
+
message: `Cannot attach child under file "${candidate.path}".`,
|
|
464
|
+
severity: "error",
|
|
465
|
+
code: "child-of-file"
|
|
466
|
+
});
|
|
467
|
+
} else {
|
|
468
|
+
diagnostics.push({
|
|
469
|
+
line: lineNo,
|
|
470
|
+
message: `Entry appears under file "${candidate.path}". Attaching as sibling at depth ${candidate.depth}.`,
|
|
471
|
+
severity: "warning",
|
|
472
|
+
code: "child-of-file-loose"
|
|
473
|
+
});
|
|
474
|
+
while (stack.length > candidate.depth) {
|
|
475
|
+
stack.pop();
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
} else {
|
|
479
|
+
parent = candidate;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
const parentPath = parent ? parent.path.replace(/\/$/, "") : "";
|
|
483
|
+
const normalizedSegment = toPosixPath(entry.segmentName.replace(/\/+$/, ""));
|
|
484
|
+
const fullPath = parentPath ? `${parentPath}/${normalizedSegment}${entry.isDir ? "/" : ""}` : `${normalizedSegment}${entry.isDir ? "/" : ""}`;
|
|
485
|
+
const baseNode = {
|
|
486
|
+
type: entry.isDir ? "dir" : "file",
|
|
487
|
+
name: entry.segmentName,
|
|
488
|
+
depth,
|
|
489
|
+
line: lineNo,
|
|
490
|
+
path: fullPath,
|
|
491
|
+
parent,
|
|
492
|
+
...entry.stub ? { stub: entry.stub } : {},
|
|
493
|
+
...entry.include ? { include: entry.include } : {},
|
|
494
|
+
...entry.exclude ? { exclude: entry.exclude } : {}
|
|
495
|
+
};
|
|
496
|
+
if (entry.isDir) {
|
|
497
|
+
const dirNode = {
|
|
498
|
+
...baseNode,
|
|
499
|
+
type: "dir",
|
|
500
|
+
children: []
|
|
501
|
+
};
|
|
502
|
+
if (parent) {
|
|
503
|
+
parent.children.push(dirNode);
|
|
504
|
+
} else {
|
|
505
|
+
rootNodes.push(dirNode);
|
|
506
|
+
}
|
|
507
|
+
while (stack.length > depth) {
|
|
508
|
+
stack.pop();
|
|
509
|
+
}
|
|
510
|
+
stack[depth] = dirNode;
|
|
511
|
+
} else {
|
|
512
|
+
const fileNode = {
|
|
513
|
+
...baseNode,
|
|
514
|
+
type: "file"
|
|
515
|
+
};
|
|
516
|
+
if (parent) {
|
|
517
|
+
parent.children.push(fileNode);
|
|
518
|
+
} else {
|
|
519
|
+
rootNodes.push(fileNode);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// src/ast/format.ts
|
|
525
|
+
function formatStructureText(text, options = {}) {
|
|
526
|
+
const indentStep = options.indentStep ?? 2;
|
|
527
|
+
const mode = options.mode ?? "loose";
|
|
528
|
+
const normalizeNewlines = options.normalizeNewlines === void 0 ? true : options.normalizeNewlines;
|
|
529
|
+
const trimTrailingWhitespace = options.trimTrailingWhitespace === void 0 ? true : options.trimTrailingWhitespace;
|
|
530
|
+
const normalizeAnnotations = options.normalizeAnnotations === void 0 ? true : options.normalizeAnnotations;
|
|
531
|
+
const ast = parseStructureAst(text, {
|
|
532
|
+
indentStep,
|
|
533
|
+
mode
|
|
534
|
+
});
|
|
535
|
+
const rawLines = text.split(/\r?\n/);
|
|
536
|
+
const lineCount = rawLines.length;
|
|
537
|
+
if (ast.lines.length !== lineCount) {
|
|
538
|
+
return {
|
|
539
|
+
text: basicNormalize(text, { normalizeNewlines, trimTrailingWhitespace }),
|
|
540
|
+
ast
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
const entryLineIndexes = [];
|
|
544
|
+
const inlineComments = [];
|
|
545
|
+
for (let i = 0; i < lineCount; i++) {
|
|
546
|
+
const lineMeta = ast.lines[i];
|
|
547
|
+
if (lineMeta.kind === "entry") {
|
|
548
|
+
entryLineIndexes.push(i);
|
|
549
|
+
const { inlineComment } = extractInlineCommentParts(lineMeta.content);
|
|
550
|
+
inlineComments.push(inlineComment);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
const flattened = [];
|
|
554
|
+
flattenAstNodes(ast.rootNodes, 0, flattened);
|
|
555
|
+
if (flattened.length !== entryLineIndexes.length) {
|
|
556
|
+
return {
|
|
557
|
+
text: basicNormalize(text, { normalizeNewlines, trimTrailingWhitespace }),
|
|
558
|
+
ast
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
const canonicalEntryLines = flattened.map(
|
|
562
|
+
({ node, level }) => formatAstNodeLine(node, level, indentStep, normalizeAnnotations)
|
|
563
|
+
);
|
|
564
|
+
const resultLines = [];
|
|
565
|
+
let entryIdx = 0;
|
|
566
|
+
for (let i = 0; i < lineCount; i++) {
|
|
567
|
+
const lineMeta = ast.lines[i];
|
|
568
|
+
const originalLine = rawLines[i];
|
|
569
|
+
if (lineMeta.kind === "entry") {
|
|
570
|
+
const base = canonicalEntryLines[entryIdx].replace(/[ \t]+$/g, "");
|
|
571
|
+
const inline = inlineComments[entryIdx];
|
|
572
|
+
entryIdx++;
|
|
573
|
+
if (inline) {
|
|
574
|
+
resultLines.push(base + " " + inline);
|
|
575
|
+
} else {
|
|
576
|
+
resultLines.push(base);
|
|
577
|
+
}
|
|
578
|
+
} else {
|
|
579
|
+
let out = originalLine;
|
|
580
|
+
if (trimTrailingWhitespace) {
|
|
581
|
+
out = out.replace(/[ \t]+$/g, "");
|
|
582
|
+
}
|
|
583
|
+
resultLines.push(out);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
const eol = normalizeNewlines ? detectPreferredEol(text) : getRawEol(text);
|
|
587
|
+
return {
|
|
588
|
+
text: resultLines.join(eol),
|
|
589
|
+
ast
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
function basicNormalize(text, opts) {
|
|
593
|
+
const lines = text.split(/\r?\n/);
|
|
594
|
+
const normalizedLines = opts.trimTrailingWhitespace ? lines.map((line) => line.replace(/[ \t]+$/g, "")) : lines;
|
|
595
|
+
const eol = opts.normalizeNewlines ? detectPreferredEol(text) : getRawEol(text);
|
|
596
|
+
return normalizedLines.join(eol);
|
|
597
|
+
}
|
|
598
|
+
function detectPreferredEol(text) {
|
|
599
|
+
const crlfCount = (text.match(/\r\n/g) || []).length;
|
|
600
|
+
const lfCount = (text.match(/(?<!\r)\n/g) || []).length;
|
|
601
|
+
if (crlfCount === 0 && lfCount === 0) {
|
|
602
|
+
return "\n";
|
|
603
|
+
}
|
|
604
|
+
if (crlfCount > lfCount) {
|
|
605
|
+
return "\r\n";
|
|
606
|
+
}
|
|
607
|
+
return "\n";
|
|
608
|
+
}
|
|
609
|
+
function getRawEol(text) {
|
|
610
|
+
return text.includes("\r\n") ? "\r\n" : "\n";
|
|
611
|
+
}
|
|
612
|
+
function flattenAstNodes(nodes, level, out) {
|
|
613
|
+
for (const node of nodes) {
|
|
614
|
+
out.push({ node, level });
|
|
615
|
+
if (node.type === "dir" && node.children && node.children.length) {
|
|
616
|
+
flattenAstNodes(node.children, level + 1, out);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
function formatAstNodeLine(node, level, indentStep, normalizeAnnotations) {
|
|
621
|
+
const indent = " ".repeat(indentStep * level);
|
|
622
|
+
const baseName = node.name;
|
|
623
|
+
if (!normalizeAnnotations) {
|
|
624
|
+
return indent + baseName;
|
|
625
|
+
}
|
|
626
|
+
const tokens = [];
|
|
627
|
+
if (node.stub) {
|
|
628
|
+
tokens.push(`@stub:${node.stub}`);
|
|
629
|
+
}
|
|
630
|
+
if (node.include && node.include.length > 0) {
|
|
631
|
+
tokens.push(`@include:${node.include.join(",")}`);
|
|
632
|
+
}
|
|
633
|
+
if (node.exclude && node.exclude.length > 0) {
|
|
634
|
+
tokens.push(`@exclude:${node.exclude.join(",")}`);
|
|
635
|
+
}
|
|
636
|
+
const annotations = tokens.length ? " " + tokens.join(" ") : "";
|
|
637
|
+
return indent + baseName + annotations;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
// src/core/structure-txt.ts
|
|
641
|
+
function stripInlineComment(content) {
|
|
642
|
+
const cutIndex = mapThrough(content);
|
|
643
|
+
if (cutIndex === -1) {
|
|
644
|
+
return content.trimEnd();
|
|
645
|
+
}
|
|
646
|
+
return content.slice(0, cutIndex).trimEnd();
|
|
647
|
+
}
|
|
648
|
+
function parseLine(line, lineNo) {
|
|
649
|
+
const match = line.match(/^(\s*)(.*)$/);
|
|
650
|
+
if (!match) return null;
|
|
651
|
+
const indentSpaces = match[1].length;
|
|
652
|
+
let rest = match[2];
|
|
653
|
+
if (!rest.trim()) return null;
|
|
654
|
+
const trimmedRest = rest.trimStart();
|
|
655
|
+
if (trimmedRest.startsWith("#") || trimmedRest.startsWith("//")) {
|
|
656
|
+
return null;
|
|
657
|
+
}
|
|
658
|
+
const stripped = stripInlineComment(rest);
|
|
659
|
+
const trimmed = stripped.trim();
|
|
660
|
+
if (!trimmed) return null;
|
|
661
|
+
const parts = trimmed.split(/\s+/);
|
|
662
|
+
if (!parts.length) return null;
|
|
663
|
+
const pathToken = parts[0];
|
|
664
|
+
if (pathToken.includes(":")) {
|
|
665
|
+
throw new Error(
|
|
666
|
+
`structure.txt: ":" is reserved for annotations (@stub:, @include:, etc). Invalid path "${pathToken}" on line ${lineNo}.`
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
let stub;
|
|
670
|
+
const include = [];
|
|
671
|
+
const exclude = [];
|
|
672
|
+
for (const token of parts.slice(1)) {
|
|
673
|
+
if (token.startsWith("@stub:")) {
|
|
674
|
+
stub = token.slice("@stub:".length);
|
|
675
|
+
} else if (token.startsWith("@include:")) {
|
|
676
|
+
const val = token.slice("@include:".length);
|
|
677
|
+
if (val) {
|
|
678
|
+
include.push(
|
|
679
|
+
...val.split(",").map((s) => s.trim()).filter(Boolean)
|
|
680
|
+
);
|
|
681
|
+
}
|
|
682
|
+
} else if (token.startsWith("@exclude:")) {
|
|
683
|
+
const val = token.slice("@exclude:".length);
|
|
684
|
+
if (val) {
|
|
685
|
+
exclude.push(
|
|
686
|
+
...val.split(",").map((s) => s.trim()).filter(Boolean)
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
return {
|
|
692
|
+
lineNo,
|
|
693
|
+
indentSpaces,
|
|
694
|
+
rawPath: pathToken,
|
|
695
|
+
stub,
|
|
696
|
+
include: include.length ? include : void 0,
|
|
697
|
+
exclude: exclude.length ? exclude : void 0
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
function parseStructureText(text, indentStep = 2) {
|
|
701
|
+
const lines = text.split(/\r?\n/);
|
|
702
|
+
const parsed = [];
|
|
703
|
+
for (let i = 0; i < lines.length; i++) {
|
|
704
|
+
const lineNo = i + 1;
|
|
705
|
+
const p = parseLine(lines[i], lineNo);
|
|
706
|
+
if (p) parsed.push(p);
|
|
707
|
+
}
|
|
708
|
+
const rootEntries = [];
|
|
709
|
+
const stack = [];
|
|
710
|
+
for (const p of parsed) {
|
|
711
|
+
const { indentSpaces, lineNo } = p;
|
|
712
|
+
if (indentSpaces % indentStep !== 0) {
|
|
713
|
+
throw new Error(
|
|
714
|
+
`structure.txt: Invalid indent on line ${lineNo}. Indent must be multiples of ${indentStep} spaces.`
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
const level = indentSpaces / indentStep;
|
|
718
|
+
if (level > stack.length) {
|
|
719
|
+
if (level !== stack.length + 1) {
|
|
720
|
+
throw new Error(
|
|
721
|
+
`structure.txt: Invalid indentation on line ${lineNo}. You cannot jump more than one level at a time. Previous depth: ${stack.length}, this line depth: ${level}.`
|
|
722
|
+
);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
if (level > 0) {
|
|
726
|
+
const parent2 = stack[level - 1];
|
|
727
|
+
if (!parent2) {
|
|
728
|
+
throw new Error(
|
|
729
|
+
`structure.txt: Indented entry without a parent on line ${lineNo}.`
|
|
730
|
+
);
|
|
731
|
+
}
|
|
732
|
+
if (!parent2.isDir) {
|
|
733
|
+
throw new Error(
|
|
734
|
+
`structure.txt: Cannot indent under a file on line ${lineNo}. Files cannot have children. Parent: "${parent2.entry.path}".`
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
const isDir = p.rawPath.endsWith("/");
|
|
739
|
+
const clean = p.rawPath.replace(/\/$/, "");
|
|
740
|
+
const basePath = toPosixPath(clean);
|
|
741
|
+
while (stack.length > level) {
|
|
742
|
+
stack.pop();
|
|
743
|
+
}
|
|
744
|
+
const parent = stack[stack.length - 1]?.entry;
|
|
745
|
+
const parentPath = parent ? parent.path.replace(/\/$/, "") : "";
|
|
746
|
+
const fullPath = parentPath ? `${parentPath}/${basePath}${isDir ? "/" : ""}` : `${basePath}${isDir ? "/" : ""}`;
|
|
747
|
+
if (isDir) {
|
|
748
|
+
const dirEntry = {
|
|
749
|
+
type: "dir",
|
|
750
|
+
path: fullPath,
|
|
751
|
+
children: [],
|
|
752
|
+
...p.stub ? { stub: p.stub } : {},
|
|
753
|
+
...p.include ? { include: p.include } : {},
|
|
754
|
+
...p.exclude ? { exclude: p.exclude } : {}
|
|
755
|
+
};
|
|
756
|
+
if (parent && parent.type === "dir") {
|
|
757
|
+
parent.children = parent.children ?? [];
|
|
758
|
+
parent.children.push(dirEntry);
|
|
759
|
+
} else if (!parent) {
|
|
760
|
+
rootEntries.push(dirEntry);
|
|
761
|
+
}
|
|
762
|
+
stack.push({ level, entry: dirEntry, isDir: true });
|
|
763
|
+
} else {
|
|
764
|
+
const fileEntry = {
|
|
765
|
+
type: "file",
|
|
766
|
+
path: fullPath,
|
|
767
|
+
...p.stub ? { stub: p.stub } : {},
|
|
768
|
+
...p.include ? { include: p.include } : {},
|
|
769
|
+
...p.exclude ? { exclude: p.exclude } : {}
|
|
770
|
+
};
|
|
771
|
+
if (parent && parent.type === "dir") {
|
|
772
|
+
parent.children = parent.children ?? [];
|
|
773
|
+
parent.children.push(fileEntry);
|
|
774
|
+
} else if (!parent) {
|
|
775
|
+
rootEntries.push(fileEntry);
|
|
776
|
+
}
|
|
777
|
+
stack.push({ level, entry: fileEntry, isDir: false });
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
return rootEntries;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// src/core/resolve-structure.ts
|
|
784
|
+
var logger2 = defaultLogger.child("[structure]");
|
|
785
|
+
function resolveGroupStructure(scaffoldDir, group) {
|
|
786
|
+
if (group.structure && group.structure.length) {
|
|
787
|
+
logger2.debug(`Using inline structure for group "${group.name}"`);
|
|
788
|
+
return group.structure;
|
|
789
|
+
}
|
|
790
|
+
const fileName = group.structureFile ?? `${group.name}.txt`;
|
|
791
|
+
const filePath = path2__default.default.join(scaffoldDir, fileName);
|
|
792
|
+
if (!fs2__default.default.existsSync(filePath)) {
|
|
793
|
+
throw new Error(
|
|
794
|
+
`@timeax/scaffold: Group "${group.name}" has no structure. Expected file "${fileName}" in "${scaffoldDir}".`
|
|
795
|
+
);
|
|
796
|
+
}
|
|
797
|
+
logger2.debug(`Reading structure for group "${group.name}" from ${filePath}`);
|
|
798
|
+
const raw = fs2__default.default.readFileSync(filePath, "utf8");
|
|
799
|
+
return parseStructureText(raw);
|
|
800
|
+
}
|
|
801
|
+
function resolveSingleStructure(scaffoldDir, config) {
|
|
802
|
+
if (config.structure && config.structure.length) {
|
|
803
|
+
logger2.debug("Using inline single structure (no groups)");
|
|
804
|
+
return config.structure;
|
|
805
|
+
}
|
|
806
|
+
const fileName = config.structureFile ?? "structure.txt";
|
|
807
|
+
const filePath = path2__default.default.join(scaffoldDir, fileName);
|
|
808
|
+
if (!fs2__default.default.existsSync(filePath)) {
|
|
809
|
+
throw new Error(
|
|
810
|
+
`@timeax/scaffold: No structure defined. Expected "${fileName}" in "${scaffoldDir}".`
|
|
811
|
+
);
|
|
812
|
+
}
|
|
813
|
+
logger2.debug(`Reading single structure from ${filePath}`);
|
|
814
|
+
const raw = fs2__default.default.readFileSync(filePath, "utf8");
|
|
815
|
+
return parseStructureText(raw);
|
|
816
|
+
}
|
|
817
|
+
var logger3 = defaultLogger.child("[cache]");
|
|
818
|
+
var DEFAULT_CACHE = {
|
|
819
|
+
version: 1,
|
|
820
|
+
entries: {}
|
|
821
|
+
};
|
|
822
|
+
var CacheManager = class {
|
|
823
|
+
constructor(projectRoot, cacheFileRelPath) {
|
|
824
|
+
this.projectRoot = projectRoot;
|
|
825
|
+
this.cacheFileRelPath = cacheFileRelPath;
|
|
826
|
+
}
|
|
827
|
+
cache = DEFAULT_CACHE;
|
|
828
|
+
get cachePathAbs() {
|
|
829
|
+
return path2__default.default.resolve(this.projectRoot, this.cacheFileRelPath);
|
|
830
|
+
}
|
|
831
|
+
load() {
|
|
832
|
+
const cachePath = this.cachePathAbs;
|
|
833
|
+
if (!fs2__default.default.existsSync(cachePath)) {
|
|
834
|
+
this.cache = { ...DEFAULT_CACHE, entries: {} };
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
try {
|
|
838
|
+
const raw = fs2__default.default.readFileSync(cachePath, "utf8");
|
|
839
|
+
const parsed = JSON.parse(raw);
|
|
840
|
+
if (parsed.version === 1 && parsed.entries) {
|
|
841
|
+
this.cache = parsed;
|
|
842
|
+
} else {
|
|
843
|
+
logger3.warn("Cache file version mismatch or invalid, resetting cache.");
|
|
844
|
+
this.cache = { ...DEFAULT_CACHE, entries: {} };
|
|
845
|
+
}
|
|
846
|
+
} catch (err) {
|
|
847
|
+
logger3.warn("Failed to read cache file, resetting cache.", err);
|
|
848
|
+
this.cache = { ...DEFAULT_CACHE, entries: {} };
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
save() {
|
|
852
|
+
const cachePath = this.cachePathAbs;
|
|
853
|
+
const dir = path2__default.default.dirname(cachePath);
|
|
854
|
+
ensureDirSync(dir);
|
|
855
|
+
fs2__default.default.writeFileSync(cachePath, JSON.stringify(this.cache, null, 2), "utf8");
|
|
856
|
+
}
|
|
857
|
+
get(relPath) {
|
|
858
|
+
const key = toPosixPath(relPath);
|
|
859
|
+
return this.cache.entries[key];
|
|
860
|
+
}
|
|
861
|
+
set(entry) {
|
|
862
|
+
const key = toPosixPath(entry.path);
|
|
863
|
+
this.cache.entries[key] = {
|
|
864
|
+
...entry,
|
|
865
|
+
path: key
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
delete(relPath) {
|
|
869
|
+
const key = toPosixPath(relPath);
|
|
870
|
+
delete this.cache.entries[key];
|
|
871
|
+
}
|
|
872
|
+
allPaths() {
|
|
873
|
+
return Object.keys(this.cache.entries);
|
|
874
|
+
}
|
|
875
|
+
allEntries() {
|
|
876
|
+
return Object.values(this.cache.entries);
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
function matchesFilter(pathRel, cfg) {
|
|
880
|
+
const { include, exclude, files } = cfg;
|
|
881
|
+
const patterns = [];
|
|
882
|
+
if (include?.length) patterns.push(...include);
|
|
883
|
+
if (files?.length) patterns.push(...files);
|
|
884
|
+
if (patterns.length) {
|
|
885
|
+
const ok = patterns.some((p) => minimatch.minimatch(pathRel, p));
|
|
886
|
+
if (!ok) return false;
|
|
887
|
+
}
|
|
888
|
+
if (exclude?.length) {
|
|
889
|
+
const blocked = exclude.some((p) => minimatch.minimatch(pathRel, p));
|
|
890
|
+
if (blocked) return false;
|
|
891
|
+
}
|
|
892
|
+
return true;
|
|
893
|
+
}
|
|
894
|
+
var HookRunner = class {
|
|
895
|
+
constructor(config) {
|
|
896
|
+
this.config = config;
|
|
897
|
+
}
|
|
898
|
+
async runRegular(kind, ctx) {
|
|
899
|
+
const configs = this.config.hooks?.[kind] ?? [];
|
|
900
|
+
for (const cfg of configs) {
|
|
901
|
+
if (!matchesFilter(ctx.targetPath, cfg)) continue;
|
|
902
|
+
await cfg.fn(ctx);
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
getStubConfig(stubName) {
|
|
906
|
+
if (!stubName) return void 0;
|
|
907
|
+
return this.config.stubs?.[stubName];
|
|
908
|
+
}
|
|
909
|
+
async runStub(kind, ctx) {
|
|
910
|
+
const stub = this.getStubConfig(ctx.stubName);
|
|
911
|
+
if (!stub?.hooks) return;
|
|
912
|
+
const configs = kind === "preStub" ? stub.hooks.preStub ?? [] : stub.hooks.postStub ?? [];
|
|
913
|
+
for (const cfg of configs) {
|
|
914
|
+
if (!matchesFilter(ctx.targetPath, cfg)) continue;
|
|
915
|
+
await cfg.fn(ctx);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
async renderStubContent(ctx) {
|
|
919
|
+
const stub = this.getStubConfig(ctx.stubName);
|
|
920
|
+
if (!stub?.getContent) return void 0;
|
|
921
|
+
return stub.getContent(ctx);
|
|
922
|
+
}
|
|
923
|
+
};
|
|
924
|
+
async function applyStructure(opts) {
|
|
925
|
+
const {
|
|
926
|
+
config,
|
|
927
|
+
projectRoot,
|
|
928
|
+
baseDir,
|
|
929
|
+
structure,
|
|
930
|
+
cache,
|
|
931
|
+
hooks,
|
|
932
|
+
groupName,
|
|
933
|
+
groupRoot,
|
|
934
|
+
sizePromptThreshold,
|
|
935
|
+
interactiveDelete
|
|
936
|
+
} = opts;
|
|
937
|
+
const logger5 = opts.logger ?? defaultLogger.child(groupName ? `[apply:${groupName}]` : "[apply]");
|
|
938
|
+
const desiredPaths = /* @__PURE__ */ new Set();
|
|
939
|
+
const threshold = sizePromptThreshold ?? config.sizePromptThreshold ?? 128 * 1024;
|
|
940
|
+
async function walk(entry, inheritedStub) {
|
|
941
|
+
const effectiveStub = entry.stub ?? inheritedStub;
|
|
942
|
+
if (entry.type === "dir") {
|
|
943
|
+
await handleDir(entry, effectiveStub);
|
|
944
|
+
} else {
|
|
945
|
+
await handleFile(entry, effectiveStub);
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
async function handleDir(entry, inheritedStub) {
|
|
949
|
+
const relFromBase = entry.path.replace(/^[./]+/, "");
|
|
950
|
+
const absDir = path2__default.default.resolve(baseDir, relFromBase);
|
|
951
|
+
const relFromRoot = toPosixPath(
|
|
952
|
+
toProjectRelativePath(projectRoot, absDir)
|
|
953
|
+
);
|
|
954
|
+
desiredPaths.add(relFromRoot);
|
|
955
|
+
ensureDirSync(absDir);
|
|
956
|
+
const nextStub = entry.stub ?? inheritedStub;
|
|
957
|
+
if (entry.children) {
|
|
958
|
+
for (const child of entry.children) {
|
|
959
|
+
await walk(child, nextStub);
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
async function handleFile(entry, inheritedStub) {
|
|
964
|
+
const relFromBase = entry.path.replace(/^[./]+/, "");
|
|
965
|
+
const absFile = path2__default.default.resolve(baseDir, relFromBase);
|
|
966
|
+
const relFromRoot = toPosixPath(
|
|
967
|
+
toProjectRelativePath(projectRoot, absFile)
|
|
968
|
+
);
|
|
969
|
+
desiredPaths.add(relFromRoot);
|
|
970
|
+
const stubName = entry.stub ?? inheritedStub;
|
|
971
|
+
const ctx = {
|
|
972
|
+
projectRoot,
|
|
973
|
+
targetPath: relFromRoot,
|
|
974
|
+
absolutePath: absFile,
|
|
975
|
+
isDirectory: false,
|
|
976
|
+
stubName
|
|
977
|
+
};
|
|
978
|
+
if (fs2__default.default.existsSync(absFile)) {
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
await hooks.runRegular("preCreateFile", ctx);
|
|
982
|
+
const dir = path2__default.default.dirname(absFile);
|
|
983
|
+
ensureDirSync(dir);
|
|
984
|
+
if (stubName) {
|
|
985
|
+
await hooks.runStub("preStub", ctx);
|
|
986
|
+
}
|
|
987
|
+
let content = "";
|
|
988
|
+
const stubContent = await hooks.renderStubContent(ctx);
|
|
989
|
+
if (typeof stubContent === "string") {
|
|
990
|
+
content = stubContent;
|
|
991
|
+
}
|
|
992
|
+
fs2__default.default.writeFileSync(absFile, content, "utf8");
|
|
993
|
+
const stats = fs2__default.default.statSync(absFile);
|
|
994
|
+
cache.set({
|
|
995
|
+
path: relFromRoot,
|
|
996
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
997
|
+
sizeAtCreate: stats.size,
|
|
998
|
+
createdByStub: stubName,
|
|
999
|
+
groupName,
|
|
1000
|
+
groupRoot
|
|
1001
|
+
});
|
|
1002
|
+
logger5.info(`created ${relFromRoot}`);
|
|
1003
|
+
if (stubName) {
|
|
1004
|
+
await hooks.runStub("postStub", ctx);
|
|
1005
|
+
}
|
|
1006
|
+
await hooks.runRegular("postCreateFile", ctx);
|
|
1007
|
+
}
|
|
1008
|
+
for (const entry of structure) {
|
|
1009
|
+
await walk(entry);
|
|
1010
|
+
}
|
|
1011
|
+
for (const cachedPath of cache.allPaths()) {
|
|
1012
|
+
if (desiredPaths.has(cachedPath)) continue;
|
|
1013
|
+
const abs = path2__default.default.resolve(projectRoot, cachedPath);
|
|
1014
|
+
const stats = statSafeSync(abs);
|
|
1015
|
+
if (!stats) {
|
|
1016
|
+
cache.delete(cachedPath);
|
|
1017
|
+
continue;
|
|
1018
|
+
}
|
|
1019
|
+
if (!stats.isFile()) {
|
|
1020
|
+
cache.delete(cachedPath);
|
|
1021
|
+
continue;
|
|
1022
|
+
}
|
|
1023
|
+
const entry = cache.get(cachedPath);
|
|
1024
|
+
const ctx = {
|
|
1025
|
+
projectRoot,
|
|
1026
|
+
targetPath: cachedPath,
|
|
1027
|
+
absolutePath: abs,
|
|
1028
|
+
isDirectory: false,
|
|
1029
|
+
stubName: entry?.createdByStub
|
|
1030
|
+
};
|
|
1031
|
+
await hooks.runRegular("preDeleteFile", ctx);
|
|
1032
|
+
let shouldDelete = true;
|
|
1033
|
+
if (stats.size > threshold && interactiveDelete) {
|
|
1034
|
+
const res = await interactiveDelete({
|
|
1035
|
+
absolutePath: abs,
|
|
1036
|
+
relativePath: cachedPath,
|
|
1037
|
+
size: stats.size,
|
|
1038
|
+
createdByStub: entry?.createdByStub,
|
|
1039
|
+
groupName: entry?.groupName
|
|
1040
|
+
});
|
|
1041
|
+
if (res === "keep") {
|
|
1042
|
+
shouldDelete = false;
|
|
1043
|
+
cache.delete(cachedPath);
|
|
1044
|
+
logger5.info(`keeping ${cachedPath} (removed from cache)`);
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
if (shouldDelete) {
|
|
1048
|
+
try {
|
|
1049
|
+
fs2__default.default.unlinkSync(abs);
|
|
1050
|
+
logger5.info(`deleted ${cachedPath}`);
|
|
1051
|
+
} catch (err) {
|
|
1052
|
+
logger5.warn(`failed to delete ${cachedPath}`, err);
|
|
1053
|
+
}
|
|
1054
|
+
cache.delete(cachedPath);
|
|
1055
|
+
await hooks.runRegular("postDeleteFile", ctx);
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
function getStructureFilesFromConfig(projectRoot, scaffoldDir, config) {
|
|
1060
|
+
const baseDir = path2__default.default.resolve(projectRoot, scaffoldDir || SCAFFOLD_ROOT_DIR);
|
|
1061
|
+
const files = [];
|
|
1062
|
+
if (config.groups && config.groups.length > 0) {
|
|
1063
|
+
for (const group of config.groups) {
|
|
1064
|
+
const structureFile = group.structureFile && group.structureFile.trim().length ? group.structureFile : `${group.name}.txt`;
|
|
1065
|
+
files.push(path2__default.default.join(baseDir, structureFile));
|
|
1066
|
+
}
|
|
1067
|
+
} else {
|
|
1068
|
+
const structureFile = config.structureFile || "structure.txt";
|
|
1069
|
+
files.push(path2__default.default.join(baseDir, structureFile));
|
|
1070
|
+
}
|
|
1071
|
+
return files;
|
|
1072
|
+
}
|
|
1073
|
+
async function formatStructureFilesFromConfig(projectRoot, scaffoldDir, config, opts = {}) {
|
|
1074
|
+
const formatCfg = config.format;
|
|
1075
|
+
const enabled = !!(formatCfg?.enabled || opts.force);
|
|
1076
|
+
if (!enabled) return;
|
|
1077
|
+
const files = getStructureFilesFromConfig(projectRoot, scaffoldDir, config);
|
|
1078
|
+
const indentStep = formatCfg?.indentStep ?? config.indentStep ?? 2;
|
|
1079
|
+
const mode = formatCfg?.mode ?? "loose";
|
|
1080
|
+
!!formatCfg?.sortEntries;
|
|
1081
|
+
for (const filePath of files) {
|
|
1082
|
+
let text;
|
|
1083
|
+
try {
|
|
1084
|
+
text = fs2__default.default.readFileSync(filePath, "utf8");
|
|
1085
|
+
} catch {
|
|
1086
|
+
continue;
|
|
1087
|
+
}
|
|
1088
|
+
const { text: formatted } = formatStructureText(text, {
|
|
1089
|
+
indentStep,
|
|
1090
|
+
mode});
|
|
1091
|
+
if (formatted !== text) {
|
|
1092
|
+
fs2__default.default.writeFileSync(filePath, formatted, "utf8");
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
// src/core/runner.ts
|
|
1098
|
+
async function runOnce(cwd, options = {}) {
|
|
1099
|
+
const logger5 = options.logger ?? defaultLogger.child("[runner]");
|
|
1100
|
+
const { config, scaffoldDir, projectRoot } = await loadScaffoldConfig(cwd, {
|
|
1101
|
+
scaffoldDir: options.scaffoldDir,
|
|
1102
|
+
configPath: options.configPath
|
|
1103
|
+
});
|
|
1104
|
+
await formatStructureFilesFromConfig(projectRoot, scaffoldDir, config, { force: options.format });
|
|
1105
|
+
const cachePath = config.cacheFile ?? ".scaffold-cache.json";
|
|
1106
|
+
const cache = new CacheManager(projectRoot, cachePath);
|
|
1107
|
+
cache.load();
|
|
1108
|
+
const hooks = new HookRunner(config);
|
|
1109
|
+
if (config.groups && config.groups.length > 0) {
|
|
1110
|
+
for (const group of config.groups) {
|
|
1111
|
+
const groupRootAbs = path2__default.default.resolve(projectRoot, group.root);
|
|
1112
|
+
const structure = resolveGroupStructure(scaffoldDir, group);
|
|
1113
|
+
const groupLogger = logger5.child(`[group:${group.name}]`);
|
|
1114
|
+
await applyStructure({
|
|
1115
|
+
config,
|
|
1116
|
+
projectRoot,
|
|
1117
|
+
baseDir: groupRootAbs,
|
|
1118
|
+
structure,
|
|
1119
|
+
cache,
|
|
1120
|
+
hooks,
|
|
1121
|
+
groupName: group.name,
|
|
1122
|
+
groupRoot: group.root,
|
|
1123
|
+
interactiveDelete: options.interactiveDelete,
|
|
1124
|
+
logger: groupLogger
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
} else {
|
|
1128
|
+
const structure = resolveSingleStructure(scaffoldDir, config);
|
|
1129
|
+
const baseLogger = logger5.child("[group:default]");
|
|
1130
|
+
await applyStructure({
|
|
1131
|
+
config,
|
|
1132
|
+
projectRoot,
|
|
1133
|
+
baseDir: projectRoot,
|
|
1134
|
+
structure,
|
|
1135
|
+
cache,
|
|
1136
|
+
hooks,
|
|
1137
|
+
groupName: "default",
|
|
1138
|
+
groupRoot: ".",
|
|
1139
|
+
interactiveDelete: options.interactiveDelete,
|
|
1140
|
+
logger: baseLogger
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
cache.save();
|
|
1144
|
+
}
|
|
1145
|
+
var logger4 = defaultLogger.child("[scan]");
|
|
1146
|
+
var DEFAULT_IGNORE = [
|
|
1147
|
+
"node_modules/**",
|
|
1148
|
+
".git/**",
|
|
1149
|
+
"dist/**",
|
|
1150
|
+
"build/**",
|
|
1151
|
+
".turbo/**",
|
|
1152
|
+
".next/**",
|
|
1153
|
+
"coverage/**"
|
|
1154
|
+
];
|
|
1155
|
+
function scanDirectoryToStructureText(rootDir, options = {}) {
|
|
1156
|
+
const absRoot = path2__default.default.resolve(rootDir);
|
|
1157
|
+
const lines = [];
|
|
1158
|
+
const ignorePatterns = options.ignore ?? DEFAULT_IGNORE;
|
|
1159
|
+
const maxDepth = options.maxDepth ?? Infinity;
|
|
1160
|
+
function isIgnored(absPath) {
|
|
1161
|
+
const rel = toPosixPath(path2__default.default.relative(absRoot, absPath));
|
|
1162
|
+
if (!rel || rel === ".") return false;
|
|
1163
|
+
return ignorePatterns.some(
|
|
1164
|
+
(pattern) => minimatch.minimatch(rel, pattern, { dot: true })
|
|
1165
|
+
);
|
|
1166
|
+
}
|
|
1167
|
+
function walk(currentAbs, depth) {
|
|
1168
|
+
if (depth > maxDepth) return;
|
|
1169
|
+
let dirents;
|
|
1170
|
+
try {
|
|
1171
|
+
dirents = fs2__default.default.readdirSync(currentAbs, { withFileTypes: true });
|
|
1172
|
+
} catch {
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
dirents.sort((a, b) => {
|
|
1176
|
+
if (a.isDirectory() && !b.isDirectory()) return -1;
|
|
1177
|
+
if (!a.isDirectory() && b.isDirectory()) return 1;
|
|
1178
|
+
return a.name.localeCompare(b.name);
|
|
1179
|
+
});
|
|
1180
|
+
for (const dirent of dirents) {
|
|
1181
|
+
const name = dirent.name;
|
|
1182
|
+
const absPath = path2__default.default.join(currentAbs, name);
|
|
1183
|
+
if (isIgnored(absPath)) continue;
|
|
1184
|
+
const indent = " ".repeat(depth);
|
|
1185
|
+
if (dirent.isDirectory()) {
|
|
1186
|
+
lines.push(`${indent}${name}/`);
|
|
1187
|
+
walk(absPath, depth + 1);
|
|
1188
|
+
} else if (dirent.isFile()) {
|
|
1189
|
+
lines.push(`${indent}${name}`);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
walk(absRoot, 0);
|
|
1194
|
+
return lines.join("\n");
|
|
1195
|
+
}
|
|
1196
|
+
async function scanProjectFromConfig(cwd, options = {}) {
|
|
1197
|
+
const { config, scaffoldDir, projectRoot } = await loadScaffoldConfig(cwd, {
|
|
1198
|
+
scaffoldDir: options.scaffoldDir
|
|
1199
|
+
});
|
|
1200
|
+
const ignorePatterns = options.ignore ?? DEFAULT_IGNORE;
|
|
1201
|
+
const maxDepth = options.maxDepth ?? Infinity;
|
|
1202
|
+
const onlyGroups = options.groups;
|
|
1203
|
+
const results = [];
|
|
1204
|
+
function scanGroup(cfg, group) {
|
|
1205
|
+
const rootAbs = path2__default.default.resolve(projectRoot, group.root);
|
|
1206
|
+
const text = scanDirectoryToStructureText(rootAbs, {
|
|
1207
|
+
ignore: ignorePatterns,
|
|
1208
|
+
maxDepth
|
|
1209
|
+
});
|
|
1210
|
+
const structureFileName = group.structureFile ?? `${group.name}.txt`;
|
|
1211
|
+
const structureFilePath = path2__default.default.join(scaffoldDir, structureFileName);
|
|
1212
|
+
return {
|
|
1213
|
+
groupName: group.name,
|
|
1214
|
+
groupRoot: group.root,
|
|
1215
|
+
structureFileName,
|
|
1216
|
+
structureFilePath,
|
|
1217
|
+
text
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
if (config.groups && config.groups.length > 0) {
|
|
1221
|
+
logger4.debug(
|
|
1222
|
+
`Scanning project from config with ${config.groups.length} group(s).`
|
|
1223
|
+
);
|
|
1224
|
+
for (const group of config.groups) {
|
|
1225
|
+
if (onlyGroups && !onlyGroups.includes(group.name)) {
|
|
1226
|
+
continue;
|
|
1227
|
+
}
|
|
1228
|
+
const result = scanGroup(config, group);
|
|
1229
|
+
results.push(result);
|
|
1230
|
+
}
|
|
1231
|
+
} else {
|
|
1232
|
+
logger4.debug("Scanning project in single-root mode (no groups).");
|
|
1233
|
+
const text = scanDirectoryToStructureText(projectRoot, {
|
|
1234
|
+
ignore: ignorePatterns,
|
|
1235
|
+
maxDepth
|
|
1236
|
+
});
|
|
1237
|
+
const structureFileName = config.structureFile ?? "structure.txt";
|
|
1238
|
+
const structureFilePath = path2__default.default.join(scaffoldDir, structureFileName);
|
|
1239
|
+
results.push({
|
|
1240
|
+
groupName: "default",
|
|
1241
|
+
groupRoot: ".",
|
|
1242
|
+
structureFileName,
|
|
1243
|
+
structureFilePath,
|
|
1244
|
+
text
|
|
1245
|
+
});
|
|
1246
|
+
}
|
|
1247
|
+
return results;
|
|
1248
|
+
}
|
|
1249
|
+
async function writeScannedStructuresFromConfig(cwd, options = {}) {
|
|
1250
|
+
const { scaffoldDir } = await loadScaffoldConfig(cwd, {
|
|
1251
|
+
scaffoldDir: options.scaffoldDir
|
|
1252
|
+
});
|
|
1253
|
+
ensureDirSync(scaffoldDir);
|
|
1254
|
+
const results = await scanProjectFromConfig(cwd, options);
|
|
1255
|
+
for (const result of results) {
|
|
1256
|
+
fs2__default.default.writeFileSync(result.structureFilePath, result.text, "utf8");
|
|
1257
|
+
logger4.info(
|
|
1258
|
+
`Wrote structure for group "${result.groupName}" to ${result.structureFilePath}`
|
|
1259
|
+
);
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
async function ensureStructureFilesFromConfig(cwd, options = {}) {
|
|
1263
|
+
const { config, scaffoldDir } = await loadScaffoldConfig(cwd, {
|
|
1264
|
+
scaffoldDir: options.scaffoldDirOverride
|
|
1265
|
+
});
|
|
1266
|
+
ensureDirSync(scaffoldDir);
|
|
1267
|
+
const created = [];
|
|
1268
|
+
const existing = [];
|
|
1269
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1270
|
+
const ensureFile = (fileName) => {
|
|
1271
|
+
if (!fileName) return;
|
|
1272
|
+
const filePath = path2__default.default.join(scaffoldDir, fileName);
|
|
1273
|
+
const key = path2__default.default.resolve(filePath);
|
|
1274
|
+
if (seen.has(key)) return;
|
|
1275
|
+
seen.add(key);
|
|
1276
|
+
if (fs2__default.default.existsSync(filePath)) {
|
|
1277
|
+
existing.push(filePath);
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
const header = `# ${fileName}
|
|
1281
|
+
# Structure file for @timeax/scaffold
|
|
1282
|
+
# Define your desired folders/files here.
|
|
1283
|
+
`;
|
|
1284
|
+
fs2__default.default.writeFileSync(filePath, header, "utf8");
|
|
1285
|
+
created.push(filePath);
|
|
1286
|
+
};
|
|
1287
|
+
if (config.groups && config.groups.length > 0) {
|
|
1288
|
+
for (const group of config.groups) {
|
|
1289
|
+
const fileName = group.structureFile ?? `${group.name}.txt`;
|
|
1290
|
+
ensureFile(fileName);
|
|
1291
|
+
}
|
|
1292
|
+
} else {
|
|
1293
|
+
const fileName = config.structureFile ?? "structure.txt";
|
|
1294
|
+
ensureFile(fileName);
|
|
1295
|
+
}
|
|
1296
|
+
logger4.debug(
|
|
1297
|
+
`ensureStructureFilesFromConfig: created=${created.length}, existing=${existing.length}`
|
|
1298
|
+
);
|
|
1299
|
+
return { created, existing };
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
exports.SCAFFOLD_ROOT_DIR = SCAFFOLD_ROOT_DIR;
|
|
1303
|
+
exports.ensureStructureFilesFromConfig = ensureStructureFilesFromConfig;
|
|
1304
|
+
exports.loadScaffoldConfig = loadScaffoldConfig;
|
|
1305
|
+
exports.parseStructureText = parseStructureText;
|
|
1306
|
+
exports.runOnce = runOnce;
|
|
1307
|
+
exports.scanDirectoryToStructureText = scanDirectoryToStructureText;
|
|
1308
|
+
exports.scanProjectFromConfig = scanProjectFromConfig;
|
|
1309
|
+
exports.writeScannedStructuresFromConfig = writeScannedStructuresFromConfig;
|
|
1310
|
+
//# sourceMappingURL=index.cjs.map
|
|
1311
|
+
//# sourceMappingURL=index.cjs.map
|