sommark 4.0.3 → 4.2.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/README.md +304 -73
- package/cli/cli.mjs +1 -1
- package/cli/commands/build.js +3 -1
- package/cli/commands/help.js +2 -0
- package/cli/commands/init.js +25 -6
- package/cli/constants.js +2 -1
- package/cli/helpers/transpile.js +5 -2
- package/constants/html_props.js +1 -0
- package/core/evaluator.js +1061 -0
- package/core/formats.js +15 -7
- package/core/helpers/config-loader.js +16 -8
- package/core/helpers/lib.js +72 -0
- package/core/helpers/preprocessor.js +202 -0
- package/core/helpers/runtimeOutput.js +28 -0
- package/core/helpers/url.js +12 -0
- package/core/labels.js +9 -2
- package/core/lexer.js +228 -61
- package/core/modules.js +338 -60
- package/core/parser.js +275 -55
- package/core/tokenTypes.js +11 -0
- package/core/transpiler.js +352 -66
- package/core/validator.js +70 -7
- package/formatter/tag.js +31 -7
- package/grammar.ebnf +21 -10
- package/helpers/fetch-fs.js +37 -0
- package/helpers/safeDataParser.js +3 -3
- package/helpers/spinner.js +97 -0
- package/helpers/utils.js +46 -0
- package/helpers/virtual-fs.js +29 -0
- package/index.browser.js +87 -0
- package/index.js +23 -332
- package/index.shared.js +443 -0
- package/mappers/languages/html.js +50 -9
- package/mappers/languages/json.js +81 -38
- package/mappers/languages/jsonc.js +82 -0
- package/mappers/languages/markdown.js +88 -48
- package/mappers/languages/mdx.js +50 -15
- package/mappers/languages/text.js +67 -0
- package/mappers/languages/xml.js +6 -6
- package/mappers/mapper.js +36 -4
- package/mappers/shared/index.js +12 -13
- package/package.json +11 -2
- package/core/formatter.js +0 -215
package/index.shared.js
ADDED
|
@@ -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;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import Mapper from "../mapper.js";
|
|
2
2
|
import { VOID_ELEMENTS } from "../../constants/void_elements.js";
|
|
3
3
|
import { registerSharedOutputs } from "../shared/index.js";
|
|
4
|
+
import kebabize from "../../helpers/kebabize.js";
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Helper to format an HTML tag with attributes and content.
|
|
@@ -10,17 +11,17 @@ import { registerSharedOutputs } from "../shared/index.js";
|
|
|
10
11
|
* @param {string} content - The text or tags inside this tag.
|
|
11
12
|
* @returns {string} - The finished HTML string.
|
|
12
13
|
*/
|
|
13
|
-
const renderHtmlTag = function (id, args, content) {
|
|
14
|
+
const renderHtmlTag = function (id, args, content, isSelfClosing) {
|
|
14
15
|
const element = this.tag(id);
|
|
15
16
|
|
|
16
|
-
element.smartAttributes(args, this.customProps);
|
|
17
|
+
element.smartAttributes(args, this.customProps, this.options);
|
|
17
18
|
|
|
18
19
|
let finalContent = content;
|
|
19
20
|
if (id.toLowerCase() === "script" && args.scoped === true) {
|
|
20
21
|
finalContent = `(function(){\n${content}\n})();`;
|
|
21
22
|
}
|
|
22
23
|
|
|
23
|
-
if (VOID_ELEMENTS.has(id.toLowerCase())) {
|
|
24
|
+
if (VOID_ELEMENTS.has(id.toLowerCase()) || isSelfClosing) {
|
|
24
25
|
return element.selfClose();
|
|
25
26
|
}
|
|
26
27
|
|
|
@@ -40,6 +41,22 @@ const HTML = Mapper.define({
|
|
|
40
41
|
return `<!-- ${text} -->`;
|
|
41
42
|
},
|
|
42
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Natively formats runtime logic for HTML.
|
|
46
|
+
* Global logic is placed in a raw script tag.
|
|
47
|
+
* Block-level logic is wrapped in a self-executing function to isolate scope and provide `self` reference.
|
|
48
|
+
*/
|
|
49
|
+
runtimeLogic(code, isGlobal, parentId) {
|
|
50
|
+
if (isGlobal) {
|
|
51
|
+
return this.tag("script").body(`\n${code.split("\n").filter(line => line.trim() !== "").join("\n")}\n`);
|
|
52
|
+
} else {
|
|
53
|
+
const selfDefinition = parentId
|
|
54
|
+
? `const self = document.querySelector('[data-sommark-id="${parentId}"]');`
|
|
55
|
+
: `const self = document.currentScript.parentElement;`;
|
|
56
|
+
return this.tag("script").body(`\n(async function(){${selfDefinition}\nif (self) {\n${code.split("\n").filter(line => line.trim() !== "").join("\n")}\n}\n})();\n`);
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
|
|
43
60
|
/**
|
|
44
61
|
* Formats plain text and makes sure it's safe for HTML if needed.
|
|
45
62
|
*/
|
|
@@ -66,9 +83,6 @@ const HTML = Mapper.define({
|
|
|
66
83
|
if (options?.escape !== false) {
|
|
67
84
|
out = this.escapeHTML(out);
|
|
68
85
|
}
|
|
69
|
-
if (out.includes('\n')) {
|
|
70
|
-
out = '\n' + out + '\n';
|
|
71
|
-
}
|
|
72
86
|
return out;
|
|
73
87
|
},
|
|
74
88
|
|
|
@@ -83,7 +97,7 @@ const HTML = Mapper.define({
|
|
|
83
97
|
const isCodeStyleOrScript = ["code", "style", "script"].includes(id);
|
|
84
98
|
|
|
85
99
|
return {
|
|
86
|
-
render: function ({ args, content }) { return renderHtmlTag.call(this, id, args, content); },
|
|
100
|
+
render: function ({ args, content, isSelfClosing }) { return renderHtmlTag.call(this, id, args, content, isSelfClosing); },
|
|
87
101
|
options: {
|
|
88
102
|
type: isCodeStyleOrScript ? ["Block", "AtBlock"] : ["Block", "Inline"],
|
|
89
103
|
escape: !isCodeStyleOrScript,
|
|
@@ -91,9 +105,9 @@ const HTML = Mapper.define({
|
|
|
91
105
|
}
|
|
92
106
|
};
|
|
93
107
|
},
|
|
94
|
-
|
|
108
|
+
|
|
95
109
|
options: {
|
|
96
|
-
|
|
110
|
+
trimAndWrapBlocks: true
|
|
97
111
|
}
|
|
98
112
|
});
|
|
99
113
|
|
|
@@ -127,7 +141,34 @@ HTML.register(
|
|
|
127
141
|
type: "Block"
|
|
128
142
|
}
|
|
129
143
|
);
|
|
144
|
+
// Inline CSS tag (Moved from shared)
|
|
145
|
+
HTML.register("css", ({ args, content }) => {
|
|
146
|
+
// Compile style from named arguments (keys that are not numeric digits)
|
|
147
|
+
const namedStyle = Object.keys(args)
|
|
148
|
+
.filter(k => isNaN(parseInt(k)))
|
|
149
|
+
.map(k => `${kebabize(k)}:${args[k]}`)
|
|
150
|
+
.join(";");
|
|
151
|
+
|
|
152
|
+
// Fetch positional style string (index 0) or "style" key if present
|
|
153
|
+
let positionalStyle = HTML.safeArg({ args, index: 0, key: "style", fallBack: "" });
|
|
154
|
+
|
|
155
|
+
// Filter out positional styles that are just duplicates of named arguments
|
|
156
|
+
const hasDuplicateNamed = Object.keys(args)
|
|
157
|
+
.filter(k => isNaN(parseInt(k)))
|
|
158
|
+
.some(k => args[k] === positionalStyle);
|
|
159
|
+
|
|
160
|
+
if (hasDuplicateNamed) {
|
|
161
|
+
positionalStyle = "";
|
|
162
|
+
}
|
|
130
163
|
|
|
164
|
+
// Combine both together
|
|
165
|
+
let style = [positionalStyle, namedStyle].filter(s => s.trim()).join(";");
|
|
166
|
+
|
|
167
|
+
style = style.split(";").filter(s => s.trim()).map(s => s.trim().split(":").map(s => s.trim()).join(":")).join(";");
|
|
168
|
+
return HTML.tag("span").attributes({ style }).body(content);
|
|
169
|
+
}, {
|
|
170
|
+
type: "Inline"
|
|
171
|
+
});
|
|
131
172
|
registerSharedOutputs(HTML);
|
|
132
173
|
|
|
133
174
|
export default HTML;
|