markdown-patch 0.1.0

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/.tool-versions ADDED
@@ -0,0 +1 @@
1
+ nodejs 20.8.0
@@ -0,0 +1,21 @@
1
+ {
2
+ // Use IntelliSense to learn about possible attributes.
3
+ // Hover to view descriptions of existing attributes.
4
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+ "version": "0.2.0",
6
+ "configurations": [
7
+ {
8
+ "type": "node",
9
+ "request": "launch",
10
+ "name": "Jest All",
11
+ //"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/jest",
12
+ "args": [
13
+ "--runInBand"
14
+ ],
15
+ "console": "integratedTerminal",
16
+ "internalConsoleOptions": "neverOpen",
17
+ "program": "${workspaceFolder}/node_modules/.bin/jest",
18
+ "cwd": "${workspaceFolder}"
19
+ }
20
+ ]
21
+ }
package/dist/index.js ADDED
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import fs from "fs/promises";
4
+ import { getDocumentMap } from "./map.js";
5
+ import { printMap } from "./debug.js";
6
+ import { applyPatch } from "./patch.js";
7
+ async function readStdin() {
8
+ return new Promise((resolve, reject) => {
9
+ let data = "";
10
+ process.stdin.on("data", (chunk) => (data += chunk));
11
+ process.stdin.on("end", () => resolve(data));
12
+ process.stdin.on("error", reject);
13
+ });
14
+ }
15
+ const program = new Command();
16
+ // Configure the CLI
17
+ program
18
+ .name("mdpatch")
19
+ .description("Change markdown documents by inserting or changing content relative to headings or other parst of a document's structure.")
20
+ .version("0.1.0");
21
+ program
22
+ .command("print-map")
23
+ .argument("<path>", "filepath to show identified patchable paths for")
24
+ .argument("[regex]", "limit displayed matches to those matching the supplied regular expression")
25
+ .action(async (path, regex) => {
26
+ const document = await fs.readFile(path, "utf-8");
27
+ const documentMap = getDocumentMap(document);
28
+ printMap(document, documentMap, regex ? new RegExp(regex) : undefined);
29
+ });
30
+ program
31
+ .command("apply")
32
+ .argument("<path>", "file to patch")
33
+ .argument("<patch>", "patch file to apply")
34
+ .option("-o, --output <output>", "write output to the specified path instead of applying in-place; use '-' for stdout")
35
+ .action(async (path, patch, options) => {
36
+ let patchParsed;
37
+ let patchData;
38
+ try {
39
+ if (patch === "-") {
40
+ patchData = await readStdin();
41
+ }
42
+ else {
43
+ patchData = await fs.readFile(patch, "utf-8");
44
+ }
45
+ }
46
+ catch (e) {
47
+ console.error("Failed to read patch: ", e);
48
+ process.exit(1);
49
+ }
50
+ try {
51
+ const parsedData = JSON.parse(patchData);
52
+ if (!Array.isArray(parsedData)) {
53
+ patchParsed = [parsedData];
54
+ }
55
+ else {
56
+ patchParsed = parsedData;
57
+ }
58
+ }
59
+ catch (e) {
60
+ console.error("Could not parse patch file as JSON");
61
+ process.exit(1);
62
+ }
63
+ let document = await fs.readFile(path, "utf-8");
64
+ console.log("Document", document);
65
+ for (const instruction of patchParsed) {
66
+ document = applyPatch(document, instruction);
67
+ }
68
+ if (options.output === "-") {
69
+ process.stdout.write(document);
70
+ }
71
+ else {
72
+ await fs.writeFile(options.output ? options.output : path, document);
73
+ }
74
+ });
75
+ program.parse(process.argv);
package/document.md ADDED
@@ -0,0 +1,11 @@
1
+ # Main
2
+
3
+ Some content
4
+
5
+ ## Secondary
6
+
7
+ Some more content
8
+
9
+ ## Tertiary
10
+
11
+ Even more content
@@ -0,0 +1,8 @@
1
+ [
2
+ {
3
+ "operation": "append",
4
+ "targetType": "heading",
5
+ "target": ["Main", "Secondary"],
6
+ "content": "This is a test\n"
7
+ }
8
+ ]
package/jest.config.ts ADDED
@@ -0,0 +1,9 @@
1
+ module.exports = {
2
+ preset: 'ts-jest',
3
+ testEnvironment: 'node',
4
+ // Include other configurations if needed
5
+ testPathIgnorePatterns: [
6
+ "/node_modules/",
7
+ "/dist/"
8
+ ]
9
+ };
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "dependencies": {
3
+ "@tsconfig/node16": "^16.1.3",
4
+ "chalk": "^5.3.0",
5
+ "commander": "^12.1.0",
6
+ "marked": "^14.1.0"
7
+ },
8
+ "devDependencies": {
9
+ "@types/commander": "^2.12.2",
10
+ "@types/jest": "^29.5.12",
11
+ "@types/node": "^22.4.0",
12
+ "jest": "^29.7.0",
13
+ "ts-jest": "^29.2.4",
14
+ "ts-node": "^10.9.2",
15
+ "typescript": "^5.5.4"
16
+ },
17
+ "name": "markdown-patch",
18
+ "version": "0.1.0",
19
+ "main": "index.js",
20
+ "scripts": {
21
+ "test": "node node_modules/.bin/jest"
22
+ },
23
+ "bin": {
24
+ "mdpatch": "./dist/index.js"
25
+ },
26
+ "keywords": [],
27
+ "author": "",
28
+ "license": "ISC",
29
+ "description": "Change markdown documents by inserting or changing content relative to headings or other parts of a document's structure.",
30
+ "type": "module"
31
+ }
@@ -0,0 +1,11 @@
1
+ export const TARGETABLE_BY_ISOLATED_BLOCK_REFERENCE = [
2
+ "code",
3
+ "heading",
4
+ "table",
5
+ "blockquote",
6
+ "list",
7
+ "paragraph",
8
+ "image",
9
+ ];
10
+
11
+ export const CAN_INCLUDE_BLOCK_REFERENCE = ["paragraph", "list_item"];
package/src/debug.ts ADDED
@@ -0,0 +1,75 @@
1
+ import chalk from "chalk";
2
+ import { DocumentMap } from "./types.js";
3
+
4
+ export const printMap = (
5
+ content: string,
6
+ documentMap: DocumentMap,
7
+ regex: RegExp | undefined
8
+ ): void => {
9
+ for (const type in documentMap) {
10
+ for (const positionName in documentMap[type as keyof typeof documentMap]) {
11
+ const position =
12
+ documentMap[type as keyof typeof documentMap][positionName];
13
+
14
+ const blockName = `${type} :: ${positionName.replaceAll(
15
+ "\u001f",
16
+ " :: "
17
+ )}`;
18
+ if (regex && !blockName.match(regex)) {
19
+ continue;
20
+ }
21
+ console.log("\n" + chalk.blue(blockName));
22
+ if (position.content.start < position.marker.start) {
23
+ console.log(
24
+ content
25
+ .slice(position.content.start - 100, position.content.start)
26
+ .replaceAll("\n", "\\n\n") +
27
+ chalk.black.bgGreen(
28
+ content
29
+ .slice(position.content.start, position.content.end)
30
+ .replaceAll("\n", "\\n\n")
31
+ ) +
32
+ content
33
+ .slice(
34
+ position.content.end,
35
+ Math.min(position.content.end + 100, position.marker.start)
36
+ )
37
+ .replaceAll("\n", "\\n\n") +
38
+ chalk.black.bgRed(
39
+ content
40
+ .slice(position.marker.start, position.marker.end)
41
+ .replaceAll("\n", "\\n\n")
42
+ ) +
43
+ content
44
+ .slice(position.marker.end, position.marker.end + 100)
45
+ .replaceAll("\n", "\\n\n")
46
+ );
47
+ } else {
48
+ console.log(
49
+ content
50
+ .slice(position.marker.start - 100, position.marker.start)
51
+ .replaceAll("\n", "\\n\n") +
52
+ chalk.black.bgRed(
53
+ content
54
+ .slice(position.marker.start, position.marker.end)
55
+ .replaceAll("\n", "\\n\n")
56
+ ) +
57
+ content
58
+ .slice(
59
+ position.marker.end,
60
+ Math.min(position.marker.end + 100, position.content.start)
61
+ )
62
+ .replaceAll("\n", "\\n\n") +
63
+ chalk.black.bgGreen(
64
+ content
65
+ .slice(position.content.start, position.content.end)
66
+ .replaceAll("\n", "\\n\n")
67
+ ) +
68
+ content
69
+ .slice(position.content.end, position.content.end + 100)
70
+ .replaceAll("\n", "\\n\n")
71
+ );
72
+ }
73
+ }
74
+ }
75
+ };
package/src/index.ts ADDED
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import fs from "fs/promises";
4
+ import { getDocumentMap } from "./map.js";
5
+ import { printMap } from "./debug.js";
6
+ import { PatchInstruction } from "./types.js";
7
+ import { applyPatch } from "./patch.js";
8
+ import packageJson from "../package.json" assert { type: "json" };
9
+
10
+ async function readStdin(): Promise<string> {
11
+ return new Promise((resolve, reject) => {
12
+ let data = "";
13
+ process.stdin.on("data", (chunk) => (data += chunk));
14
+ process.stdin.on("end", () => resolve(data));
15
+ process.stdin.on("error", reject);
16
+ });
17
+ }
18
+
19
+ const program = new Command();
20
+
21
+ // Configure the CLI
22
+ program
23
+ .name(Object.keys(packageJson.bin)[0])
24
+ .description(packageJson.description)
25
+ .version(packageJson.version);
26
+
27
+ program
28
+ .command("print-map")
29
+ .argument("<path>", "filepath to show identified patchable paths for")
30
+ .argument(
31
+ "[regex]",
32
+ "limit displayed matches to those matching the supplied regular expression"
33
+ )
34
+ .action(async (path: string, regex: string | undefined) => {
35
+ const document = await fs.readFile(path, "utf-8");
36
+ const documentMap = getDocumentMap(document);
37
+
38
+ printMap(document, documentMap, regex ? new RegExp(regex) : undefined);
39
+ });
40
+
41
+ program
42
+ .command("apply")
43
+ .argument("<path>", "file to patch")
44
+ .argument("<patch>", "patch file to apply")
45
+ .option(
46
+ "-o, --output <output>",
47
+ "write output to the specified path instead of applying in-place; use '-' for stdout"
48
+ )
49
+ .action(async (path: string, patch: string, options) => {
50
+ let patchParsed: PatchInstruction[];
51
+ let patchData: string;
52
+ try {
53
+ if (patch === "-") {
54
+ patchData = await readStdin();
55
+ } else {
56
+ patchData = await fs.readFile(patch, "utf-8");
57
+ }
58
+ } catch (e) {
59
+ console.error("Failed to read patch: ", e);
60
+ process.exit(1);
61
+ }
62
+
63
+ try {
64
+ const parsedData = JSON.parse(patchData);
65
+ if (!Array.isArray(parsedData)) {
66
+ patchParsed = [parsedData];
67
+ } else {
68
+ patchParsed = parsedData;
69
+ }
70
+ } catch (e) {
71
+ console.error("Could not parse patch file as JSON");
72
+ process.exit(1);
73
+ }
74
+
75
+ let document = await fs.readFile(path, "utf-8");
76
+ console.log("Document", document);
77
+ for (const instruction of patchParsed) {
78
+ document = applyPatch(document, instruction);
79
+ }
80
+
81
+ if (options.output === "-") {
82
+ process.stdout.write(document);
83
+ } else {
84
+ await fs.writeFile(options.output ? options.output : path, document);
85
+ }
86
+ });
87
+
88
+ program.parse(process.argv);
package/src/map.ts ADDED
@@ -0,0 +1,200 @@
1
+ import * as marked from "marked";
2
+
3
+ import {
4
+ DocumentMap,
5
+ DocumentMapMarkerContentPair,
6
+ HeadingMarkerContentPair,
7
+ } from "./types.js";
8
+
9
+ import {
10
+ CAN_INCLUDE_BLOCK_REFERENCE,
11
+ TARGETABLE_BY_ISOLATED_BLOCK_REFERENCE,
12
+ } from "./constants.js";
13
+
14
+ function getHeadingPositions(
15
+ document: string,
16
+ tokens: marked.TokensList
17
+ ): Record<string, HeadingMarkerContentPair> {
18
+ // If the document starts with frontmatter, figure out where
19
+ // the frontmatter ends so we can know where the text of the
20
+ // document begins
21
+ let documentStart = 0;
22
+ if (tokens[0].type === "hr") {
23
+ documentStart = tokens[0].raw.length + 1;
24
+ for (const token of tokens.slice(1)) {
25
+ documentStart += token.raw.length;
26
+ if (token.type === "hr") {
27
+ break;
28
+ }
29
+ }
30
+ }
31
+
32
+ const positions: Record<string, HeadingMarkerContentPair> = {
33
+ "": {
34
+ content: {
35
+ start: documentStart,
36
+ end: document.length,
37
+ },
38
+ marker: {
39
+ start: 0,
40
+ end: 0,
41
+ },
42
+ level: 0,
43
+ },
44
+ };
45
+ const stack: Array<{ heading: string; position: HeadingMarkerContentPair }> =
46
+ [];
47
+
48
+ let currentPosition = 0;
49
+
50
+ tokens.forEach((token, index) => {
51
+ if (token.type === "heading") {
52
+ const headingToken = token as marked.Tokens.Heading;
53
+
54
+ const startHeading = document.indexOf(
55
+ headingToken.raw.trim(),
56
+ currentPosition
57
+ );
58
+ const endHeading = startHeading + headingToken.raw.trim().length + 1;
59
+ const headingLevel = headingToken.depth;
60
+
61
+ // Determine the start of the content after this heading
62
+ const startContent = endHeading;
63
+
64
+ // Determine the end of the content before the next heading of the same or higher level, or end of document
65
+ let endContent: number | undefined = undefined;
66
+ for (let i = index + 1; i < tokens.length; i++) {
67
+ if (
68
+ tokens[i].type === "heading" &&
69
+ (tokens[i] as marked.Tokens.Heading).depth <= headingLevel
70
+ ) {
71
+ endContent = document.indexOf(tokens[i].raw.trim(), startContent);
72
+ break;
73
+ }
74
+ }
75
+ if (endContent === undefined) {
76
+ endContent = document.length;
77
+ }
78
+
79
+ const currentHeading: HeadingMarkerContentPair = {
80
+ content: {
81
+ start: startContent,
82
+ end: endContent,
83
+ },
84
+ marker: {
85
+ start: startHeading,
86
+ end: endHeading,
87
+ },
88
+ level: headingLevel,
89
+ };
90
+
91
+ // Build the full heading path with parent headings separated by '\t'
92
+ let fullHeadingPath = headingToken.text.trim();
93
+ while (
94
+ stack.length &&
95
+ stack[stack.length - 1].position.level >= headingLevel
96
+ ) {
97
+ stack.pop();
98
+ }
99
+
100
+ if (stack.length) {
101
+ const parent = stack[stack.length - 1];
102
+ parent.position.content.end = endContent;
103
+ fullHeadingPath = `${parent.heading}\u001f${fullHeadingPath}`;
104
+ }
105
+
106
+ positions[fullHeadingPath] = currentHeading;
107
+ stack.push({ heading: fullHeadingPath, position: currentHeading });
108
+
109
+ currentPosition = endHeading;
110
+ }
111
+ });
112
+
113
+ return positions;
114
+ }
115
+
116
+ function getBlockPositions(
117
+ document: string,
118
+ tokens: marked.TokensList
119
+ ): Record<string, DocumentMapMarkerContentPair> {
120
+ const positions: Record<string, DocumentMapMarkerContentPair> = {};
121
+
122
+ let lastBlockDetails:
123
+ | {
124
+ token: marked.Token;
125
+ start: number;
126
+ end: number;
127
+ }
128
+ | undefined = undefined;
129
+ let startContent = 0;
130
+ let endContent = 0;
131
+ let endMarker = 0;
132
+ marked.walkTokens(tokens, (token) => {
133
+ const blockReferenceRegex = /(?:\s+|^)\^([a-zA-Z0-9_-]+)\s*$/;
134
+ startContent = document.indexOf(token.raw, startContent);
135
+ const match = blockReferenceRegex.exec(token.raw);
136
+ endContent = startContent + (match ? match.index : token.raw.length);
137
+ const startMarker = match ? startContent + match.index : -1;
138
+ endMarker = startContent + token.raw.length;
139
+ // The end of a list item token sometimes doesn't include the trailing
140
+ // newline -- i'm honestly not sure why, but treating it as
141
+ // included here would simplify my implementation
142
+ if (
143
+ document.slice(endMarker - 1, endMarker) !== "\n" &&
144
+ document.slice(endMarker, endMarker + 1) === "\n"
145
+ ) {
146
+ endMarker += 1;
147
+ } else if (
148
+ document.slice(endMarker - 2, endMarker) !== "\r\n" &&
149
+ document.slice(endMarker, endMarker + 2) === "\r\n"
150
+ ) {
151
+ endMarker += 2;
152
+ }
153
+ if (CAN_INCLUDE_BLOCK_REFERENCE.includes(token.type) && match) {
154
+ const name = match[1];
155
+ if (!name || match.index === undefined) {
156
+ return;
157
+ }
158
+
159
+ const finalStartContent = {
160
+ start: startContent,
161
+ end: endContent,
162
+ };
163
+ if (
164
+ finalStartContent.start === finalStartContent.end &&
165
+ lastBlockDetails
166
+ ) {
167
+ finalStartContent.start = lastBlockDetails.start;
168
+ finalStartContent.end = lastBlockDetails.end;
169
+ }
170
+
171
+ positions[name] = {
172
+ content: finalStartContent,
173
+ marker: {
174
+ start: startMarker,
175
+ end: endMarker,
176
+ },
177
+ };
178
+ }
179
+
180
+ if (TARGETABLE_BY_ISOLATED_BLOCK_REFERENCE.includes(token.type)) {
181
+ lastBlockDetails = {
182
+ token: token,
183
+ start: startContent,
184
+ end: endContent - 1,
185
+ };
186
+ }
187
+ });
188
+
189
+ return positions;
190
+ }
191
+
192
+ export const getDocumentMap = (document: string): DocumentMap => {
193
+ const lexer = new marked.Lexer();
194
+ const tokens = lexer.lex(document);
195
+
196
+ return {
197
+ heading: getHeadingPositions(document, tokens),
198
+ block: getBlockPositions(document, tokens),
199
+ };
200
+ };