@pluginfinity/engine 0.0.1 → 0.1.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/agents.js +88 -0
- package/body.js +110 -0
- package/component.js +157 -0
- package/discovery.js +1 -1
- package/doctor.js +1 -1
- package/emit.js +133 -0
- package/errors.js +198 -5
- package/frontmatter.js +169 -0
- package/hooks.js +118 -0
- package/index.d.ts +566 -9
- package/index.js +9 -2
- package/loader.js +3 -1
- package/manifest.js +45 -0
- package/operations.js +254 -8
- package/package.json +4 -3
- package/skills.js +132 -0
- package/version.js +1 -1
package/agents.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { applyHostBlocks } from "./body.js";
|
|
2
|
+
import { appendSections, mapFrontmatter } from "./frontmatter.js";
|
|
3
|
+
import { decodeComponent, frontmatterText, invalid, issue, overlayIssues, unknownTargets } from "./component.js";
|
|
4
|
+
import { AGENT_FIELDS, AgentFrontmatter } from "@pluginfinity/core";
|
|
5
|
+
import { Effect, FileSystem, Path } from "effect";
|
|
6
|
+
|
|
7
|
+
//#region src/agents.ts
|
|
8
|
+
/** Read and decode one agent file. */
|
|
9
|
+
const readAgent = (file, name, known) => Effect.gen(function* () {
|
|
10
|
+
const fs = yield* FileSystem.FileSystem;
|
|
11
|
+
const { frontmatter, frontmatterText: text, body, bodyOffset } = yield* decodeComponent(file, yield* fs.readFileString(file), AgentFrontmatter);
|
|
12
|
+
const problems = [...frontmatter.name === name ? [] : [issue("name", `must equal the file name "${name}"`)], ...unknownTargets(frontmatter.targets, known)];
|
|
13
|
+
if (problems.length > 0) return yield* Effect.fail(invalid(file, problems));
|
|
14
|
+
return {
|
|
15
|
+
name,
|
|
16
|
+
path: file,
|
|
17
|
+
frontmatter,
|
|
18
|
+
frontmatterText: text,
|
|
19
|
+
body,
|
|
20
|
+
bodyOffset
|
|
21
|
+
};
|
|
22
|
+
});
|
|
23
|
+
/**
|
|
24
|
+
* Read every agent under `<root>/agents/`, sorted by name; none when the
|
|
25
|
+
* directory is absent. An agent whose frontmatter does not decode, whose
|
|
26
|
+
* `name` differs from its file stem, or whose `targets` block names an
|
|
27
|
+
* unknown target is collected in `failures` rather than stopping the read,
|
|
28
|
+
* so one build reports them all.
|
|
29
|
+
*
|
|
30
|
+
* @public
|
|
31
|
+
*/
|
|
32
|
+
const readAgents = (root, known) => Effect.gen(function* () {
|
|
33
|
+
const fs = yield* FileSystem.FileSystem;
|
|
34
|
+
const path = yield* Path.Path;
|
|
35
|
+
const dir = path.join(root, "agents");
|
|
36
|
+
if (!(yield* fs.exists(dir))) return {
|
|
37
|
+
agents: [],
|
|
38
|
+
failures: []
|
|
39
|
+
};
|
|
40
|
+
const agents = [];
|
|
41
|
+
const failures = [];
|
|
42
|
+
for (const entry of (yield* fs.readDirectory(dir)).sort()) {
|
|
43
|
+
const file = path.join(dir, entry);
|
|
44
|
+
if (!entry.endsWith(".md") || (yield* fs.stat(file)).type !== "File") continue;
|
|
45
|
+
const agent = yield* readAgent(file, entry.slice(0, -3), known).pipe(Effect.catchTag("ComponentInvalid", (error) => Effect.sync(() => void failures.push(error))));
|
|
46
|
+
if (agent !== void 0) agents.push(agent);
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
agents,
|
|
50
|
+
failures
|
|
51
|
+
};
|
|
52
|
+
});
|
|
53
|
+
/**
|
|
54
|
+
* Render one agent for a target, or `undefined` when its `targets` block
|
|
55
|
+
* excludes it: the file at `<agents.dir>/<name><agents.suffix>` with the
|
|
56
|
+
* target's frontmatter, degraded fields appended as body sections, and host
|
|
57
|
+
* blocks applied. It keeps its source mode.
|
|
58
|
+
*
|
|
59
|
+
* @public
|
|
60
|
+
*/
|
|
61
|
+
const renderAgent = (target, id, agent, known) => Effect.gen(function* () {
|
|
62
|
+
const fs = yield* FileSystem.FileSystem;
|
|
63
|
+
const block = agent.frontmatter.targets?.[id];
|
|
64
|
+
if (block === false) return void 0;
|
|
65
|
+
const mapped = mapFrontmatter(target, target.agents.fields, target.agents.hostFields, agent.frontmatter, block ?? {});
|
|
66
|
+
const problems = [
|
|
67
|
+
...yield* overlayIssues(AgentFrontmatter, AGENT_FIELDS, agent.frontmatter, block ?? {}, id),
|
|
68
|
+
...mapped.unresolved.map((field) => issue(field.field, `${id} leaves this field unresolved (${field.note})`)),
|
|
69
|
+
...mapped.unknown.map((key) => issue(`targets.${id}.${key}`, `not an agent field or a ${id} agent field`))
|
|
70
|
+
];
|
|
71
|
+
const body = applyHostBlocks(agent.body, id, known);
|
|
72
|
+
if ("problem" in body) return yield* Effect.fail(invalid(agent.path, [issue(`line ${body.problem.line + agent.bodyOffset}`, body.problem.message)]));
|
|
73
|
+
if (problems.length > 0) return yield* Effect.fail(invalid(agent.path, problems, id));
|
|
74
|
+
const { name: _name, description, ...rest } = mapped.fields;
|
|
75
|
+
const yaml = yield* frontmatterText({
|
|
76
|
+
name: agent.name,
|
|
77
|
+
description,
|
|
78
|
+
...rest
|
|
79
|
+
}, agent);
|
|
80
|
+
return {
|
|
81
|
+
path: `${target.agents.dir}/${agent.name}${target.agents.suffix}`,
|
|
82
|
+
content: `---\n${yaml}---\n${appendSections(body.text, mapped.sections)}`,
|
|
83
|
+
mode: (yield* fs.stat(agent.path)).mode & 511
|
|
84
|
+
};
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
//#endregion
|
|
88
|
+
export { readAgents, renderAgent };
|
package/body.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
//#region src/body.ts
|
|
2
|
+
/**
|
|
3
|
+
* The markers of a host block: a line holding only
|
|
4
|
+
* `<!-- pluginfinity:only <id> [<id>…] -->` opens one, and a line holding only
|
|
5
|
+
* `<!-- /pluginfinity:only -->` closes it. A marker inside fenced code or an
|
|
6
|
+
* inline code span is text, so a body can show one.
|
|
7
|
+
*/
|
|
8
|
+
const OPEN = /^\s*<!--\s*pluginfinity:only\s+([^>]*?)\s*-->\s*$/;
|
|
9
|
+
const CLOSE = /^\s*<!--\s*\/pluginfinity:only\s*-->\s*$/;
|
|
10
|
+
const MARKER = /<!--\s*\/?pluginfinity:only/;
|
|
11
|
+
const FENCE = /^ {0,3}(`{3,}|~{3,})/;
|
|
12
|
+
const INLINE_CODE = /(`+)[\s\S]*?\1/g;
|
|
13
|
+
/**
|
|
14
|
+
* Keep the passages of a body's host blocks that list `target`, drop the
|
|
15
|
+
* rest, and remove every marker line. Blocks do not nest; an unclosed block,
|
|
16
|
+
* a stray close, a marker that is not on a line of its own, or an id outside
|
|
17
|
+
* `known` is a problem, and the body is not rewritten. So, until references
|
|
18
|
+
* are built, is a `pluginfinity://` link; see {@link referenceLines}.
|
|
19
|
+
*
|
|
20
|
+
* @public
|
|
21
|
+
*/
|
|
22
|
+
const applyHostBlocks = (text, target, known) => {
|
|
23
|
+
const [reference] = referenceLines(text);
|
|
24
|
+
if (reference !== void 0) return { problem: {
|
|
25
|
+
line: reference,
|
|
26
|
+
message: "pluginfinity:// references are not built yet; link with a relative path instead"
|
|
27
|
+
} };
|
|
28
|
+
if (!MARKER.test(text)) return { text };
|
|
29
|
+
const kept = [];
|
|
30
|
+
let open;
|
|
31
|
+
let fence;
|
|
32
|
+
const lines = text.split("\n");
|
|
33
|
+
for (const [index, line] of lines.entries()) {
|
|
34
|
+
const number = index + 1;
|
|
35
|
+
const keep = open === void 0 || open.keep;
|
|
36
|
+
const fenceMark = FENCE.exec(line)?.[1];
|
|
37
|
+
if (fence !== void 0 || fenceMark !== void 0) {
|
|
38
|
+
if (fence === void 0) fence = fenceMark;
|
|
39
|
+
else if (fenceMark !== void 0 && fenceMark[0] === fence[0] && fenceMark.length >= fence.length) fence = void 0;
|
|
40
|
+
if (keep) kept.push(line);
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
const opening = OPEN.exec(line);
|
|
44
|
+
if (opening !== null) {
|
|
45
|
+
if (open !== void 0) return { problem: {
|
|
46
|
+
line: number,
|
|
47
|
+
message: "host blocks do not nest"
|
|
48
|
+
} };
|
|
49
|
+
const ids = (opening[1] ?? "").split(/\s+/).filter((id) => id.length > 0);
|
|
50
|
+
const unknown = ids.filter((id) => !known.includes(id));
|
|
51
|
+
if (ids.length === 0) return { problem: {
|
|
52
|
+
line: number,
|
|
53
|
+
message: "a host block names no target"
|
|
54
|
+
} };
|
|
55
|
+
if (unknown.length > 0) return { problem: {
|
|
56
|
+
line: number,
|
|
57
|
+
message: `unknown target ${unknown.map((id) => `"${id}"`).join(", ")} in a host block`
|
|
58
|
+
} };
|
|
59
|
+
open = {
|
|
60
|
+
line: number,
|
|
61
|
+
keep: ids.includes(target)
|
|
62
|
+
};
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (CLOSE.test(line)) {
|
|
66
|
+
if (open === void 0) return { problem: {
|
|
67
|
+
line: number,
|
|
68
|
+
message: "a host block closes without opening"
|
|
69
|
+
} };
|
|
70
|
+
open = void 0;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (MARKER.test(line.replace(INLINE_CODE, ""))) return { problem: {
|
|
74
|
+
line: number,
|
|
75
|
+
message: "a host block marker must be on a line of its own"
|
|
76
|
+
} };
|
|
77
|
+
if (keep) kept.push(line);
|
|
78
|
+
}
|
|
79
|
+
if (open !== void 0) return { problem: {
|
|
80
|
+
line: open.line,
|
|
81
|
+
message: "a host block is never closed"
|
|
82
|
+
} };
|
|
83
|
+
return { text: kept.join("\n") };
|
|
84
|
+
};
|
|
85
|
+
const REFERENCE = /\]\(\s*<?pluginfinity:\/\//;
|
|
86
|
+
/**
|
|
87
|
+
* The 1-based lines of a body that link to a `pluginfinity://` reference,
|
|
88
|
+
* outside fenced code and inline code spans. References are not built yet,
|
|
89
|
+
* and an unbuilt reference must never ship as text, so each is a problem.
|
|
90
|
+
*
|
|
91
|
+
* @public
|
|
92
|
+
*/
|
|
93
|
+
const referenceLines = (text) => {
|
|
94
|
+
if (!text.includes("pluginfinity://")) return [];
|
|
95
|
+
const found = [];
|
|
96
|
+
let fence;
|
|
97
|
+
for (const [index, line] of text.split("\n").entries()) {
|
|
98
|
+
const fenceMark = FENCE.exec(line)?.[1];
|
|
99
|
+
if (fence !== void 0 || fenceMark !== void 0) {
|
|
100
|
+
if (fence === void 0) fence = fenceMark;
|
|
101
|
+
else if (fenceMark !== void 0 && fenceMark[0] === fence[0] && fenceMark.length >= fence.length) fence = void 0;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (REFERENCE.test(line.replace(INLINE_CODE, ""))) found.push(index + 1);
|
|
105
|
+
}
|
|
106
|
+
return found;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
//#endregion
|
|
110
|
+
export { applyHostBlocks, referenceLines };
|
package/component.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { ComponentInvalid, ConfigIssue } from "./errors.js";
|
|
2
|
+
import { splitFrontmatter } from "./frontmatter.js";
|
|
3
|
+
import { Effect, Schema, SchemaIssue } from "effect";
|
|
4
|
+
import { Yaml } from "@effected/yaml";
|
|
5
|
+
|
|
6
|
+
//#region src/component.ts
|
|
7
|
+
const formatter = SchemaIssue.makeFormatterStandardSchemaV1();
|
|
8
|
+
/**
|
|
9
|
+
* One problem with a component, keyed by field or by `line N, column M`.
|
|
10
|
+
*
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
13
|
+
const issue = (key, message) => ConfigIssue.make({
|
|
14
|
+
key,
|
|
15
|
+
message
|
|
16
|
+
});
|
|
17
|
+
/**
|
|
18
|
+
* A `ComponentInvalid` for `path`, optionally specific to one target.
|
|
19
|
+
*
|
|
20
|
+
* @internal
|
|
21
|
+
*/
|
|
22
|
+
const invalid = (path, issues, target) => new ComponentInvalid({
|
|
23
|
+
path,
|
|
24
|
+
issues: [...issues],
|
|
25
|
+
...target === void 0 ? {} : { target }
|
|
26
|
+
});
|
|
27
|
+
/**
|
|
28
|
+
* Plain values holding ` #`, which YAML reads as the start of a
|
|
29
|
+
* comment: Claude Code's own frontmatter reader keeps the rest of the line,
|
|
30
|
+
* every YAML parser drops it, so the value would silently lose its tail. It
|
|
31
|
+
* checks every depth, including a `targets` block and list items, and skips
|
|
32
|
+
* block scalars, where `#` is literal. A deliberate trailing comment is
|
|
33
|
+
* flagged too; frontmatter rarely wants one.
|
|
34
|
+
*/
|
|
35
|
+
const trailingComments = (frontmatter) => {
|
|
36
|
+
const issues = [];
|
|
37
|
+
let block;
|
|
38
|
+
for (const [index, line] of frontmatter.split("\n").entries()) {
|
|
39
|
+
const indent = /^[ \t]*/.exec(line)?.[0].length ?? 0;
|
|
40
|
+
if (block !== void 0 && (line.trim() === "" || indent > block)) continue;
|
|
41
|
+
block = void 0;
|
|
42
|
+
if (BLOCK_SCALAR.test(line)) {
|
|
43
|
+
block = indent;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const match = KEYED_PLAIN.exec(line) ?? ITEM_PLAIN.exec(line);
|
|
47
|
+
if (match === null) continue;
|
|
48
|
+
const subject = match[1] === void 0 ? "a list item" : `the plain value of ${match[1]}`;
|
|
49
|
+
issues.push(issue(`line ${index + 2}`, `${subject} holds " #", which YAML reads as a comment, dropping the rest of the line; quote or fold the value`));
|
|
50
|
+
}
|
|
51
|
+
return issues;
|
|
52
|
+
};
|
|
53
|
+
const BLOCK_SCALAR = /^[ \t]*(?:-[ \t]+)?(?:[A-Za-z_][\w-]*:[ \t]*)?[|>][-+0-9]*[ \t]*(?:#.*)?$/;
|
|
54
|
+
const KEYED_PLAIN = /^[ \t]*(?:-[ \t]+)?([A-Za-z_][\w-]*):[ \t]+[^"'|>\s#[{].*?[ \t]+#/;
|
|
55
|
+
const ITEM_PLAIN = /^[ \t]*-[ \t]+(?=[^"'|>\s#[{])(?![A-Za-z_][\w-]*:[ \t]).*?[ \t]+#/;
|
|
56
|
+
/**
|
|
57
|
+
* Split a component file's text at its frontmatter, parse the frontmatter as
|
|
58
|
+
* YAML, and decode it strictly against `schema`; any failure is a
|
|
59
|
+
* `ComponentInvalid` for `path`.
|
|
60
|
+
*
|
|
61
|
+
* @internal
|
|
62
|
+
*/
|
|
63
|
+
const decodeComponent = (path, text, schema) => Effect.gen(function* () {
|
|
64
|
+
const lf = toLf(text);
|
|
65
|
+
const split = splitFrontmatter(lf);
|
|
66
|
+
if (split === void 0) return yield* Effect.fail(invalid(path, [issue("", "the file must open with a --- frontmatter block")]));
|
|
67
|
+
const comments = trailingComments(split.frontmatter);
|
|
68
|
+
if (comments.length > 0) return yield* Effect.fail(invalid(path, comments));
|
|
69
|
+
const raw = yield* Yaml.parse(split.frontmatter).pipe(Effect.mapError((error) => invalid(path, error.diagnostics.map((diagnostic) => issue(`line ${diagnostic.line + 2}, column ${diagnostic.character + 1}`, `the frontmatter is not valid YAML: ${diagnostic.message}`)))));
|
|
70
|
+
const decoded = yield* Schema.decodeUnknownEffect(schema)(raw ?? {}, {
|
|
71
|
+
errors: "all",
|
|
72
|
+
onExcessProperty: "error"
|
|
73
|
+
}).pipe(Effect.mapError((error) => invalid(path, formatter(error.issue).issues.map((found) => issue((found.path ?? []).map(String).join("."), found.message)))));
|
|
74
|
+
const ordered = Object.fromEntries(Object.keys(typeof raw === "object" && raw !== null ? raw : {}).filter((key) => key in decoded).map((key) => [key, decoded[key]]));
|
|
75
|
+
const bodyOffset = lf.slice(0, lf.length - split.body.length).split("\n").length - 1;
|
|
76
|
+
return {
|
|
77
|
+
frontmatter: ordered,
|
|
78
|
+
frontmatterText: split.frontmatter,
|
|
79
|
+
body: split.body,
|
|
80
|
+
bodyOffset
|
|
81
|
+
};
|
|
82
|
+
});
|
|
83
|
+
/**
|
|
84
|
+
* The `targets` keys a component names that are not known target ids.
|
|
85
|
+
*
|
|
86
|
+
* @internal
|
|
87
|
+
*/
|
|
88
|
+
const unknownTargets = (targets, known) => Object.keys(targets ?? {}).filter((id) => !known.includes(id)).map((id) => issue(`targets.${id}`, `unknown target; known targets: ${known.join(", ")}`));
|
|
89
|
+
/**
|
|
90
|
+
* The YAML options every built frontmatter is written with: no folding,
|
|
91
|
+
* indented sequences, double quotes where quoting is needed, and YAML 1.1
|
|
92
|
+
* lookalikes quoted.
|
|
93
|
+
*
|
|
94
|
+
* @internal
|
|
95
|
+
*/
|
|
96
|
+
const STRINGIFY = {
|
|
97
|
+
lineWidth: 0,
|
|
98
|
+
quoteStyle: "double",
|
|
99
|
+
quoteCompat: "yaml-1.1",
|
|
100
|
+
indentSequences: true,
|
|
101
|
+
finalNewline: true
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* The frontmatter text a built component is written with: the author's own
|
|
105
|
+
* text when the fields come out exactly as they went in, so a target that
|
|
106
|
+
* keeps everything keeps the author's formatting and comments too, and
|
|
107
|
+
* otherwise the fields serialized with {@link STRINGIFY}.
|
|
108
|
+
*
|
|
109
|
+
* @internal
|
|
110
|
+
*/
|
|
111
|
+
const frontmatterText = (fields, source) => JSON.stringify(fields) === JSON.stringify(source.frontmatter) ? Effect.succeed(`${source.frontmatterText}\n`) : Yaml.stringify(fields, STRINGIFY).pipe(Effect.orDie);
|
|
112
|
+
/**
|
|
113
|
+
* Check the core fields a component's `targets.<id>` block sets, together with
|
|
114
|
+
* the base fields they overlay, against the component schema, so an override
|
|
115
|
+
* is held to the same rules as the base. Problems are keyed
|
|
116
|
+
* `targets.<id>.<field>`.
|
|
117
|
+
*
|
|
118
|
+
* @internal
|
|
119
|
+
*/
|
|
120
|
+
const overlayIssues = (schema, coreFields, frontmatter, block, id) => {
|
|
121
|
+
const overlay = Object.fromEntries(Object.entries(block).filter(([key]) => coreFields.includes(key)));
|
|
122
|
+
if (Object.keys(overlay).length === 0) return Effect.succeed([]);
|
|
123
|
+
const { targets: _targets, ...base } = frontmatter;
|
|
124
|
+
return Schema.decodeUnknownEffect(schema)({
|
|
125
|
+
...base,
|
|
126
|
+
...overlay
|
|
127
|
+
}, {
|
|
128
|
+
errors: "all",
|
|
129
|
+
onExcessProperty: "error"
|
|
130
|
+
}).pipe(Effect.as([]), Effect.catchTag("SchemaError", (error) => Effect.succeed(formatter(error.issue).issues.map((found) => {
|
|
131
|
+
const path = (found.path ?? []).map(String);
|
|
132
|
+
const key = path.join(".");
|
|
133
|
+
return issue(path[0] !== void 0 && path[0] in overlay ? `targets.${id}.${key}` : key, found.message);
|
|
134
|
+
}))));
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* Whether a file name is operating-system clutter that never ships, such as
|
|
138
|
+
* a Finder or Explorer index, or an editor backup.
|
|
139
|
+
*
|
|
140
|
+
* @internal
|
|
141
|
+
*/
|
|
142
|
+
const isJunk = (name) => JUNK.has(name) || name.endsWith("~");
|
|
143
|
+
const JUNK = /* @__PURE__ */ new Set([
|
|
144
|
+
".DS_Store",
|
|
145
|
+
"Thumbs.db",
|
|
146
|
+
"desktop.ini"
|
|
147
|
+
]);
|
|
148
|
+
/**
|
|
149
|
+
* Text with every CRLF line ending turned to LF, so a build's line endings do
|
|
150
|
+
* not depend on the machine that wrote the source.
|
|
151
|
+
*
|
|
152
|
+
* @internal
|
|
153
|
+
*/
|
|
154
|
+
const toLf = (text) => text.replaceAll("\r\n", "\n");
|
|
155
|
+
|
|
156
|
+
//#endregion
|
|
157
|
+
export { STRINGIFY, decodeComponent, frontmatterText, invalid, isJunk, issue, overlayIssues, toLf, unknownTargets };
|
package/discovery.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ConfigAmbiguous, ConfigNotFound } from "./errors.js";
|
|
2
|
+
import { Effect, FileSystem, Path } from "effect";
|
|
2
3
|
import { GlobPattern } from "@effected/glob";
|
|
3
4
|
import { Walker, descend } from "@effected/walker";
|
|
4
|
-
import { Effect, FileSystem, Path } from "effect";
|
|
5
5
|
|
|
6
6
|
//#region src/discovery.ts
|
|
7
7
|
/**
|
package/doctor.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { ConfigLoader } from "./loader.js";
|
|
2
2
|
import { selectConfigPaths } from "./selection.js";
|
|
3
3
|
import { ENGINE_VERSION } from "./version.js";
|
|
4
|
-
import { Walker } from "@effected/walker";
|
|
5
4
|
import { Duration, Effect, FileSystem, Option, Path, Result, Schema } from "effect";
|
|
5
|
+
import { Walker } from "@effected/walker";
|
|
6
6
|
import { Tool, ToolDiscovery } from "@effected/commands";
|
|
7
7
|
import { CurrentDistribution, DistributionField, Remediation } from "@effected/engine";
|
|
8
8
|
import { SemVer } from "@effected/semver";
|
package/emit.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { Effect, FileSystem, Path, Schema } from "effect";
|
|
2
|
+
|
|
3
|
+
//#region src/emit.ts
|
|
4
|
+
/**
|
|
5
|
+
* The mode every generated file is written with.
|
|
6
|
+
*
|
|
7
|
+
* @public
|
|
8
|
+
*/
|
|
9
|
+
const GENERATED_MODE = 420;
|
|
10
|
+
const encoder = new TextEncoder();
|
|
11
|
+
const bytesOf = (file) => typeof file.content === "string" ? encoder.encode(file.content) : file.content;
|
|
12
|
+
const modeOf = (file) => file.mode ?? 420;
|
|
13
|
+
/**
|
|
14
|
+
* How an output directory differs from what a build produces. Every list is
|
|
15
|
+
* sorted and holds `/`-separated paths relative to the output directory.
|
|
16
|
+
*
|
|
17
|
+
* @public
|
|
18
|
+
*/
|
|
19
|
+
var EmitPlan = class extends Schema.Class("EmitPlan")({
|
|
20
|
+
/** Produced, not on disk. */
|
|
21
|
+
added: Schema.Array(Schema.String),
|
|
22
|
+
/** On disk with other bytes or another mode. */
|
|
23
|
+
changed: Schema.Array(Schema.String),
|
|
24
|
+
/** On disk, no longer produced; an empty directory ends in `/`. */
|
|
25
|
+
removed: Schema.Array(Schema.String),
|
|
26
|
+
/** On disk with the same bytes and mode; never touched, so its mtime stays. */
|
|
27
|
+
unchanged: Schema.Array(Schema.String)
|
|
28
|
+
}) {
|
|
29
|
+
/** Whether the output directory already matches the build. */
|
|
30
|
+
get clean() {
|
|
31
|
+
return this.added.length === 0 && this.changed.length === 0 && this.removed.length === 0;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i]);
|
|
35
|
+
/**
|
|
36
|
+
* Every non-directory under `dir`, and every empty directory with a trailing
|
|
37
|
+
* `/`, as sorted `/`-separated relative paths. A build never produces an empty
|
|
38
|
+
* directory, so one on disk is always a leftover to remove.
|
|
39
|
+
*/
|
|
40
|
+
const inventory = (dir) => Effect.gen(function* () {
|
|
41
|
+
const fs = yield* FileSystem.FileSystem;
|
|
42
|
+
const path = yield* Path.Path;
|
|
43
|
+
if (!(yield* fs.exists(dir))) return [];
|
|
44
|
+
const files = [];
|
|
45
|
+
for (const entry of yield* fs.readDirectory(dir, { recursive: true })) {
|
|
46
|
+
const absolute = path.join(dir, entry);
|
|
47
|
+
const relative = entry.split(path.sep).join("/");
|
|
48
|
+
if ((yield* fs.stat(absolute)).type !== "Directory") files.push(relative);
|
|
49
|
+
else if ((yield* fs.readDirectory(absolute)).length === 0) files.push(`${relative}/`);
|
|
50
|
+
}
|
|
51
|
+
return files.sort();
|
|
52
|
+
});
|
|
53
|
+
/**
|
|
54
|
+
* Compare `files` with what `dir` holds, reading only.
|
|
55
|
+
*
|
|
56
|
+
* @public
|
|
57
|
+
*/
|
|
58
|
+
const planEmit = (dir, files) => Effect.gen(function* () {
|
|
59
|
+
const fs = yield* FileSystem.FileSystem;
|
|
60
|
+
const path = yield* Path.Path;
|
|
61
|
+
const existing = new Set(yield* inventory(dir));
|
|
62
|
+
const added = [];
|
|
63
|
+
const changed = [];
|
|
64
|
+
const unchanged = [];
|
|
65
|
+
for (const file of files) {
|
|
66
|
+
if (!existing.has(file.path)) {
|
|
67
|
+
added.push(file.path);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
const target = path.join(dir, file.path);
|
|
71
|
+
const info = yield* fs.stat(target);
|
|
72
|
+
(info.type === "File" && (info.mode & 511) === modeOf(file) && sameBytes(yield* fs.readFile(target), bytesOf(file)) ? unchanged : changed).push(file.path);
|
|
73
|
+
}
|
|
74
|
+
const produced = new Set(files.map((file) => file.path));
|
|
75
|
+
const removed = [...existing].filter((file) => !produced.has(file));
|
|
76
|
+
return EmitPlan.make({
|
|
77
|
+
added: added.sort(),
|
|
78
|
+
changed: changed.sort(),
|
|
79
|
+
removed,
|
|
80
|
+
unchanged: unchanged.sort()
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
/**
|
|
84
|
+
* Bring `dir` in line with `files` according to `plan`: stage every added and
|
|
85
|
+
* changed file in a sibling temporary directory first, so a failed write
|
|
86
|
+
* leaves `dir` untouched; then delete removed files and prune the directories
|
|
87
|
+
* they leave empty; then move each staged file into place. Unchanged files are
|
|
88
|
+
* never written.
|
|
89
|
+
*
|
|
90
|
+
* @remarks
|
|
91
|
+
* Removals run before the moves. A path that changes only by case is a
|
|
92
|
+
* removal and an addition naming the same file on a case-insensitive
|
|
93
|
+
* filesystem, so moving first and removing second deletes the new file. A
|
|
94
|
+
* path that turns from a file into a directory, or back, cannot be moved into
|
|
95
|
+
* place while the old entry still stands.
|
|
96
|
+
*
|
|
97
|
+
* @public
|
|
98
|
+
*/
|
|
99
|
+
const applyEmit = (dir, files, plan) => Effect.scoped(Effect.gen(function* () {
|
|
100
|
+
if (plan.clean) return;
|
|
101
|
+
const fs = yield* FileSystem.FileSystem;
|
|
102
|
+
const path = yield* Path.Path;
|
|
103
|
+
const parent = path.dirname(dir);
|
|
104
|
+
yield* fs.makeDirectory(parent, { recursive: true });
|
|
105
|
+
const staging = yield* fs.makeTempDirectoryScoped({
|
|
106
|
+
directory: parent,
|
|
107
|
+
prefix: ".pluginfinity-"
|
|
108
|
+
});
|
|
109
|
+
const writes = /* @__PURE__ */ new Set([...plan.added, ...plan.changed]);
|
|
110
|
+
const staged = files.filter((file) => writes.has(file.path));
|
|
111
|
+
for (const file of staged) {
|
|
112
|
+
const target = path.join(staging, file.path);
|
|
113
|
+
yield* fs.makeDirectory(path.dirname(target), { recursive: true });
|
|
114
|
+
yield* fs.writeFile(target, bytesOf(file));
|
|
115
|
+
yield* fs.chmod(target, modeOf(file));
|
|
116
|
+
}
|
|
117
|
+
for (const file of plan.removed) {
|
|
118
|
+
yield* fs.remove(path.join(dir, file), { recursive: file.endsWith("/") });
|
|
119
|
+
let current = path.dirname(path.join(dir, file));
|
|
120
|
+
while (current !== dir && current.startsWith(dir) && (yield* fs.readDirectory(current)).length === 0) {
|
|
121
|
+
yield* fs.remove(current, { recursive: true });
|
|
122
|
+
current = path.dirname(current);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
for (const file of staged) {
|
|
126
|
+
const target = path.join(dir, file.path);
|
|
127
|
+
yield* fs.makeDirectory(path.dirname(target), { recursive: true });
|
|
128
|
+
yield* fs.rename(path.join(staging, file.path), target);
|
|
129
|
+
}
|
|
130
|
+
}));
|
|
131
|
+
|
|
132
|
+
//#endregion
|
|
133
|
+
export { EmitPlan, GENERATED_MODE, applyEmit, planEmit };
|