@kklab/json2markdown 0.0.7 → 0.0.9

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/README.md CHANGED
@@ -13,10 +13,18 @@ import { Converter } from '@kklab/json2markdown';
13
13
 
14
14
  const output = Converter.toMarkdown({
15
15
  'Hello, World!': 'It works!',
16
+ }, {
17
+ onConvert: (element) => {
18
+ if (element.tag === 'heading') {
19
+ element.level += 1;
20
+ }
21
+ return element;
22
+ },
16
23
  });
24
+
17
25
  console.log(output);
18
26
  // Output:
19
- // # Hello, World!\n\nIt works!\n\n
27
+ // ## Hello, World!\n\nIt works!\n\n
20
28
  ```
21
29
 
22
30
  ### Using with UMD Modules
@@ -28,10 +36,18 @@ Include the UMD script in your HTML file and use it:
28
36
  <script>
29
37
  const output = window.JSON2MD.Converter.toMarkdown({
30
38
  'Hello, World!': 'It works!',
39
+ }, {
40
+ onConvert: (element) => {
41
+ if (element.tag === 'heading') {
42
+ element.level += 1;
43
+ }
44
+ return element;
45
+ },
31
46
  });
47
+
32
48
  console.log(JSON.stringify(output));
33
49
  // Output:
34
- // # Hello, World!\n\nIt works!\n\n
50
+ // ## Hello, World!\n\nIt works!\n\n
35
51
  </script>
36
52
  ```
37
53
 
@@ -0,0 +1,9 @@
1
+ declare const Tags: {
2
+ readonly BR: "br";
3
+ readonly HEADING: "heading";
4
+ readonly LI: "li";
5
+ readonly P: "p";
6
+ readonly TD: "td";
7
+ readonly TR: "tr";
8
+ };
9
+ export default Tags;
@@ -0,0 +1,2 @@
1
+ import { default as Tags } from './Tags';
2
+ export { Tags, };
@@ -1,26 +1,25 @@
1
- import { MarkdownSchema } from '../types';
1
+ import { Element } from '../types';
2
+ interface ConverterOptions {
3
+ onConvert?: (element: Element) => Element;
4
+ }
2
5
  declare class Converter {
6
+ private elements;
7
+ private onConvert;
8
+ constructor(data: unknown, options?: ConverterOptions);
3
9
  /**
4
- * Converts a given data object into a Markdown string.
5
- *
6
- * This method processes the data and identifies headings, unordered lists,
7
- * and paragraph elements, formatting them according to Markdown syntax.
8
- *
9
- * @param data - A record representing the input data to be converted.
10
- * @returns A string formatted in Markdown based on the input data.
10
+ * Converts the provided data into Markdown format.
11
11
  */
12
- static toMarkdown(data: Record<string, unknown>): string;
12
+ static toMarkdown(data: unknown, options?: ConverterOptions): string;
13
13
  /**
14
- * Constructs a Markdown schema from a given data object.
15
- *
16
- * This method recursively traverses the data object to build a schema that
17
- * identifies headings, lists, and paragraphs, which will later be converted to Markdown.
18
- *
19
- * @param data - A record representing the input data.
20
- * @param level - The current heading level (default is 1).
21
- * @param schema - An array that accumulates the schema entries (default is an empty array).
22
- * @returns An array representing the schema for the Markdown conversion.
14
+ * Converts the provided data into Markdown format.
23
15
  */
24
- static toMarkdownSchema(data: Record<string, unknown>, level?: number, schema?: MarkdownSchema[]): MarkdownSchema[];
16
+ toMarkdown(): string;
17
+ getElements(): Element[];
18
+ private pushElement;
19
+ private convert;
20
+ private convertFromArray;
21
+ private convertFromObject;
22
+ private convertFromPrimitive;
23
+ private formatValue;
25
24
  }
26
25
  export default Converter;
