@d10f/asciidoc-astro-loader 0.0.1 → 0.0.3

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/dist/index.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import {
2
2
  sourceCodeConverter
3
- } from "./chunk-HAZIHU2Y.js";
3
+ } from "./chunk-KZRXEKZK.js";
4
+ import {
5
+ transformAsciidocCallout
6
+ } from "./chunk-5P6LDJGO.js";
4
7
  import {
5
8
  slugify,
6
9
  splitFilenameComponents
7
- } from "./chunk-DDIUST2Z.js";
10
+ } from "./chunk-2UGTFP4R.js";
8
11
  import {
9
12
  HandlebarsEngine,
10
13
  NunjucksEngine
@@ -247,23 +250,23 @@ var AsciidocDocument = class {
247
250
  };
248
251
 
249
252
  // src/schemas/index.ts
250
- import { z as z3 } from "zod";
253
+ import { z as z3 } from "astro/zod";
251
254
 
252
255
  // src/schemas/document.ts
253
256
  import { resolve } from "path";
254
- import { z } from "zod";
255
- var documentOptionsSchema = z.looseObject({
257
+ import { z } from "astro/zod";
258
+ var documentOptionsSchema = z.object({
256
259
  mode: z.union([z.literal("safe"), z.literal("unsafe")]).default("safe"),
257
- template: z.string().default("").transform((val) => resolve(process.cwd(), val)),
260
+ template: z.string().default("").transform((val) => val ? resolve(process.cwd(), val) : ""),
258
261
  recursive: z.boolean().default(false)
259
- }).default({
262
+ }).passthrough().default({
260
263
  mode: "safe",
261
264
  template: "",
262
265
  recursive: false
263
266
  });
264
267
 
265
268
  // src/schemas/shiki.ts
266
- import { z as z2 } from "zod";
269
+ import { z as z2 } from "astro/zod";
267
270
  var shikiOptionsSchema = z2.object({
268
271
  theme: z2.union([
269
272
  z2.string(),
@@ -278,8 +281,19 @@ var shikiOptionsSchema = z2.object({
278
281
  defaultColor: z2.string().default("light-dark()"),
279
282
  cssVariablePrefix: z2.string().default("--shiki-"),
280
283
  mergeWhitespaces: z2.union([z2.boolean(), z2.literal("never")]).default(true),
281
- tabindex: z2.union([z2.number(), z2.string(), z2.literal(false)]).default(false)
282
- }).transform(({ theme, ...rest }) => ({
284
+ tabindex: z2.union([z2.number(), z2.string(), z2.literal(false)]).default(false),
285
+ // transformers: z
286
+ // .array(
287
+ // z.object({
288
+ // name: z.string(),
289
+ // enforce: z.union([z.literal('pre'), z.literal('post')]),
290
+ // }),
291
+ // )
292
+ // .optional(),
293
+ callouts: z2.object({
294
+ cssClasses: z2.string().optional()
295
+ }).optional()
296
+ }).passthrough().transform(({ theme, ...rest }) => ({
283
297
  themes: theme,
284
298
  ...rest
285
299
  })).default({
@@ -290,7 +304,9 @@ var shikiOptionsSchema = z2.object({
290
304
  theme: {
291
305
  light: "catppuccin-latte",
292
306
  dark: "catppuccin-macchiato"
293
- }
307
+ },
308
+ // transformers: undefined,
309
+ callouts: void 0
294
310
  });
295
311
  function transformThemeProp(value) {
296
312
  return typeof value === "string" ? { light: value, dark: value } : value;
@@ -335,68 +351,117 @@ async function createHighlighter(documents, themes) {
335
351
  }
336
352
 
337
353
  // src/loader.ts
338
- function asciidocLoader(options) {
339
- const parsedOpts = loaderOptionsSchema.parse(options);
340
- if (parsedOpts.document.converters === void 0) {
341
- parsedOpts.document.converters = [
342
- sourceCodeConverter({ nodeContext: "listing" })
343
- ];
354
+ function asciidocLoader(_options) {
355
+ const options = loaderOptionsSchema.parse(_options);
356
+ if (options.document.converters === void 0) {
357
+ options.document.converters = [];
344
358
  }
345
- if (parsedOpts.document.templateEngines === void 0) {
346
- parsedOpts.document.templateEngines = [
359
+ if (options.document.templateEngines === void 0) {
360
+ options.document.templateEngines = [
347
361
  new HandlebarsEngine(),
348
362
  new NunjucksEngine()
349
363
  ];
350
364
  }
365
+ let highlighter;
366
+ let templateEngine;
351
367
  return {
352
368
  name: "asciidoc-loader",
353
- async load({ config, parseData, store, logger }) {
369
+ async load(loaderContext) {
370
+ const { config, logger, watcher } = loaderContext;
354
371
  const root = config.root.pathname;
355
- const base = parsedOpts.base.startsWith(".") ? realpathSync(options.base) : root + options.base;
372
+ const base = options.base.startsWith(".") ? realpathSync(options.base) : root + options.base;
356
373
  const docs = readdirSync2(base, "utf8").filter((file) => file.match(/(?:\.a(?:scii)?doc)$/)).map((filename) => new AsciidocDocument(`${base}/${filename}`));
357
374
  if (docs.length === 0) {
358
375
  logger.warn("No documents found for this collection.");
359
376
  return;
360
377
  }
361
- let templateEngine = void 0;
362
- if (parsedOpts.document.template) {
378
+ if (options.document.template) {
363
379
  templateEngine = new TemplateEngineRegistry(
364
- parsedOpts.document.templateEngines,
380
+ options.document.templateEngines,
365
381
  {
366
- rootDir: parsedOpts.document.template,
367
- recursive: parsedOpts.document.recursive
382
+ rootDir: options.document.template,
383
+ recursive: options.document.recursive
368
384
  }
369
385
  );
370
386
  await templateEngine.loadEngines();
371
387
  }
372
- const highlighter = await createHighlighter(
373
- docs,
374
- parsedOpts.syntaxHighlighting.themes
388
+ if (!highlighter) {
389
+ highlighter = await createHighlighter(
390
+ docs,
391
+ options.syntaxHighlighting.themes
392
+ );
393
+ }
394
+ const converters = options.document.converters.map(
395
+ (converter) => converter(options, highlighter)
375
396
  );
376
- const converters = parsedOpts.document.converters.map(
377
- (converter) => converter(parsedOpts, highlighter)
397
+ const hasSourceCodeConverter = converters.find(
398
+ (converter) => converter.nodeContext === "listing" && converter?.nodeStyle === "source"
378
399
  );
379
- docs.forEach(async (doc) => {
380
- const data = await parseData({
381
- id: doc.slug,
382
- data: {
383
- title: doc.title,
384
- createdAt: new Date(doc.createdAt),
385
- description: doc.preamble
386
- }
387
- });
388
- store.set({
389
- id: doc.slug,
390
- data,
391
- rendered: {
392
- html: doc.convert(converters, templateEngine)
400
+ if (!hasSourceCodeConverter) {
401
+ converters.push(
402
+ sourceCodeConverter({
403
+ transformers: [
404
+ ...options.syntaxHighlighting.transformers ?? [],
405
+ transformAsciidocCallout(
406
+ options.syntaxHighlighting.callouts
407
+ )
408
+ ]
409
+ })(options, highlighter)
410
+ );
411
+ }
412
+ await Promise.all(
413
+ docs.map(
414
+ (doc) => setDocument(doc, converters, templateEngine, loaderContext)
415
+ )
416
+ );
417
+ if (watcher) {
418
+ let handle2 = function() {
419
+ logger.info("Shutting down highlighter instance");
420
+ highlighter.dispose();
421
+ process.exit(0);
422
+ };
423
+ var handle = handle2;
424
+ const watchedFileRegExp = new RegExp(
425
+ `^${base}.*.(a(?:scii)?doc)$`
426
+ );
427
+ watcher.on("change", async (changedPath) => {
428
+ if (changedPath.match(watchedFileRegExp)) {
429
+ const newDoc = new AsciidocDocument(changedPath);
430
+ await setDocument(
431
+ newDoc,
432
+ converters,
433
+ templateEngine,
434
+ loaderContext
435
+ );
393
436
  }
394
437
  });
395
- });
396
- nextTick(highlighter.dispose);
438
+ if (highlighter) {
439
+ process.on("SIGINT", handle2);
440
+ process.on("SIGTERM", handle2);
441
+ }
442
+ } else {
443
+ nextTick(highlighter.dispose);
444
+ }
397
445
  }
398
446
  };
399
447
  }
448
+ async function setDocument(doc, converters, templateEngine, { parseData, store }) {
449
+ const data = await parseData({
450
+ id: doc.slug,
451
+ data: {
452
+ title: doc.title,
453
+ createdAt: new Date(doc.createdAt),
454
+ description: doc.preamble
455
+ }
456
+ });
457
+ store.set({
458
+ id: doc.slug,
459
+ data,
460
+ rendered: {
461
+ html: doc.convert(converters, templateEngine)
462
+ }
463
+ });
464
+ }
400
465
  export {
401
466
  asciidocLoader
402
467
  };
@@ -25,14 +25,9 @@ __export(converters_exports, {
25
25
  module.exports = __toCommonJS(converters_exports);
26
26
 
27
27
  // src/lib/asciidoc/converters/sourceCodeConverter.ts
28
- var import_transformers = require("@shikijs/transformers");
29
28
  var import_node_path = require("path");
30
29
 
31
30
  // src/lib/utils.ts
32
- function escapeRegexCharacters(str) {
33
- const re = /[-\\^$*+?.()|\[\]{}]/g;
34
- return str.replace(re, "\\$&");
35
- }
36
31
  function splitFilenameComponents(filename) {
37
32
  const match = filename.match(/^(?<path>.*\/)*(?<name>[^\.]+)\.(?<ext>.*)$/);
38
33
  return {
@@ -42,115 +37,21 @@ function splitFilenameComponents(filename) {
42
37
  };
43
38
  }
44
39
 
45
- // src/lib/shiki/transformers/transformAsciidocCallout.ts
46
- function transformAsciidocCallout({
47
- node,
48
- cssClasses = "pointer-events-none select-none ml-2"
49
- }) {
50
- const lineComments = ["//", "#", ";;"];
51
- const customLineComment = node.getAttribute("line-comment");
52
- if (customLineComment) {
53
- lineComments.push(escapeRegexCharacters(customLineComment));
54
- }
55
- const calloutReList = [
56
- // Handles C-style and similar comments like Perl, Python...
57
- new RegExp(`(?:${lineComments.join("|")})((?:\\s+<(\\d+)>)+)`),
58
- // Handles XML comments
59
- new RegExp(/((?:\s*<!--(\d+)-->)+)/)
60
- ];
61
- const linesWithCallout = {};
62
- return {
63
- preprocess(code) {
64
- return code.split("\n").map((line, idx) => {
65
- for (const re of calloutReList) {
66
- const match = line.match(re);
67
- if (!match) continue;
68
- const callouts = match[0].trim().replaceAll(/(?:<!--|-->|[<>])/g, "").split(" ");
69
- linesWithCallout[idx + 1] = callouts;
70
- return line.replace(re, "");
71
- }
72
- return line;
73
- }).join("\n");
74
- },
75
- line(hast, line) {
76
- const callouts = linesWithCallout[line];
77
- if (!callouts) return;
78
- callouts.forEach((calloutId) => {
79
- hast.properties[`data-callout-${calloutId}`] = "";
80
- hast.children.push({
81
- type: "element",
82
- tagName: "i",
83
- properties: {
84
- class: `conum ${cssClasses}`,
85
- "data-value": calloutId
86
- },
87
- children: [
88
- {
89
- type: "element",
90
- tagName: "b",
91
- properties: {},
92
- children: [
93
- {
94
- type: "text",
95
- value: calloutId
96
- }
97
- ]
98
- }
99
- ]
100
- });
101
- });
102
- }
103
- };
104
- }
105
-
106
- // src/lib/shiki/transformers/transformConsoleCodeBlock.ts
107
- function transformConsoleCodeBlock(options = {
108
- cssClasses: "pointer-events-none select-none mr-2 opacity-50"
109
- }) {
110
- const unselectablePrompt = `<span $1 class="${options.cssClasses}">$</span>`;
111
- const linePrefix = '<span class="line[^>]+?>';
112
- const splitPrompt = new RegExp(
113
- `(?<=${linePrefix})(?:<span (style="[^"]*?")>\\s*?\\$\\s+?([^<]))`
114
- );
115
- const trimWhitespace = new RegExp(
116
- `(?<=${linePrefix})(?:<span (style="[^"]*?")>\\s*?\\$\\s*?<\\/span>(?:<span>\\s+<\\/span>)?)`
117
- );
118
- const trimWhitespaceAhead = new RegExp(
119
- `(?<=${linePrefix}<span [^>]+?>\\$<\\/span>)(<span style="[^"]+?">)\\s+?`
120
- );
121
- return {
122
- postprocess: (html, { lang }) => {
123
- if (lang === "console") {
124
- return html.split("\n").map((line) => {
125
- return line.replace(
126
- splitPrompt,
127
- unselectablePrompt + "<span $1>$2"
128
- ).replace(trimWhitespace, unselectablePrompt).replace(trimWhitespaceAhead, "$1");
129
- }).join("\n");
130
- }
131
- }
132
- };
133
- }
134
-
135
40
  // src/lib/asciidoc/converters/sourceCodeConverter.ts
136
- var sourceCodeConverter = ({ nodeContext, transformers, template }) => {
41
+ var sourceCodeConverter = ({ transformers, template }) => {
137
42
  return (options, highlighter) => {
138
43
  return {
139
- nodeContext: nodeContext ?? "listing",
44
+ nodeContext: "listing",
45
+ nodeStyle: "source",
140
46
  convert(node, templateEngine) {
141
47
  const input = node.getSourceLines().join("\n");
142
48
  const lang = node.getAttribute("language");
143
49
  const output = highlighter.codeToHtml(input, {
144
50
  ...options.syntaxHighlighting,
145
51
  lang,
146
- transformers: [
147
- ...transformers ?? [],
148
- (0, import_transformers.transformerNotationDiff)(),
149
- (0, import_transformers.transformerNotationHighlight)(),
150
- (0, import_transformers.transformerNotationFocus)(),
151
- transformAsciidocCallout({ node }),
152
- transformConsoleCodeBlock()
153
- ]
52
+ transformers: (transformers ?? []).map((transformer) => {
53
+ return typeof transformer === "function" ? transformer(node) : transformer;
54
+ })
154
55
  });
155
56
  if (templateEngine && template) {
156
57
  const { extension } = splitFilenameComponents(template);
@@ -1,11 +1,10 @@
1
1
  import { ShikiTransformer } from 'shiki';
2
- import { C as CustomConverterFactoryFn, N as NodeContext } from '../../../index-Cf7MF6tZ.cjs';
2
+ import { C as CustomConverterFactoryFn, S as ShikiTransformerFactoryFn } from '../../../index-sFlXF8Qm.cjs';
3
3
  import 'asciidoctor';
4
- import 'zod';
4
+ import 'astro/zod';
5
5
 
6
6
  type CodeBlockConverterOptions = {
7
- nodeContext: NodeContext;
8
- transformers: ShikiTransformer[];
7
+ transformers: Array<ShikiTransformer | ShikiTransformerFactoryFn>;
9
8
  template: string;
10
9
  };
11
10
  declare const sourceCodeConverter: CustomConverterFactoryFn<Partial<CodeBlockConverterOptions>>;
@@ -1,11 +1,10 @@
1
1
  import { ShikiTransformer } from 'shiki';
2
- import { C as CustomConverterFactoryFn, N as NodeContext } from '../../../index-Cf7MF6tZ.js';
2
+ import { C as CustomConverterFactoryFn, S as ShikiTransformerFactoryFn } from '../../../index-sFlXF8Qm.js';
3
3
  import 'asciidoctor';
4
- import 'zod';
4
+ import 'astro/zod';
5
5
 
6
6
  type CodeBlockConverterOptions = {
7
- nodeContext: NodeContext;
8
- transformers: ShikiTransformer[];
7
+ transformers: Array<ShikiTransformer | ShikiTransformerFactoryFn>;
9
8
  template: string;
10
9
  };
11
10
  declare const sourceCodeConverter: CustomConverterFactoryFn<Partial<CodeBlockConverterOptions>>;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  sourceCodeConverter
3
- } from "../../../chunk-HAZIHU2Y.js";
4
- import "../../../chunk-DDIUST2Z.js";
3
+ } from "../../../chunk-KZRXEKZK.js";
4
+ import "../../../chunk-2UGTFP4R.js";
5
5
  export {
6
6
  sourceCodeConverter
7
7
  };
@@ -32,8 +32,7 @@ var engines_exports = {};
32
32
  __export(engines_exports, {
33
33
  AbstractEngine: () => AbstractEngine,
34
34
  HandlebarsEngine: () => HandlebarsEngine,
35
- NunjucksEngine: () => NunjucksEngine,
36
- PhpEngine: () => PhpEngine
35
+ NunjucksEngine: () => NunjucksEngine
37
36
  });
38
37
  module.exports = __toCommonJS(engines_exports);
39
38
 
@@ -163,29 +162,9 @@ var NunjucksEngine = class extends AbstractEngine {
163
162
  return this.render(str, options);
164
163
  }
165
164
  };
166
-
167
- // src/lib/asciidoc/templates/engines/Php.ts
168
- var import_php_node = require("@platformatic/php-node");
169
- var PhpEngine = class extends AbstractEngine {
170
- server;
171
- constructor(name = "php", extensions = ["php"], docroot) {
172
- super(name, extensions);
173
- this.server = new import_php_node.Php({ docroot });
174
- }
175
- renderFile(filepath, options) {
176
- const request = new import_php_node.Request({
177
- method: "POST",
178
- url: "http://localhost/" + filepath,
179
- body: Buffer.from(JSON.stringify(options))
180
- });
181
- const response = this.server.handleRequestSync(request);
182
- return response.body.toString();
183
- }
184
- };
185
165
  // Annotate the CommonJS export names for ESM import in node:
186
166
  0 && (module.exports = {
187
167
  AbstractEngine,
188
168
  HandlebarsEngine,
189
- NunjucksEngine,
190
- PhpEngine
169
+ NunjucksEngine
191
170
  });
@@ -1,13 +1,13 @@
1
- import { b as AbstractEngine, a as AsciidocTemplate, T as TemplateModule, F as FilesystemTemplate, R as RawTemplate } from '../../../../index-Cf7MF6tZ.cjs';
2
- import { AbstractNode } from 'asciidoctor';
1
+ import { c as AbstractEngine, a as AsciidocTemplate, T as TemplateModule, F as FilesystemTemplate, R as RawTemplate } from '../../../../index-sFlXF8Qm.cjs';
2
+ import { AbstractBlock } from 'asciidoctor';
3
3
  import 'shiki';
4
- import 'zod';
4
+ import 'astro/zod';
5
5
 
6
6
  declare class HandlebarsEngine extends AbstractEngine implements AsciidocTemplate, TemplateModule, FilesystemTemplate, RawTemplate {
7
7
  private render;
8
8
  constructor(name?: string, extensions?: string[]);
9
9
  load(): Promise<void>;
10
- renderNode(node: AbstractNode, options?: Record<string, unknown>): string;
10
+ renderNode(node: AbstractBlock, options?: Record<string, unknown>): string;
11
11
  renderFile(filepath: string, options?: Record<string, unknown>): string;
12
12
  renderString(str: string, options?: Record<string, unknown>): string;
13
13
  }
@@ -16,15 +16,9 @@ declare class NunjucksEngine extends AbstractEngine implements AsciidocTemplate,
16
16
  private render;
17
17
  constructor(name?: string, extensions?: string[]);
18
18
  load(): Promise<void>;
19
- renderNode(node: AbstractNode, options?: Record<string, unknown>): string;
19
+ renderNode(node: AbstractBlock, options?: Record<string, unknown>): string;
20
20
  renderFile(filepath: string, options?: Record<string, unknown>): string;
21
21
  renderString(str: string, options?: Record<string, unknown>): string;
22
22
  }
23
23
 
24
- declare class PhpEngine extends AbstractEngine implements FilesystemTemplate {
25
- private server;
26
- constructor(name: string | undefined, extensions: string[] | undefined, docroot: string);
27
- renderFile(filepath: string, options?: Record<string, unknown>): string;
28
- }
29
-
30
- export { AbstractEngine, HandlebarsEngine, NunjucksEngine, PhpEngine };
24
+ export { AbstractEngine, HandlebarsEngine, NunjucksEngine };
@@ -1,13 +1,13 @@
1
- import { b as AbstractEngine, a as AsciidocTemplate, T as TemplateModule, F as FilesystemTemplate, R as RawTemplate } from '../../../../index-Cf7MF6tZ.js';
2
- import { AbstractNode } from 'asciidoctor';
1
+ import { c as AbstractEngine, a as AsciidocTemplate, T as TemplateModule, F as FilesystemTemplate, R as RawTemplate } from '../../../../index-sFlXF8Qm.js';
2
+ import { AbstractBlock } from 'asciidoctor';
3
3
  import 'shiki';
4
- import 'zod';
4
+ import 'astro/zod';
5
5
 
6
6
  declare class HandlebarsEngine extends AbstractEngine implements AsciidocTemplate, TemplateModule, FilesystemTemplate, RawTemplate {
7
7
  private render;
8
8
  constructor(name?: string, extensions?: string[]);
9
9
  load(): Promise<void>;
10
- renderNode(node: AbstractNode, options?: Record<string, unknown>): string;
10
+ renderNode(node: AbstractBlock, options?: Record<string, unknown>): string;
11
11
  renderFile(filepath: string, options?: Record<string, unknown>): string;
12
12
  renderString(str: string, options?: Record<string, unknown>): string;
13
13
  }
@@ -16,15 +16,9 @@ declare class NunjucksEngine extends AbstractEngine implements AsciidocTemplate,
16
16
  private render;
17
17
  constructor(name?: string, extensions?: string[]);
18
18
  load(): Promise<void>;
19
- renderNode(node: AbstractNode, options?: Record<string, unknown>): string;
19
+ renderNode(node: AbstractBlock, options?: Record<string, unknown>): string;
20
20
  renderFile(filepath: string, options?: Record<string, unknown>): string;
21
21
  renderString(str: string, options?: Record<string, unknown>): string;
22
22
  }
23
23
 
24
- declare class PhpEngine extends AbstractEngine implements FilesystemTemplate {
25
- private server;
26
- constructor(name: string | undefined, extensions: string[] | undefined, docroot: string);
27
- renderFile(filepath: string, options?: Record<string, unknown>): string;
28
- }
29
-
30
- export { AbstractEngine, HandlebarsEngine, NunjucksEngine, PhpEngine };
24
+ export { AbstractEngine, HandlebarsEngine, NunjucksEngine };
@@ -3,28 +3,8 @@ import {
3
3
  HandlebarsEngine,
4
4
  NunjucksEngine
5
5
  } from "../../../../chunk-2F52PMNV.js";
6
-
7
- // src/lib/asciidoc/templates/engines/Php.ts
8
- import { Php, Request } from "@platformatic/php-node";
9
- var PhpEngine = class extends AbstractEngine {
10
- server;
11
- constructor(name = "php", extensions = ["php"], docroot) {
12
- super(name, extensions);
13
- this.server = new Php({ docroot });
14
- }
15
- renderFile(filepath, options) {
16
- const request = new Request({
17
- method: "POST",
18
- url: "http://localhost/" + filepath,
19
- body: Buffer.from(JSON.stringify(options))
20
- });
21
- const response = this.server.handleRequestSync(request);
22
- return response.body.toString();
23
- }
24
- };
25
6
  export {
26
7
  AbstractEngine,
27
8
  HandlebarsEngine,
28
- NunjucksEngine,
29
- PhpEngine
9
+ NunjucksEngine
30
10
  };