sommark 4.1.0 → 4.3.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.
@@ -0,0 +1,443 @@
1
+ import { VirtualFS } from "./helpers/virtual-fs.js";
2
+ import { FetchFS } from "./helpers/fetch-fs.js";
3
+ import lexer from "./core/lexer.js";
4
+ import parser from "./core/parser.js";
5
+ import transpiler from "./core/transpiler.js";
6
+ import Mapper from "./mappers/mapper.js";
7
+ import { registerSharedOutputs } from "./mappers/shared/index.js";
8
+ import HTML from "./mappers/languages/html.js";
9
+ import MARKDOWN from "./mappers/languages/markdown.js";
10
+ import MDX from "./mappers/languages/mdx.js";
11
+ import Json from "./mappers/languages/json.js";
12
+ import Jsonc from "./mappers/languages/jsonc.js";
13
+ import XML from "./mappers/languages/xml.js";
14
+ import TEXT from "./mappers/languages/text.js";
15
+ import { runtimeError } from "./core/errors.js";
16
+ import FORMATS, { textFormat, htmlFormat, markdownFormat, mdxFormat, jsonFormat, jsoncFormat, xmlFormat } from "./core/formats.js";
17
+ import TOKEN_TYPES from "./core/tokenTypes.js";
18
+ import * as labels from "./core/labels.js";
19
+ import { resolveModules } from "./core/modules.js";
20
+ import { validateAST } from "./core/validator.js";
21
+ import { enableColor } from "./helpers/colorize.js";
22
+ import { safeArg } from "./helpers/utils.js";
23
+ import { startSpinner, stopSpinner } from "./helpers/spinner.js";
24
+ import { preprocessRuntimeLogic } from "./core/helpers/preprocessor.js";
25
+
26
+ let defaultFs = null;
27
+ let defaultCwd = "/";
28
+ let defaultFindAndLoadConfig = async () => ({});
29
+
30
+ const isURL = (s) => typeof s === "string" && /^https?:\/\//.test(s);
31
+
32
+ export function setDefaultCwd(cwd) {
33
+ defaultCwd = cwd;
34
+ }
35
+
36
+ export function setDefaultFs(fs) {
37
+ defaultFs = fs;
38
+ Evaluator.setDefaultFs(fs);
39
+ }
40
+
41
+ export function setDefaultFindAndLoadConfig(fn) {
42
+ defaultFindAndLoadConfig = fn;
43
+ }
44
+
45
+ /**
46
+ * The SomMark Core Engine.
47
+ * Processes SomMark code and turns it into different formats.
48
+ */
49
+ class SomMark {
50
+ static Mapper = Mapper;
51
+ /**
52
+ * Creates a new SomMark engine.
53
+ *
54
+ * @param {Object} options - Settings for the engine.
55
+ * @param {string} options.src - The SomMark code to process.
56
+ * @param {string} options.format - The final format you want (like 'html' or 'markdown').
57
+ * @param {Mapper|null} [options.mapperFile=null] - Custom rules for formatting.
58
+ * @param {string} [options.filename="anonymous"] - The name of the file, used for errors and settings.
59
+ * @param {boolean} [options.removeComments=true] - If true, comments will be removed from the final code.
60
+ * @param {Object} [options.placeholders={}] - Values to use for p{placeholders}.
61
+ * @param {Array<string>} [options.customProps=[]] - Allowed custom HTML attributes.
62
+ * @param {Object} [options.importAliases={}] - Custom path aliases for modules.
63
+ * @param {Array<string>} [options.importStack=[]] - Tracking for circular dependencies.
64
+ * @param {string} [options.baseDir=null] - The base directory for resolving relative paths.
65
+ */
66
+ constructor(options = {}) {
67
+ const { src, ast = null, format, mapperFile = null, filename = "anonymous", removeComments = true, placeholders = {}, customProps = [], fallbackTarget = "style", outputValidator = null, importAliases = {}, importStack = [], baseDir = null, moduleCache = null, showSpinner = true, security = {}, generateRuntimeOutput = false, hideRuntimeOutput = false, moduleIdentityToken = null } = options;
68
+ this.rawSettings = options;
69
+ this.src = src;
70
+ this.ast = ast;
71
+ this.targetFormat = format;
72
+ this.mapperFile = mapperFile;
73
+ this.filename = filename;
74
+ this.removeComments = removeComments;
75
+ this.placeholders = placeholders;
76
+ this.customProps = customProps;
77
+ this.generateRuntimeOutput = generateRuntimeOutput;
78
+ this.hideRuntimeOutput = hideRuntimeOutput;
79
+ this.cwd = options.baseDir || (options.files ? "/" : defaultCwd);
80
+ this.fs = options.fs
81
+ || (options.files ? new VirtualFS(options.files) : null)
82
+ || (isURL(options.baseDir) ? new FetchFS(options.baseDir) : defaultFs);
83
+
84
+ // Validate fallbackTarget
85
+ const VALID_FALLBACK_TARGETS = new Set(["style", "class", false]);
86
+ if (!VALID_FALLBACK_TARGETS.has(fallbackTarget)) {
87
+ runtimeError([
88
+ `{line}<$red:Invalid fallbackTarget$>: <$green:'${fallbackTarget}'$> <$yellow:is not a valid value.$>`,
89
+ `{N}<$yellow:Use$> <$green:'style'$><$yellow:,$> <$green:'class'$><$yellow:, or$> <$green:false$><$yellow:.$>{line}`
90
+ ]);
91
+ }
92
+ this.fallbackTarget = fallbackTarget;
93
+ this.outputValidator = outputValidator;
94
+ this.importAliases = importAliases;
95
+ this.importStack = importStack;
96
+ this.baseDir = baseDir;
97
+ this.moduleCache = moduleCache || new Map();
98
+ this.showSpinner = showSpinner;
99
+ this.security = {
100
+ allowRaw: security?.allowRaw !== false,
101
+ maxDepth: security?.maxDepth ?? 5,
102
+ timeout: security?.timeout ?? 5000,
103
+ sanitize: typeof security?.sanitize === "function" ? security.sanitize : null,
104
+ allowFetch: security?.allowFetch !== false,
105
+ allowHttp: security?.allowHttp === true,
106
+ allowedOrigins: Array.isArray(security?.allowedOrigins) ? security.allowedOrigins.map(o => o.toLowerCase()) : null,
107
+ allowedExtensions: Array.isArray(security?.allowedExtensions) ? security.allowedExtensions.map(e => e.toLowerCase()) : null
108
+ };
109
+ this.warnings = [];
110
+ this._prepared = false;
111
+
112
+ // Create a random token to safely wrap data
113
+ this.moduleIdentityToken = moduleIdentityToken || `$_SM_MOD_${Math.random().toString(36).slice(2, 7)}_$`;
114
+
115
+ this.Mapper = Mapper;
116
+
117
+ const mapperFiles = { [htmlFormat]: HTML, [markdownFormat]: MARKDOWN, [mdxFormat]: MDX, [jsonFormat]: Json, [jsoncFormat]: Jsonc, [xmlFormat]: XML, [textFormat]: TEXT };
118
+
119
+ if (!this.mapperFile && this.targetFormat) {
120
+ const DefaultMapper = mapperFiles[this.targetFormat];
121
+ if (DefaultMapper) {
122
+ this.mapperFile = DefaultMapper.clone();
123
+ }
124
+ } else if (this.mapperFile) {
125
+ this.mapperFile = this.mapperFile.clone();
126
+ }
127
+
128
+ if (this.mapperFile) {
129
+ this.mapperFile.options.removeComments = this.removeComments;
130
+ this.mapperFile.options.moduleIdentityToken = this.moduleIdentityToken;
131
+ this.mapperFile.options.filename = this.filename;
132
+
133
+ this.mapperFile.options.usePrivateAttributes = this.usePrivateAttributes;
134
+ this.mapperFile.options.fallbackTarget = this.fallbackTarget;
135
+
136
+ // Initialize custom props whitelist
137
+ if (this.customProps && this.customProps.length > 0) {
138
+ const props = Array.isArray(this.customProps) ? this.customProps : [this.customProps];
139
+ props.forEach(prop => this.mapperFile.customProps.add(prop));
140
+ }
141
+ }
142
+
143
+ this._initializeMappers();
144
+ }
145
+
146
+
147
+ /**
148
+ * Adds a new rule or changes an existing one.
149
+ *
150
+ * @param {string} id - The name of the tag.
151
+ * @param {Function} render - The function that formats the tag.
152
+ * @param {Object} [options] - Extra settings for the tag.
153
+ */
154
+ register = (id, render, options) => {
155
+ this.mapperFile.register(id, render, options);
156
+ };
157
+
158
+ /**
159
+ * Copies rules from other mappers.
160
+ *
161
+ * @param {...Mapper} mappers - The mappers to copy from.
162
+ */
163
+ inherit = (...mappers) => {
164
+ this.mapperFile.inherit(...mappers);
165
+ };
166
+
167
+ /**
168
+ * Gets a rule by its name.
169
+ *
170
+ * @param {string} id - The tag name.
171
+ * @returns {Object|null}
172
+ */
173
+ get = id => {
174
+ return this.mapperFile.get(id);
175
+ };
176
+
177
+ removeOutput = id => {
178
+ this.mapperFile.removeOutput(id);
179
+ };
180
+
181
+ clear = () => {
182
+ this.mapperFile.clear();
183
+ };
184
+
185
+ _initializeMappers() {
186
+ if (!this.targetFormat) {
187
+ runtimeError(["{line}<$red:Undefined Format$>: <$yellow:Format argument is not defined.$>{line}"]);
188
+ }
189
+
190
+ if (!this.mapperFile && this.targetFormat) {
191
+ runtimeError([`{line}<$red:Unknown Format$>: <$yellow:Mapper for format '${this.targetFormat}' not found.$>{line}`]);
192
+ }
193
+ }
194
+
195
+ reportWarning(message) {
196
+ this.warnings.push(message);
197
+ }
198
+
199
+
200
+ _ensurePrepared() {
201
+ if (this._prepared) return;
202
+
203
+ // Final check
204
+ if (!this.mapperFile) {
205
+ runtimeError([
206
+ `{line}<$red:Unknown Format$>: <$yellow:No mapper found for format:$> <$green:'${this.targetFormat}'$>`,
207
+ `{N}<$yellow:Make sure you have registered format mapper correctly.$>{line}`
208
+ ]);
209
+ }
210
+
211
+ this._prepared = true;
212
+ }
213
+
214
+ /**
215
+ * Breaks the code into small pieces called tokens.
216
+ *
217
+ * @param {string} [src=this.src] - The code to break apart.
218
+ * @returns {Promise<Array<Object>>} - The list of tokens.
219
+ */
220
+ async lex(src = this.src) {
221
+ this._ensurePrepared();
222
+ if (src !== this.src) this.src = src;
223
+ let tokens = lexer(this.src, this.filename);
224
+ return tokens;
225
+ }
226
+
227
+ lexSync(src = this.src) {
228
+ this._ensurePrepared();
229
+ if (src !== this.src) this.src = src;
230
+ let tokens = lexer(this.src, this.filename);
231
+ return tokens;
232
+ }
233
+
234
+ /**
235
+ * Organizes the code into a tree structure.
236
+ * Also handles modules and checks for errors.
237
+ *
238
+ * @param {string} [src=this.src] - Optional source override.
239
+ * @returns {Promise<Array<Object>>} - The final code tree.
240
+ */
241
+ async parse(src = this.src) {
242
+ const tokens = await this.lex(src);
243
+ let ast = parser(tokens, this.filename, this.placeholders, {});
244
+
245
+ ast = await resolveModules(ast, {
246
+ mapperFile: this.mapperFile,
247
+ filename: this.filename,
248
+ format: this.targetFormat,
249
+ instance: this,
250
+ importStack: this.importStack
251
+ });
252
+
253
+ if (this.mapperFile) {
254
+ validateAST(ast, this.mapperFile, this);
255
+ }
256
+
257
+ return ast;
258
+ }
259
+
260
+ parseSync(src = this.src) {
261
+ this._ensurePrepared();
262
+ if (src !== this.src) this.src = src;
263
+ const tokens = lexer(this.src, this.filename);
264
+ let ast = parser(tokens, this.filename, this.placeholders, {});
265
+
266
+ if (this.mapperFile) {
267
+ validateAST(ast, this.mapperFile, this);
268
+ }
269
+
270
+ return ast;
271
+ }
272
+
273
+ /**
274
+ * Turns the SomMark code into the final format.
275
+ *
276
+ * @param {string} [src=this.src] - Optional source override.
277
+ * @returns {Promise<string>} - The finished code.
278
+ */
279
+ async transpile(src = this.src) {
280
+ if (src !== this.src) this.src = src;
281
+ this._ensurePrepared();
282
+
283
+ if (this.showSpinner) startSpinner();
284
+ try {
285
+ const ast = this.ast || await this.parse(src);
286
+ let result = await transpiler({
287
+ ast,
288
+ format: this.targetFormat,
289
+ mapperFile: this.mapperFile,
290
+ security: this.security,
291
+ settings: this.rawSettings,
292
+ generateRuntimeOutput: this.generateRuntimeOutput,
293
+ hideRuntimeOutput: this.hideRuntimeOutput,
294
+ instance: this
295
+ });
296
+
297
+ if (this.outputValidator && typeof this.outputValidator === "function") {
298
+ await this.outputValidator(result);
299
+ }
300
+
301
+ return result;
302
+ } finally {
303
+ if (this.showSpinner) stopSpinner();
304
+ }
305
+ }
306
+
307
+
308
+ }
309
+
310
+ /**
311
+ * A quick way to break code into tokens.
312
+ * Uses HTML settings by default.
313
+ *
314
+ * @param {string} src - The raw SomMark source.
315
+ * @param {string} [filename="anonymous"] - Filename for error context.
316
+ * @returns {Promise<Array<Object>>} - The list of tokens.
317
+ */
318
+ const lex = async (src, filename = "anonymous") => {
319
+ if (src === undefined || src === null) {
320
+ runtimeError([`{line}<$red:Missing Source:$> <$yellow:The 'src' argument is required for tokenization.$>{line}`]);
321
+ }
322
+ if (typeof src !== "string") {
323
+ runtimeError([`{line}<$red:Invalid Source Type:$> <$yellow:The 'src' argument must be a string, received ${typeof src}.$>{line}`]);
324
+ }
325
+ return lexer(src, filename);
326
+ };
327
+
328
+ /**
329
+ * A quick way to organize code into a tree.
330
+ * Uses HTML settings by default.
331
+ *
332
+ * @param {string} src - The raw SomMark source.
333
+ * @param {string} [filename="anonymous"] - Filename for error context.
334
+ * @returns {Promise<Array<Object>>} - The final code tree.
335
+ */
336
+ async function parse(src, filename = "anonymous") {
337
+ if (src === undefined || src === null) {
338
+ runtimeError([`{line}<$red:Missing Source:$> <$yellow:The 'src' argument is required for parsing.$>{line}`]);
339
+ }
340
+ if (typeof src !== "string") {
341
+ runtimeError([`{line}<$red:Invalid Source Type:$> <$yellow:The 'src' argument must be a string, received ${typeof src}.$>{line}`]);
342
+ }
343
+ return await new SomMark({ src, filename, format: textFormat }).parse();
344
+ }
345
+
346
+ /**
347
+ * Transpiles SomMark code to a target format.
348
+ *
349
+ * @param {Object} options - Transpilation options.
350
+ * @param {string} options.src - Raw source code.
351
+ * @param {string} [options.format="html"] - Target format.
352
+ * @param {string} [options.filename="anonymous"] - Filename for context.
353
+ * @param {Mapper|null} [options.mapperFile=null] - Custom rules for formatting.
354
+ * @param {boolean} [options.removeComments=true] - Strip comments.
355
+ * @param {Object} [options.placeholders={}] - Global placeholders.
356
+ * @param {Array<string>} [options.customProps=[]] - Custom attribute whitelist.
357
+ * @param {Object} [options.importAliases={}] - Custom path aliases for modules.
358
+ * @returns {Promise<string>} - Transpiled output.
359
+ */
360
+ async function transpile(options = {}) {
361
+ if (typeof options !== "object" || options === null) {
362
+ runtimeError([`{line}<$red:Invalid Options:$> <$yellow:The options argument must be a non-null object.$>{line}`]);
363
+ }
364
+ const { src, ast, format } = options;
365
+
366
+ if (format === undefined || format === null) {
367
+ runtimeError([`{line}<$red:Missing Target Format:$> <$yellow:The 'format' parameter is required for transpilation (e.g. 'html', 'markdown', 'xml', 'mdx', 'json', etc.).$>{line}`]);
368
+ }
369
+
370
+ if ((src === undefined || src === null) && (ast === undefined || ast === null)) {
371
+ runtimeError([`{line}<$red:Missing Input:$> <$yellow:Either 'src' or 'ast' must be provided for transpilation.$>{line}`]);
372
+ }
373
+
374
+ const sm = new SomMark(options);
375
+ return await sm.transpile();
376
+ }
377
+
378
+ /**
379
+ * A quick, synchronous way to get tokens.
380
+ *
381
+ * @param {string} src - Raw source code.
382
+ * @param {string} [filename="anonymous"] - Filename for error context.
383
+ * @returns {Array<Object>} - The list of tokens.
384
+ */
385
+ const lexSync = (src, filename = "anonymous") => {
386
+ if (src === undefined || src === null) {
387
+ runtimeError([`{line}<$red:Missing Source:$> <$yellow:The 'src' argument is required for tokenization.$>{line}`]);
388
+ }
389
+ if (typeof src !== "string") {
390
+ runtimeError([`{line}<$red:Invalid Source Type:$> <$yellow:The 'src' argument must be a string, received ${typeof src}.$>{line}`]);
391
+ }
392
+ return lexer(src, filename);
393
+ };
394
+
395
+ /**
396
+ * A quick, synchronous way to get the code tree.
397
+ *
398
+ * @param {string} src - Raw source code.
399
+ * @param {Object} [options={}] - Parsing options.
400
+ * @returns {Array<Object>} - The code tree.
401
+ */
402
+ const parseSync = (src, filename = "anonymous") => {
403
+ if (src === undefined || src === null) {
404
+ runtimeError([`{line}<$red:Missing Source:$> <$yellow:The 'src' argument is required for parsing.$>{line}`]);
405
+ }
406
+ if (typeof src !== "string") {
407
+ runtimeError([`{line}<$red:Invalid Source Type:$> <$yellow:The 'src' argument must be a string, received ${typeof src}.$>{line}`]);
408
+ }
409
+ const tokens = lexer(src, filename);
410
+ return parser(tokens, filename);
411
+ };
412
+
413
+ async function findAndLoadConfig(targetPath) {
414
+ return await defaultFindAndLoadConfig(targetPath);
415
+ }
416
+
417
+ import Evaluator, { setCompilerClass } from "./core/evaluator.js";
418
+ setCompilerClass(SomMark);
419
+
420
+ export {
421
+ registerSharedOutputs,
422
+ HTML,
423
+ MARKDOWN,
424
+ MDX,
425
+ Json,
426
+ Jsonc,
427
+ XML,
428
+ Mapper,
429
+ FORMATS,
430
+ lex,
431
+ parse,
432
+ transpile,
433
+ lexSync,
434
+ parseSync,
435
+ TOKEN_TYPES,
436
+ labels,
437
+ enableColor,
438
+ safeArg,
439
+ findAndLoadConfig,
440
+ Evaluator,
441
+ preprocessRuntimeLogic
442
+ };
443
+ export default SomMark;
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "sommark",
3
- "version": "4.1.0",
3
+ "version": "4.3.0",
4
4
  "description": "SomMark is a declarative, extensible markup language for structured content that can be converted to HTML, Markdown, MDX, JSON, XML, and more.",