package/dist/index.js CHANGED
@@ -1,69 +1,136 @@
1
- const c = /^(a|an|and|as|at|but|by|for|if|in|is|nor|of|on|or|the|to|with)$/i, f = (u) => u.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/[_-]/g, " ").split(" ").map((r, i) => r === r.toUpperCase() ? r : i === 0 || !c.test(r) ? `${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()}` : r.toLowerCase()).join(" ");
2
- class s {
1
+ var m = Object.defineProperty;
2
+ var l = (o, t, e) => t in o ? m(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e;
3
+ var s = (o, t, e) => (l(o, typeof t != "symbol" ? t + "" : t, e), e);
4
+ const r = {
5
+ BR: "br",
6
+ HEADING: "heading",
7
+ LI: "li",
8
+ P: "p",
9
+ TD: "td",
10
+ TR: "tr"
11
+ };
12
+ class a {
13
+ constructor(t, e = {}) {
14
+ s(this, "elements", []);
15
+ s(this, "onConvert");
16
+ this.onConvert = e.onConvert ?? ((n) => n), this.convert(t);
17
+ }
3
18
  /**
4
- * Converts a given data object into a Markdown string.
5
- *
6
- * This method processes the data and identifies headings, unordered lists,
7
- * and paragraph elements, formatting them according to Markdown syntax.
8
- *
9
- * @param data - A record representing the input data to be converted.
10
- * @returns A string formatted in Markdown based on the input data.
19
+ * Converts the provided data into Markdown format.
11
20
  */
12
- static toMarkdown(r) {
13
- const i = Array.from({ length: 6 }, (t, a) => `h${a + 1}`);
14
- return s.toMarkdownSchema(r).map((t) => {
15
- const a = i.findIndex((o) => t[o]);
16
- return a !== -1 ? `${"#".repeat(a + 1)} ${f(t[i[a]])}
17
-
18
- ` : t.ul ? `${t.ul.map((o) => `- ${o}
19
- `).join("")}
20
- ` : typeof t.p == "boolean" ? `${f(String(t.p))}
21
+ static toMarkdown(t, e = {}) {
22
+ return new a(t, e).toMarkdown();
23
+ }
24
+ /**
25
+ * Converts the provided data into Markdown format.
26
+ */
27
+ toMarkdown() {
28
+ return this.elements.map((t) => {
29
+ switch (t.tag) {
30
+ case r.BR:
31
+ return `
32
+ `;
33
+ case r.HEADING:
34
+ return `${"#".repeat(Math.max(1, Math.min(6, t.level)))} ${t.value}
21
35
 
22
- ` : `${t.p}
36
+ `;
37
+ case r.LI:
38
+ return `${" ".repeat(t.indent)}- ${t.value}
39
+ `;
40
+ case r.P:
41
+ return `${t.value}
23
42
 
24
43
  `;
44
+ case r.TD:
45
+ return `| ${t.values.join(" | ")} |
46
+ `;
47
+ case r.TR:
48
+ return `| ${t.values.map((e) => e).join(" | ")} |
49
+ ${t.values.map(() => "| ---").join(" ")} |
50
+ `;
51
+ default:
52
+ return "";
53
+ }
25
54
  }).join("");
26
55
  }
27
- /**
28
- * Constructs a Markdown schema from a given data object.
29
- *
30
- * This method recursively traverses the data object to build a schema that
31
- * identifies headings, lists, and paragraphs, which will later be converted to Markdown.
32
- *
33
- * @param data - A record representing the input data.
34
- * @param level - The current heading level (default is 1).
35
- * @param schema - An array that accumulates the schema entries (default is an empty array).
36
- * @returns An array representing the schema for the Markdown conversion.
37
- */
38
- static toMarkdownSchema(r, i = 1, t = []) {
39
- if (!r)
40
- return [];
41
- const a = `h${Math.min(i, 6)}`;
42
- for (let [o, n] of Object.entries(r))
43
- if (!o.startsWith("_")) {
44
- if (o = o.trim(), typeof n == "string" && (n = n.trim().replaceAll("\\n", `
45
- `)), t.push({ [a]: o }), Array.isArray(n)) {
46
- const [p] = n;
47
- if (Array.isArray(p) && p.length > 0) {
48
- t.push({ ul: n.map((e) => JSON.stringify(e)) });
49
- continue;
50
- }
51
- if (typeof p == "object") {
52
- s.toMarkdownSchema(p, i + 1, t);
53
- continue;
54
- }
55
- t.push({ ul: n.map((e) => typeof e == "string" ? e : JSON.stringify(e)) });
56
- continue;
57
- }
58
- if (typeof n == "object") {
59
- s.toMarkdownSchema(n, i + 1, t);
56
+ getElements() {
57
+ return this.elements;
58
+ }
59
+ pushElement(t) {
60
+ return this.elements.push(this.onConvert(t)), this;
61
+ }
62
+ convert(t) {
63
+ if (t) {
64
+ if (Array.isArray(t)) {
65
+ this.convertFromArray(t);
66
+ return;
67
+ }
68
+ if (typeof t == "object") {
69
+ this.convertFromObject(t);
70
+ return;
71
+ }
72
+ this.convertFromPrimitive(t);
73
+ }
74
+ }
75
+ convertFromArray(t, e = 0) {
76
+ for (const n of t) {
77
+ if (Array.isArray(n)) {
78
+ this.convertFromArray(n, e + 1);
79
+ continue;
80
+ }
81
+ this.pushElement({
82
+ tag: r.LI,
83
+ value: this.formatValue(n),
84
+ indent: e
85
+ });
86
+ }
87
+ return this;
88
+ }
89
+ convertFromObject(t, e = 0) {
90
+ for (const [n, i] of Object.entries(t)) {
91
+ if (this.pushElement({
92
+ tag: r.HEADING,
93
+ value: n,
94
+ level: e + 1
95
+ }), Array.isArray(i)) {
96
+ const [u] = i;
97
+ if (typeof u == "object") {
98
+ this.pushElement({
99
+ tag: r.TR,
100
+ values: Object.keys(u)
101
+ }), i.forEach((c) => {
102
+ this.pushElement({
103
+ tag: r.TD,
104
+ values: Object.values(c).map((h) => this.formatValue(h))
105
+ });
106
+ }), this.pushElement({
107
+ tag: r.BR
108
+ });
60
109
  continue;
61
110
  }
62
- t.push({ p: n });
111
+ this.convertFromArray(i), this.pushElement({
112
+ tag: r.BR
113
+ });
114
+ continue;
63
115
  }
64
- return t;
116
+ if (typeof i == "object") {
117
+ this.convertFromObject(i, e + 1);
118
+ continue;
119
+ }
120
+ this.convertFromPrimitive(i);
121
+ }
122
+ return this;
123
+ }
124
+ convertFromPrimitive(t) {
125
+ return this.pushElement({
126
+ tag: r.P,
127
+ value: this.formatValue(t)
128
+ });
129
+ }
130
+ formatValue(t) {
131
+ return Array.isArray(t) ? t.map((e) => this.formatValue(e)).join(", ") : typeof t == "object" ? JSON.stringify(t) : String(t).trim();
65
132
  }
66
133
  }
67
134
  export {
68
- s as Converter
135
+ a as Converter
69
136
  };
package/dist/index.umd.js CHANGED
@@ -1,10 +1,10 @@
1
- (function(a,f){typeof exports=="object"&&typeof module<"u"?f(exports):typeof define=="function"&&define.amd?define(["exports"],f):(a=typeof globalThis<"u"?globalThis:a||self,f(a.JSON2MD={}))})(this,function(a){"use strict";const f=/^(a|an|and|as|at|but|by|for|if|in|is|nor|of|on|or|the|to|with)$/i,c=y=>y.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[_-]/g," ").split(" ").map((n,i)=>n===n.toUpperCase()?n:i===0||!f.test(n)?`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()}`:n.toLowerCase()).join(" ");class s{static toMarkdown(n){const i=Array.from({length:6},(t,o)=>`h${o+1}`);return s.toMarkdownSchema(n).map(t=>{const o=i.findIndex(r=>t[r]);return o!==-1?`${"#".repeat(o+1)} ${c(t[i[o]])}
1
+ (function(n,e){typeof exports=="object"&&typeof module<"u"?e(exports):typeof define=="function"&&define.amd?define(["exports"],e):(n=typeof globalThis<"u"?globalThis:n||self,e(n.JSON2MD={}))})(this,function(n){"use strict";var l=Object.defineProperty;var h=(n,e,i)=>e in n?l(n,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):n[e]=i;var u=(n,e,i)=>(h(n,typeof e!="symbol"?e+"":e,i),i);const e={BR:"br",HEADING:"heading",LI:"li",P:"p",TD:"td",TR:"tr"};class i{constructor(t,r={}){u(this,"elements",[]);u(this,"onConvert");this.onConvert=r.onConvert??(o=>o),this.convert(t)}static toMarkdown(t,r={}){return new i(t,r).toMarkdown()}toMarkdown(){return this.elements.map(t=>{switch(t.tag){case e.BR:return`
2
+ `;case e.HEADING:return`${"#".repeat(Math.max(1,Math.min(6,t.level)))} ${t.value}
2
3
 
3
- `:t.ul?`${t.ul.map(r=>`- ${r}
4
- `).join("")}
5
- `:typeof t.p=="boolean"?`${c(String(t.p))}
4
+ `;case e.LI:return`${" ".repeat(t.indent)}- ${t.value}
5
+ `;case e.P:return`${t.value}
6
6
 
7
- `:`${t.p}
8
-
9
- `}).join("")}static toMarkdownSchema(n,i=1,t=[]){if(!n)return[];const o=`h${Math.min(i,6)}`;for(let[r,e]of Object.entries(n))if(!r.startsWith("_")){if(r=r.trim(),typeof e=="string"&&(e=e.trim().replaceAll("\\n",`
10
- `)),t.push({[o]:r}),Array.isArray(e)){const[u]=e;if(Array.isArray(u)&&u.length>0){t.push({ul:e.map(p=>JSON.stringify(p))});continue}if(typeof u=="object"){s.toMarkdownSchema(u,i+1,t);continue}t.push({ul:e.map(p=>typeof p=="string"?p:JSON.stringify(p))});continue}if(typeof e=="object"){s.toMarkdownSchema(e,i+1,t);continue}t.push({p:e})}return t}}a.Converter=s,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});
7
+ `;case e.TD:return`| ${t.values.join(" | ")} |
8
+ `;case e.TR:return`| ${t.values.map(r=>r).join(" | ")} |
9
+ ${t.values.map(()=>"| ---").join(" ")} |
10
+ `;default:return""}}).join("")}getElements(){return this.elements}pushElement(t){return this.elements.push(this.onConvert(t)),this}convert(t){if(t){if(Array.isArray(t)){this.convertFromArray(t);return}if(typeof t=="object"){this.convertFromObject(t);return}this.convertFromPrimitive(t)}}convertFromArray(t,r=0){for(const o of t){if(Array.isArray(o)){this.convertFromArray(o,r+1);continue}this.pushElement({tag:e.LI,value:this.formatValue(o),indent:r})}return this}convertFromObject(t,r=0){for(const[o,s]of Object.entries(t)){if(this.pushElement({tag:e.HEADING,value:o,level:r+1}),Array.isArray(s)){const[a]=s;if(typeof a=="object"){this.pushElement({tag:e.TR,values:Object.keys(a)}),s.forEach(c=>{this.pushElement({tag:e.TD,values:Object.values(c).map(f=>this.formatValue(f))})}),this.pushElement({tag:e.BR});continue}this.convertFromArray(s),this.pushElement({tag:e.BR});continue}if(typeof s=="object"){this.convertFromObject(s,r+1);continue}this.convertFromPrimitive(s)}return this}convertFromPrimitive(t){return this.pushElement({tag:e.P,value:this.formatValue(t)})}formatValue(t){return Array.isArray(t)?t.map(r=>this.formatValue(r)).join(", "):typeof t=="object"?JSON.stringify(t):String(t).trim()}}n.Converter=i,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})});
@@ -0,0 +1,29 @@
1
+ import { default as Tags } from '../constants/Tags';
2
+ import { default as HeadingLevel } from './HeadingLevel';
3
+ export interface BreakElement {
4
+ tag: typeof Tags.BR;
5
+ }
6
+ export interface HeadingElement {
7
+ tag: typeof Tags.HEADING;
8
+ value: string;
9
+ level: HeadingLevel;
10
+ }
11
+ export interface ListItemElement {
12
+ tag: typeof Tags.LI;
13
+ value: string;
14
+ indent: number;
15
+ }
16
+ export interface ParagraphElement {
17
+ tag: typeof Tags.P;
18
+ value: string;
19
+ }
20
+ export interface TableDataElement {
21
+ tag: typeof Tags.TD;
22
+ values: string[];
23
+ }
24
+ export interface TableRowElement {
25
+ tag: typeof Tags.TR;
26
+ values: string[];
27
+ }
28
+ type Element = BreakElement | HeadingElement | ListItemElement | ParagraphElement | TableDataElement | TableRowElement;
29
+ export default Element;
@@ -0,0 +1,2 @@
1
+ type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
2
+ export default HeadingLevel;
@@ -1,2 +1,3 @@
1
- import { default as MarkdownSchema } from './MarkdownSchema';
2
- export type { MarkdownSchema, };
1
+ import { default as Element } from './Element';
2
+ import { default as HeadingLevel } from './HeadingLevel';
3
+ export type { Element, HeadingLevel, };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kklab/json2markdown",
3
3
  "private": false,
4
- "version": "0.0.7",
4
+ "version": "0.0.9",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "scripts": {
@@ -11,11 +11,10 @@
11
11
  "lint": "eslint .",
12
12
  "test": "vitest"
13
13
  },
14
- "dependencies": {
15
- "@kklab/stryle": "^0.0.1"
16
- },
17
14
  "devDependencies": {
18
15
  "@eslint/js": "^9.11.0",
16
+ "@kklab/stryle": "^0.0.2",
17
+ "@stylistic/eslint-plugin": "^2.9.0",
19
18
  "@types/eslint__js": "^8.42.3",
20
19
  "@types/node": "^22.5.5",
21
20
  "eslint": "^9.11.0",
@@ -1,12 +0,0 @@
1
- interface MarkdownSchema {
2
- [key: string]: string | string[] | boolean | undefined;
3
- h1?: string;
4
- h2?: string;
5
- h3?: string;
6
- h4?: string;
7
- h5?: string;
8
- h6?: string;
9
- p?: string | boolean;
10
- ul?: string[];
11
- }
12
- export default MarkdownSchema;
@@ -1,2 +0,0 @@
1
- import { default as toTitleCase } from './toTitleCase';
2
- export { toTitleCase, };
@@ -1,2 +0,0 @@
1
- declare const toTitleCase: (str: string) => string;
2
- export default toTitleCase;