webforai 1.4.1 → 1.5.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.
Files changed (50) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +61 -3
  3. package/dist/bin.js +1049 -0
  4. package/dist/cjs/cli/bin.js +34 -0
  5. package/dist/cjs/cli/commands/handlers/index.js +84 -0
  6. package/dist/cjs/cli/commands/handlers/loadHtml.js +127 -0
  7. package/dist/cjs/cli/constants.js +34 -0
  8. package/dist/cjs/cli/helpers/assertContinue.js +34 -0
  9. package/dist/cjs/cli/helpers/inputOutputPath.js +89 -0
  10. package/dist/cjs/cli/helpers/inputSourcePath.js +64 -0
  11. package/dist/cjs/cli/helpers/selectExtractMode.js +39 -0
  12. package/dist/cjs/cli/helpers/selectLoader.js +44 -0
  13. package/dist/cjs/cli/utils.js +122 -0
  14. package/dist/cjs/html-to-markdown.test.js +6 -34
  15. package/dist/cjs/index.js +5 -0
  16. package/dist/cli/bin.js +12 -0
  17. package/dist/cli/commands/handlers/index.js +51 -0
  18. package/dist/cli/commands/handlers/loadHtml.js +94 -0
  19. package/dist/cli/constants.js +9 -0
  20. package/dist/cli/helpers/assertContinue.js +11 -0
  21. package/dist/cli/helpers/inputOutputPath.js +56 -0
  22. package/dist/cli/helpers/inputSourcePath.js +31 -0
  23. package/dist/cli/helpers/selectExtractMode.js +16 -0
  24. package/dist/cli/helpers/selectLoader.js +21 -0
  25. package/dist/cli/utils.js +85 -0
  26. package/dist/html-to-markdown.test.js +6 -12
  27. package/dist/index.js +3 -0
  28. package/dist/types/cli/bin.d.ts +1 -0
  29. package/dist/types/cli/bin.js.map +1 -0
  30. package/dist/types/cli/commands/handlers/index.d.ts +13 -0
  31. package/dist/types/cli/commands/handlers/index.js.map +1 -0
  32. package/dist/types/cli/commands/handlers/loadHtml.d.ts +2 -0
  33. package/dist/types/cli/commands/handlers/loadHtml.js.map +1 -0
  34. package/dist/types/cli/constants.d.ts +5 -0
  35. package/dist/types/cli/constants.js.map +1 -0
  36. package/dist/types/cli/helpers/assertContinue.d.ts +1 -0
  37. package/dist/types/cli/helpers/assertContinue.js.map +1 -0
  38. package/dist/types/cli/helpers/inputOutputPath.d.ts +1 -0
  39. package/dist/types/cli/helpers/inputOutputPath.js.map +1 -0
  40. package/dist/types/cli/helpers/inputSourcePath.d.ts +1 -0
  41. package/dist/types/cli/helpers/inputSourcePath.js.map +1 -0
  42. package/dist/types/cli/helpers/selectExtractMode.d.ts +1 -0
  43. package/dist/types/cli/helpers/selectExtractMode.js.map +1 -0
  44. package/dist/types/cli/helpers/selectLoader.d.ts +1 -0
  45. package/dist/types/cli/helpers/selectLoader.js.map +1 -0
  46. package/dist/types/cli/utils.d.ts +5 -0
  47. package/dist/types/cli/utils.js.map +1 -0
  48. package/dist/types/index.d.ts +1 -0
  49. package/dist/types/index.js.map +1 -1
  50. package/package.json +11 -21
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var utils_exports = {};
30
+ __export(utils_exports, {
31
+ changeFileExtension: () => changeFileExtension,
32
+ getNextAvailableFilePath: () => getNextAvailableFilePath,
33
+ isUrl: () => isUrl,
34
+ sourcePathToOutputPath: () => sourcePathToOutputPath,
35
+ urlToFilename: () => urlToFilename
36
+ });
37
+ module.exports = __toCommonJS(utils_exports);
38
+ var import_node_fs = __toESM(require("node:fs"), 1);
39
+ var import_node_path = __toESM(require("node:path"), 1);
40
+ const isUrl = (maybeUrl) => {
41
+ try {
42
+ new URL(maybeUrl);
43
+ return true;
44
+ } catch {
45
+ return false;
46
+ }
47
+ };
48
+ function changeFileExtension(filePath, newExtension) {
49
+ const parsedPath = filePath.split("/");
50
+ const fileName = parsedPath[parsedPath.length - 1];
51
+ const formattedNewExtension = newExtension.startsWith(".") ? newExtension : `.${newExtension}`;
52
+ if (fileName.startsWith(".")) {
53
+ const parts = fileName.split(".");
54
+ if (parts.length === 2) {
55
+ return parsedPath.slice(0, -1).concat(`${fileName}${formattedNewExtension}`).join("/");
56
+ }
57
+ parts[parts.length - 1] = newExtension.replace(/^\./, "");
58
+ return parsedPath.slice(0, -1).concat(parts.join(".")).join("/");
59
+ }
60
+ const lastDotIndex = fileName.lastIndexOf(".");
61
+ const baseName = lastDotIndex !== -1 ? fileName.slice(0, lastDotIndex) : fileName;
62
+ const newFileName = `${baseName}${formattedNewExtension}`;
63
+ parsedPath[parsedPath.length - 1] = newFileName;
64
+ return parsedPath.join("/");
65
+ }
66
+ function urlToFilename(url) {
67
+ try {
68
+ const urlObj = new URL(url);
69
+ const domainParts = urlObj.hostname.split(".").reverse().reduce((acc, part, index) => {
70
+ if (index === 0) {
71
+ return acc;
72
+ }
73
+ if (acc.length >= 2) {
74
+ return acc;
75
+ }
76
+ if (part === "www") {
77
+ return acc;
78
+ }
79
+ return [part, ...acc];
80
+ }, []);
81
+ const domainString = domainParts.reverse().join("-");
82
+ const pathParts = urlObj.pathname.split("/").filter(Boolean);
83
+ const relevantPathParts = pathParts.slice(-2);
84
+ const pathString = relevantPathParts.map((part) => decodeURIComponent(part)).join("-");
85
+ let filename = [domainString, pathString].filter(Boolean).join("-");
86
+ filename = filename.toLowerCase().replace(/[<>:"/\\|?*\x00-\x1F]/g, "").replace(/[\s.]+/g, "-").replace(/^-+|-+$/g, "");
87
+ return filename || "output";
88
+ } catch {
89
+ return "output";
90
+ }
91
+ }
92
+ const sourcePathToOutputPath = (sourcePath) => {
93
+ return isUrl(sourcePath) ? `${urlToFilename(sourcePath)}.md` : changeFileExtension(sourcePath, "md");
94
+ };
95
+ function getNextAvailableFilePath(filePath) {
96
+ const parsedPath = import_node_path.default.parse(filePath);
97
+ const directory = parsedPath.dir;
98
+ const fullName = parsedPath.base;
99
+ const [firstPart, ...restParts] = fullName.split(".");
100
+ const restName = restParts.length > 0 ? `.${restParts.join(".")}` : "";
101
+ const baseName = firstPart.replace(/_\d+$/, "");
102
+ let counter = 1;
103
+ let nextFilePath = filePath;
104
+ while (import_node_fs.default.existsSync(nextFilePath)) {
105
+ const match = firstPart.match(/_(\d+)$/);
106
+ if (match) {
107
+ counter = Number.parseInt(match[1], 10) + 1;
108
+ }
109
+ const newName = `${baseName}_${counter}${restName}`;
110
+ nextFilePath = import_node_path.default.join(directory, newName);
111
+ counter++;
112
+ }
113
+ return nextFilePath;
114
+ }
115
+ // Annotate the CommonJS export names for ESM import in node:
116
+ 0 && (module.exports = {
117
+ changeFileExtension,
118
+ getNextAvailableFilePath,
119
+ isUrl,
120
+ sourcePathToOutputPath,
121
+ urlToFilename
122
+ });
@@ -1,26 +1,4 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
15
- };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
2
  var import_fastest_levenshtein = require("fastest-levenshtein");
25
3
  var import_vitest = require("vitest");
26
4
  var import_html_to_markdown = require("./html-to-markdown");
@@ -129,18 +107,12 @@ Cell 1 Cell 2`;
129
107
  });
130
108
  });
131
109
  (0, import_vitest.describe)("htmlToMarkdown E2E", () => {
132
- (0, import_vitest.it)("should convert npm README to Markdown ", async () => {
133
- const html2 = await (0, import_fetch.loadHtml)("https://www.npmjs.com/package/webforai");
134
- const markdown = (0, import_html_to_markdown.htmlToMarkdown)(html2);
135
- const original = await import("../README.md?raw");
136
- const d = (0, import_fastest_levenshtein.distance)(markdown, original.default);
137
- (0, import_vitest.expect)(d).lte(200);
138
- });
139
- (0, import_vitest.it)("should convert GitHub README to Markdown ", async () => {
110
+ (0, import_vitest.it)("Converting for good", async () => {
111
+ const html1 = await (0, import_fetch.loadHtml)("https://www.npmjs.com/package/webforai");
112
+ const markdown1 = (0, import_html_to_markdown.htmlToMarkdown)(html1, { linkAsText: true, hideImage: true });
140
113
  const html2 = await (0, import_fetch.loadHtml)("https://github.com/inaridiy/webforai");
141
- const markdown = (0, import_html_to_markdown.htmlToMarkdown)(html2);
142
- const original = await import("../../../README.md?raw");
143
- const d = (0, import_fastest_levenshtein.distance)(markdown, original.default);
144
- (0, import_vitest.expect)(d).lte(200);
114
+ const markdown2 = (0, import_html_to_markdown.htmlToMarkdown)(html2, { linkAsText: true, hideImage: true });
115
+ const d = (0, import_fastest_levenshtein.distance)(markdown1, markdown2);
116
+ (0, import_vitest.expect)(d).lte(2500);
145
117
  });
146
118
  });
package/dist/cjs/index.js CHANGED
@@ -18,6 +18,8 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var src_exports = {};
20
20
  __export(src_exports, {
21
+ DEFAULT_EXTRACT_HAST: () => import_extract_hast.DEFAULT_EXTRACT_HAST,
22
+ PRESET_EXTRACT_HAST: () => import_extract_hast.PRESET_EXTRACT_HAST,
21
23
  htmlToMarkdown: () => import_html_to_markdown.htmlToMarkdown,
22
24
  htmlToMdast: () => import_html_to_mdast.htmlToMdast,
23
25
  mdastSplitter: () => import_md_splitter.mdastSplitter,
@@ -28,8 +30,11 @@ var import_html_to_markdown = require("./html-to-markdown");
28
30
  var import_md_splitter = require("./md-splitter");
29
31
  var import_html_to_mdast = require("./html-to-mdast");
30
32
  var import_mdast_to_markdown = require("./mdast-to-markdown");
33
+ var import_extract_hast = require("./extract-hast/index");
31
34
  // Annotate the CommonJS export names for ESM import in node:
32
35
  0 && (module.exports = {
36
+ DEFAULT_EXTRACT_HAST,
37
+ PRESET_EXTRACT_HAST,
33
38
  htmlToMarkdown,
34
39
  htmlToMdast,
35
40
  mdastSplitter,
@@ -0,0 +1,12 @@
1
+ // src/cli/bin.ts
2
+ import { intro } from "@clack/prompts";
3
+ import { program } from "commander";
4
+ import pc from "picocolors";
5
+ import packageInfo from "../../package.json";
6
+ import { webforaiCommand } from "./commands/handlers/index.js";
7
+ import { LOADERS, MODES } from "./constants.js";
8
+ program.name("webforai").description("CLI tool for ultra-precise HTML to Markdown conversion").version(packageInfo.version, "-v, --version", "output the current version").argument("[source]", "URL or path to process").argument("[outputPath]", "Path to output file or directory").option("--mode <mode>", `Processing mode (${MODES.join(", ")})`).option("--loader <loader>", `Loader to use (${LOADERS.join(", ")})`).option("--baseUrl <baseUrl>", "Base URL for relative links").option("-o, --stdout", "output to stdout").option("-d, --debug", "output extra debugging information").on("option:debug", () => {
9
+ process.env.DEBUG = "true";
10
+ }).action(webforaiCommand);
11
+ intro(pc.inverse(`webforai CLI version ${packageInfo.version}`));
12
+ program.parse();
@@ -0,0 +1,51 @@
1
+ // src/cli/commands/handlers/index.ts
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { outro } from "@clack/prompts";
5
+ import { htmlToMarkdown } from "../../../html-to-markdown.js";
6
+ import { inputOutputPath } from "../../helpers/inputOutputPath.js";
7
+ import { inputSourcePath } from "../../helpers/inputSourcePath.js";
8
+ import { selectExtractMode } from "../../helpers/selectExtractMode.js";
9
+ import { selectLoader } from "../../helpers/selectLoader.js";
10
+ import { isUrl } from "../../utils.js";
11
+ import { loadHtml } from "./loadHtml.js";
12
+ var aiModeOptions = { linkAsText: true, tableAsText: true, hideImage: true };
13
+ var readabilityModeOptions = { linkAsText: false, tableAsText: false, hideImage: false };
14
+ var webforaiCommand = async (initialPath, initialOutputPath, options) => {
15
+ const sourcePath = initialPath ?? await inputSourcePath();
16
+ if (options.debug) {
17
+ console.debug(`sourcePath: ${sourcePath}`);
18
+ }
19
+ const loader = isUrl(sourcePath) ? { type: "web", loader: options.loader ?? await selectLoader() } : { type: "local", loader: null };
20
+ if (options.debug) {
21
+ console.debug(`loader: ${loader}`);
22
+ }
23
+ const outputPath = initialOutputPath ?? await inputOutputPath(sourcePath);
24
+ if (options.debug) {
25
+ console.debug(`outputPath: ${outputPath}`);
26
+ }
27
+ const mode = options.mode ?? await selectExtractMode();
28
+ if (options.debug) {
29
+ console.debug(`mode: ${mode}`);
30
+ }
31
+ const content = await loadHtml(sourcePath, loader);
32
+ if (options.debug) {
33
+ console.debug(`content: ${content}`);
34
+ }
35
+ const markdown = htmlToMarkdown(content, {
36
+ baseUrl: isUrl(sourcePath) ? sourcePath : options.baseUrl,
37
+ ...mode === "ai" ? aiModeOptions : readabilityModeOptions
38
+ });
39
+ if (options.debug) {
40
+ console.debug(`markdown: ${markdown}`);
41
+ }
42
+ const directory = path.dirname(outputPath);
43
+ if (!fs.existsSync(directory)) {
44
+ fs.mkdirSync(directory, { recursive: true });
45
+ }
46
+ fs.writeFileSync(outputPath, markdown);
47
+ outro("Markdown conversion is complete!");
48
+ };
49
+ export {
50
+ webforaiCommand
51
+ };
@@ -0,0 +1,94 @@
1
+ // src/cli/commands/handlers/loadHtml.ts
2
+ import fs from "node:fs/promises";
3
+ import { cancel, spinner as clackSpinner, confirm, spinner } from "@clack/prompts";
4
+ import pc from "picocolors";
5
+ import { $ } from "zx";
6
+ var loadHtml = async (sourcePath, loader) => {
7
+ const loadSpinner = clackSpinner();
8
+ try {
9
+ switch (loader.type) {
10
+ case "local":
11
+ return await loadLocalHtml(sourcePath, loadSpinner);
12
+ case "web":
13
+ switch (loader.loader) {
14
+ case "fetch":
15
+ return await loadFetchHtml(sourcePath, loadSpinner);
16
+ case "playwright":
17
+ return await loadPlaywrightHtml(sourcePath, loadSpinner);
18
+ default:
19
+ throw new Error("Invalid loader");
20
+ }
21
+ default:
22
+ throw new Error("Invalid loader type");
23
+ }
24
+ } catch (error) {
25
+ loadSpinner.stop(pc.red("Content loading failed!"));
26
+ console.error(error);
27
+ process.exit(1);
28
+ }
29
+ };
30
+ var loadLocalHtml = async (sourcePath, loadSpinner) => {
31
+ loadSpinner.start("Retrieving content.");
32
+ try {
33
+ await fs.access(sourcePath);
34
+ } catch {
35
+ throw new Error("The file does not exist");
36
+ }
37
+ const stats = await fs.stat(sourcePath);
38
+ if (!stats.isFile()) {
39
+ throw new Error("The source must be a file");
40
+ }
41
+ const content = await fs.readFile(sourcePath, "utf-8");
42
+ loadSpinner.stop("Content retrieval is complete!");
43
+ return content;
44
+ };
45
+ var loadFetchHtml = async (sourcePath, loadSpinner) => {
46
+ loadSpinner.start("Downloading content.");
47
+ const { loadHtml: loadHtml2 } = await import("../../../loaders/fetch.js");
48
+ const content = await loadHtml2(sourcePath);
49
+ loadSpinner.stop("Content download is complete!");
50
+ return content;
51
+ };
52
+ var loadPlaywrightHtml = async (sourcePath, loadSpinner) => {
53
+ const launchSpinner = clackSpinner();
54
+ launchSpinner.start("Launching playwright.");
55
+ const playwright = await import("playwright");
56
+ let browser;
57
+ try {
58
+ browser = await playwright.chromium.launch();
59
+ launchSpinner.stop("Playwright launched!");
60
+ } catch (error) {
61
+ await handlePlaywrightLaunchError(error);
62
+ browser = await playwright.chromium.launch();
63
+ }
64
+ loadSpinner.start("Loading content.");
65
+ const { loadHtml: loadHtml2 } = await import("../../../loaders/playwright.js");
66
+ const content = await loadHtml2(sourcePath, browser);
67
+ loadSpinner.stop("Content download is complete!");
68
+ await browser.close();
69
+ return content;
70
+ };
71
+ var handlePlaywrightLaunchError = async (error) => {
72
+ if (!error.message.includes("npx playwright install")) {
73
+ throw error;
74
+ }
75
+ const isInstall = await confirm({
76
+ message: "To continue, you will need to download a browser. Do you wish to continue?"
77
+ });
78
+ if (!isInstall) {
79
+ cancel("End of process.");
80
+ process.exit(1);
81
+ }
82
+ const installDepsSpinner = spinner();
83
+ installDepsSpinner.start("Installing browser dependencies.");
84
+ try {
85
+ await $`npx playwright install`;
86
+ installDepsSpinner.stop("Browser dependencies installed!");
87
+ } catch (error2) {
88
+ installDepsSpinner.stop(pc.red("Browser dependencies failed to install!"));
89
+ throw error2;
90
+ }
91
+ };
92
+ export {
93
+ loadHtml
94
+ };
@@ -0,0 +1,9 @@
1
+ // src/cli/constants.ts
2
+ var DEFAULT_PATH = "https://example.com";
3
+ var LOADERS = ["fetch", "playwright"];
4
+ var MODES = ["default", "ai"];
5
+ export {
6
+ DEFAULT_PATH,
7
+ LOADERS,
8
+ MODES
9
+ };
@@ -0,0 +1,11 @@
1
+ // src/cli/helpers/assertContinue.ts
2
+ import { cancel, isCancel } from "@clack/prompts";
3
+ function assertContinue(message, cancelMessage = "Canceled.") {
4
+ if (isCancel(message)) {
5
+ cancel(cancelMessage);
6
+ process.exit(1);
7
+ }
8
+ }
9
+ export {
10
+ assertContinue
11
+ };
@@ -0,0 +1,56 @@
1
+ // src/cli/helpers/inputOutputPath.ts
2
+ import fs from "node:fs";
3
+ import { confirm, text } from "@clack/prompts";
4
+ import { getNextAvailableFilePath, sourcePathToOutputPath } from "../utils.js";
5
+ import { assertContinue } from "./assertContinue.js";
6
+ var inputOutputPath = async (sourcePath) => {
7
+ const outputPath = await text({
8
+ message: "Enter the output file path:",
9
+ placeholder: "output.md",
10
+ initialValue: sourcePathToOutputPath(sourcePath),
11
+ validate: (value) => {
12
+ if (value.trim() === "") {
13
+ return "Output path is required";
14
+ }
15
+ if (fs.existsSync(value) && fs.statSync(value).isDirectory()) {
16
+ return "No directory can be specified.";
17
+ }
18
+ if (!fs.existsSync(value) && value.endsWith("/")) {
19
+ return "No directory can be specified.";
20
+ }
21
+ }
22
+ });
23
+ assertContinue(outputPath);
24
+ if (!fs.existsSync(outputPath)) {
25
+ return outputPath;
26
+ }
27
+ const isOutputFileOverwrite = await confirm({
28
+ message: "The file already exists. Overwrite?",
29
+ initialValue: false
30
+ });
31
+ assertContinue(isOutputFileOverwrite);
32
+ if (isOutputFileOverwrite) {
33
+ return outputPath;
34
+ }
35
+ const escapedOutputPath = await text({
36
+ message: "Enter the output file path:",
37
+ placeholder: "output.md",
38
+ initialValue: getNextAvailableFilePath(outputPath),
39
+ validate: (value) => {
40
+ if (value.trim() === "") {
41
+ return "Output path is required";
42
+ }
43
+ if (fs.existsSync(value)) {
44
+ return "The file already exists";
45
+ }
46
+ if (!fs.existsSync(value) && value.endsWith("/")) {
47
+ return "No directory can be specified.";
48
+ }
49
+ }
50
+ });
51
+ assertContinue(escapedOutputPath);
52
+ return escapedOutputPath;
53
+ };
54
+ export {
55
+ inputOutputPath
56
+ };
@@ -0,0 +1,31 @@
1
+ // src/cli/helpers/inputSourcePath.ts
2
+ import fs from "node:fs";
3
+ import { text } from "@clack/prompts";
4
+ import { DEFAULT_PATH } from "../constants.js";
5
+ import { isUrl } from "../utils.js";
6
+ import { assertContinue } from "./assertContinue.js";
7
+ var inputSourcePath = async () => {
8
+ const result = await text({
9
+ message: "Enter the URL or html path to be converted to markdown:",
10
+ placeholder: DEFAULT_PATH,
11
+ initialValue: "",
12
+ validate: (value) => {
13
+ if (value.trim() === "") {
14
+ return "Source is required";
15
+ }
16
+ if (!isUrl(value)) {
17
+ if (!fs.existsSync(value)) {
18
+ return "It appears that you are specifying a local file, but the file cannot be found. hint: when specifying a url, start with http or https.";
19
+ }
20
+ if (fs.statSync(value).isDirectory()) {
21
+ return "You are specifying a local file, but you cannot specify a directory. hint: when specifying a url, start with http or https.";
22
+ }
23
+ }
24
+ }
25
+ });
26
+ assertContinue(result);
27
+ return result;
28
+ };
29
+ export {
30
+ inputSourcePath
31
+ };
@@ -0,0 +1,16 @@
1
+ // src/cli/helpers/selectExtractMode.ts
2
+ import { select } from "@clack/prompts";
3
+ import { MODES } from "../constants.js";
4
+ import { assertContinue } from "./assertContinue.js";
5
+ var selectExtractMode = async () => {
6
+ const result = await select({
7
+ message: "Select processing mode:",
8
+ options: MODES.map((mode) => ({ value: mode, label: mode })),
9
+ initialValue: MODES[0]
10
+ });
11
+ assertContinue(result);
12
+ return result;
13
+ };
14
+ export {
15
+ selectExtractMode
16
+ };
@@ -0,0 +1,21 @@
1
+ // src/cli/helpers/selectLoader.ts
2
+ import { select } from "@clack/prompts";
3
+ import { LOADERS } from "../constants.js";
4
+ import { assertContinue } from "./assertContinue.js";
5
+ var loadersHint = {
6
+ fetch: "Fetch HTML content from the given URL",
7
+ playwright: "Retrieve HTML content after rendering using Playwright; Playwright must be installed in advance.",
8
+ puppeteer: "Retrieve HTML content after rendering using Puppeteer; Puppeteer must be installed in advance."
9
+ };
10
+ var selectLoader = async () => {
11
+ const result = await select({
12
+ message: "Select loader:",
13
+ initialValue: "fetch",
14
+ options: LOADERS.map((mode) => ({ value: mode, label: mode, hint: loadersHint[mode] || "" }))
15
+ });
16
+ assertContinue(result);
17
+ return result;
18
+ };
19
+ export {
20
+ selectLoader
21
+ };
@@ -0,0 +1,85 @@
1
+ // src/cli/utils.ts
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ var isUrl = (maybeUrl) => {
5
+ try {
6
+ new URL(maybeUrl);
7
+ return true;
8
+ } catch {
9
+ return false;
10
+ }
11
+ };
12
+ function changeFileExtension(filePath, newExtension) {
13
+ const parsedPath = filePath.split("/");
14
+ const fileName = parsedPath[parsedPath.length - 1];
15
+ const formattedNewExtension = newExtension.startsWith(".") ? newExtension : `.${newExtension}`;
16
+ if (fileName.startsWith(".")) {
17
+ const parts = fileName.split(".");
18
+ if (parts.length === 2) {
19
+ return parsedPath.slice(0, -1).concat(`${fileName}${formattedNewExtension}`).join("/");
20
+ }
21
+ parts[parts.length - 1] = newExtension.replace(/^\./, "");
22
+ return parsedPath.slice(0, -1).concat(parts.join(".")).join("/");
23
+ }
24
+ const lastDotIndex = fileName.lastIndexOf(".");
25
+ const baseName = lastDotIndex !== -1 ? fileName.slice(0, lastDotIndex) : fileName;
26
+ const newFileName = `${baseName}${formattedNewExtension}`;
27
+ parsedPath[parsedPath.length - 1] = newFileName;
28
+ return parsedPath.join("/");
29
+ }
30
+ function urlToFilename(url) {
31
+ try {
32
+ const urlObj = new URL(url);
33
+ const domainParts = urlObj.hostname.split(".").reverse().reduce((acc, part, index) => {
34
+ if (index === 0) {
35
+ return acc;
36
+ }
37
+ if (acc.length >= 2) {
38
+ return acc;
39
+ }
40
+ if (part === "www") {
41
+ return acc;
42
+ }
43
+ return [part, ...acc];
44
+ }, []);
45
+ const domainString = domainParts.reverse().join("-");
46
+ const pathParts = urlObj.pathname.split("/").filter(Boolean);
47
+ const relevantPathParts = pathParts.slice(-2);
48
+ const pathString = relevantPathParts.map((part) => decodeURIComponent(part)).join("-");
49
+ let filename = [domainString, pathString].filter(Boolean).join("-");
50
+ filename = filename.toLowerCase().replace(/[<>:"/\\|?*\x00-\x1F]/g, "").replace(/[\s.]+/g, "-").replace(/^-+|-+$/g, "");
51
+ return filename || "output";
52
+ } catch {
53
+ return "output";
54
+ }
55
+ }
56
+ var sourcePathToOutputPath = (sourcePath) => {
57
+ return isUrl(sourcePath) ? `${urlToFilename(sourcePath)}.md` : changeFileExtension(sourcePath, "md");
58
+ };
59
+ function getNextAvailableFilePath(filePath) {
60
+ const parsedPath = path.parse(filePath);
61
+ const directory = parsedPath.dir;
62
+ const fullName = parsedPath.base;
63
+ const [firstPart, ...restParts] = fullName.split(".");
64
+ const restName = restParts.length > 0 ? `.${restParts.join(".")}` : "";
65
+ const baseName = firstPart.replace(/_\d+$/, "");
66
+ let counter = 1;
67
+ let nextFilePath = filePath;
68
+ while (fs.existsSync(nextFilePath)) {
69
+ const match = firstPart.match(/_(\d+)$/);
70
+ if (match) {
71
+ counter = Number.parseInt(match[1], 10) + 1;
72
+ }
73
+ const newName = `${baseName}_${counter}${restName}`;
74
+ nextFilePath = path.join(directory, newName);
75
+ counter++;
76
+ }
77
+ return nextFilePath;
78
+ }
79
+ export {
80
+ changeFileExtension,
81
+ getNextAvailableFilePath,
82
+ isUrl,
83
+ sourcePathToOutputPath,
84
+ urlToFilename
85
+ };
@@ -107,18 +107,12 @@ describe("htmlToMarkdown", () => {
107
107
  });
108
108
  });
109
109
  describe("htmlToMarkdown E2E", () => {
110
- it("should convert npm README to Markdown ", async () => {
111
- const html2 = await loadHtml("https://www.npmjs.com/package/webforai");
112
- const markdown = htmlToMarkdown(html2);
113
- const original = await import("../README.md?raw");
114
- const d = distance(markdown, original.default);
115
- expect(d).lte(200);
116
- });
117
- it("should convert GitHub README to Markdown ", async () => {
110
+ it("Converting for good", async () => {
111
+ const html1 = await loadHtml("https://www.npmjs.com/package/webforai");
112
+ const markdown1 = htmlToMarkdown(html1, { linkAsText: true, hideImage: true });
118
113
  const html2 = await loadHtml("https://github.com/inaridiy/webforai");
119
- const markdown = htmlToMarkdown(html2);
120
- const original = await import("../../../README.md?raw");
121
- const d = distance(markdown, original.default);
122
- expect(d).lte(200);
114
+ const markdown2 = htmlToMarkdown(html2, { linkAsText: true, hideImage: true });
115
+ const d = distance(markdown1, markdown2);
116
+ expect(d).lte(2500);
123
117
  });
124
118
  });
package/dist/index.js CHANGED
@@ -3,7 +3,10 @@ import { htmlToMarkdown } from "./html-to-markdown.js";
3
3
  import { mdastSplitter } from "./md-splitter.js";
4
4
  import { htmlToMdast } from "./html-to-mdast.js";
5
5
  import { mdastToMarkdown } from "./mdast-to-markdown.js";
6
+ import { PRESET_EXTRACT_HAST, DEFAULT_EXTRACT_HAST } from "./extract-hast/index.js";
6
7
  export {
8
+ DEFAULT_EXTRACT_HAST,
9
+ PRESET_EXTRACT_HAST,
7
10
  htmlToMarkdown,
8
11
  htmlToMdast,
9
12
  mdastSplitter,
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","sourceRoot":"","sources":["../../../src/cli/bin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5B,OAAO,WAAW,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAE7C,OAAO;KACL,IAAI,CAAC,UAAU,CAAC;KAChB,WAAW,CAAC,wDAAwD,CAAC;KACrE,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,eAAe,EAAE,4BAA4B,CAAC;KAC3E,QAAQ,CAAC,UAAU,EAAE,wBAAwB,CAAC;KAC9C,QAAQ,CAAC,cAAc,EAAE,kCAAkC,CAAC;KAC5D,MAAM,CAAC,eAAe,EAAE,oBAAoB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;KAChE,MAAM,CAAC,mBAAmB,EAAE,kBAAkB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;KACpE,MAAM,CAAC,qBAAqB,EAAE,6BAA6B,CAAC;KAC5D,MAAM,CAAC,cAAc,EAAE,kBAAkB,CAAC;KAC1C,MAAM,CAAC,aAAa,EAAE,oCAAoC,CAAC;KAC3D,EAAE,CAAC,cAAc,EAAE,GAAG,EAAE;IACxB,OAAO,CAAC,GAAG,CAAC,KAAK,GAAG,MAAM,CAAC;AAC5B,CAAC,CAAC;KACD,MAAM,CAAC,eAAe,CAAC,CAAC;AAE1B,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,wBAAwB,WAAW,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;AAEjE,OAAO,CAAC,KAAK,EAAE,CAAC"}
@@ -0,0 +1,13 @@
1
+ export type LoaderOptions = {
2
+ type: "web";
3
+ loader: "playwright" | "pw" | "fetch" | string;
4
+ } | {
5
+ type: "local";
6
+ loader: null;
7
+ };
8
+ export declare const webforaiCommand: (initialPath: string, initialOutputPath: string, options: {
9
+ mode?: string;
10
+ loader: string;
11
+ debug?: boolean;
12
+ baseUrl?: string;
13
+ }) => Promise<void>;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/cli/commands/handlers/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE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