5
5
  "main": "index.js",
6
6
  "files": [
7
7
  "index.js",
8
+ "index.browser.js",
9
+ "index.shared.js",
8
10
  "core/",
9
11
  "mappers/",
10
12
  "helpers/",
@@ -12,6 +14,7 @@
12
14
  "constants/",
13
15
  "cli/",
14
16
  "assets/",
17
+ "dist/",
15
18
  "grammar.ebnf",
16
19
  "README.md",
17
20
  "LICENSE"
@@ -21,13 +24,17 @@
21
24
  },
22
25
  "type": "module",
23
26
  "exports": {
24
- "import": "./index.js"
27
+ ".": "./index.js",
28
+ "./browser": "./index.browser.js",
29
+ "./browser/cdn": "./dist/sommark.browser.js"
25
30
  },
26
31
  "scripts": {
27
32
  "test": "vitest",
28
33
  "test:run": "vitest run --pool=forks --maxWorkers=1",
29
34
  "test:watch": "vitest watch",
30
- "test:html": "vitest run tests/html"
35
+ "test:html": "vitest run tests/html",
36
+ "build:browser": "rollup -c rollup.browser.config.js",
37
+ "prepublishOnly": "npm run build:browser"
31
38
  },
32
39
  "bin": {
33
40
  "sommark": "cli/cli.mjs"
@@ -60,16 +67,20 @@
60
67
  "homepage": "https://github.com/Adam-Elmi/SomMark#readme",
61
68
  "devDependencies": {
62
69
  "@mdx-js/mdx": "^3.1.1",
70
+ "@rollup/plugin-commonjs": "^29.0.3",
71
+ "@rollup/plugin-node-resolve": "^16.0.3",
63
72
  "fast-xml-parser": "^5.5.11",
64
73
  "isomorphic-dompurify": "^3.14.0",
65
74
  "jsdom": "^29.0.2",
66
75
  "remark": "^15.0.1",
67
76
  "remark-gfm": "^4.0.1",
68
77
  "remark-parse": "^11.0.0",
78
+ "rollup": "^4.61.1",
69
79
  "vitest": "^4.0.16"
70
80
  },
71
81
  "dependencies": {
72
- "@sebastianwessel/quickjs": "^1.1.1",
73
- "acorn": "^8.15.0"
82
+ "acorn": "^8.15.0",
83
+ "pathe": "^2.0.3",
84
+ "quickjs-emscripten": "^0.32.0"
74
85
  }
75
86
  }