fuma-content 0.0.0 → 0.0.2

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
@@ -13,8 +13,7 @@ function document(entryPoint, options) {
13
13
  ...rest
14
14
  } = item;
15
15
  const result = schema.safeParse(frontmatter);
16
- if (!result.success)
17
- throw createError(file, result.error);
16
+ if (!result.success) throw createError(file, result.error);
18
17
  return {
19
18
  file,
20
19
  info: result.data,
@@ -28,8 +27,7 @@ function json(entryPoint, options) {
28
27
  return read(entryPoint, ["json"], include).map(
29
28
  ({ file, default: data }) => {
30
29
  const result = schema.safeParse(data);
31
- if (!result.success)
32
- throw createError(file, result.error);
30
+ if (!result.success) throw createError(file, result.error);
33
31
  return {
34
32
  file,
35
33
  info: result.data
@@ -38,10 +36,9 @@ function json(entryPoint, options) {
38
36
  );
39
37
  }
40
38
  function createError(file, err) {
41
- return new Error(
42
- `${file}:
43
- ${Object.entries(err.flatten().fieldErrors).map(([k, v]) => `${k}: ${v?.join(", ")}`).join("\n")}`
44
- );
39
+ const message = `${file}:
40
+ ${Object.entries(err.flatten().fieldErrors).map(([k, v]) => `${k}: ${v?.join(", ") ?? ""}`).join("\n")}`;
41
+ return new Error(message);
45
42
  }
46
43
  function read(entryPoint, format, include) {
47
44
  const cast = entryPoint;
@@ -3,7 +3,21 @@ import { ProcessorOptions } from '@mdx-js/mdx';
3
3
  import { VFile } from '@mdx-js/mdx/internal-create-format-aware-processors';
4
4
  import { FSWatcher } from 'chokidar';
5
5
 
6
+ interface OutputEntry extends Output {
7
+ /**
8
+ * extension of file, like: `md`
9
+ */
10
+ format: string;
11
+ file: string;
12
+ }
13
+ interface CompilerWithCache$1 extends Compiler {
14
+ _compileCache?: Map<string, OutputEntry>;
15
+ }
16
+ declare function compile(this: Compiler): Promise<OutputEntry[]>;
17
+ declare function compileFile(this: CompilerWithCache$1, file: string): Promise<OutputEntry>;
18
+
6
19
  interface Output {
20
+ dependencies?: OutputEntry[];
7
21
  content: string;
8
22
  _entryPoint?: unknown;
9
23
  _mdx?: {
@@ -19,24 +33,20 @@ interface Options extends ProcessorOptions {
19
33
  */
20
34
  lastModifiedTime?: "git" | "none";
21
35
  /**
22
- * @defaultValue `['frontmatter']`
36
+ * @defaultValue `['frontmatter', 'lastModified']`
23
37
  */
24
38
  remarkExports?: string[];
39
+ /**
40
+ * Convert relative imports into absolute imports
41
+ *
42
+ * @defaultValue true
43
+ */
44
+ enableAbsoluteImport?: boolean;
25
45
  }
26
46
  /**
27
47
  * Load MDX/markdown files
28
48
  */
29
- declare const loadMDX: ({ lastModifiedTime, format: forceFormat, remarkExports, ...rest }?: Options) => Transformer;
30
-
31
- interface OutputEntry extends Output {
32
- /**
33
- * extension of file, like: `md`
34
- */
35
- format: string;
36
- file: string;
37
- }
38
- declare function compile(this: Compiler): Promise<OutputEntry[]>;
39
- declare function compileFile(this: Compiler, file: string): Promise<OutputEntry>;
49
+ declare const loadMDX: ({ lastModifiedTime, format: forceFormat, remarkExports, enableAbsoluteImport, ...rest }?: Options) => Transformer;
40
50
 
41
51
  interface EntryPointOptions {
42
52
  /**
@@ -57,8 +67,11 @@ declare function loadEntryPoint(this: Compiler, entries: OutputEntry[]): OutputE
57
67
  interface EmitEntry extends OutputEntry {
58
68
  outputPath: string;
59
69
  }
70
+ interface CompilerWithCache extends Compiler {
71
+ _emitCache?: WeakMap<OutputEntry, EmitEntry>;
72
+ }
60
73
  declare function emit(this: Compiler): Promise<void>;
61
- declare function emitEntry(this: Compiler, entry: OutputEntry): Promise<EmitEntry>;
74
+ declare function emitEntry(this: CompilerWithCache, entry: OutputEntry): Promise<EmitEntry>;
62
75
 
63
76
  declare function watch(this: Compiler): FSWatcher;
64
77
 
@@ -86,7 +99,6 @@ interface Compiler {
86
99
  loaders: Record<string, Transformer>;
87
100
  _output?: OutputEntry[];
88
101
  _emit?: EmitEntry[];
89
- _cache: Map<string, OutputEntry>;
90
102
  }
91
103
 
92
104
  declare const defaultOptions: {
@@ -98,6 +110,5 @@ type CreateCompilerOptions = Pick<Partial<CompilerOptions>, keyof typeof default
98
110
  declare function createCompiler(options: CreateCompilerOptions): Promise<Compiler>;
99
111
 
100
112
  declare const defaultConfig: CreateCompilerOptions;
101
- declare const defaultConfigPath = "./fc.config.js";
102
113
 
103
- export { type CreateCompilerOptions, type EntryPointOptions, type Options, createCompiler, defaultConfig, defaultConfigPath, loadEntryPoint, loadMDX };
114
+ export { type CreateCompilerOptions, type EntryPointOptions, type Options, createCompiler, defaultConfig, loadEntryPoint, loadMDX };
package/dist/internal.js CHANGED
@@ -1,14 +1,420 @@
1
- import {
2
- createCompiler,
3
- defaultConfig,
4
- defaultConfigPath,
5
- loadEntryPoint,
6
- loadMDX
7
- } from "./chunk-UDFHC2Y3.js";
1
+ // src/constants.ts
2
+ var defaultConfig = {
3
+ files: ["./content/**/*"]
4
+ };
5
+
6
+ // src/utils/path.ts
7
+ import * as path from "node:path";
8
+ import FastGlob from "fast-glob";
9
+ function getAbsolutePath(cwd, relativePath) {
10
+ return path.join(cwd, relativePath);
11
+ }
12
+ function getRelativePath(cwd, absolutePath) {
13
+ return slash(
14
+ path.join(
15
+ path.relative(cwd, path.dirname(absolutePath)),
16
+ path.basename(absolutePath)
17
+ )
18
+ );
19
+ }
20
+ function getImportPath(absolutePath) {
21
+ return slash(absolutePath);
22
+ }
23
+ function slash(anyPath) {
24
+ const isExtendedLengthPath = anyPath.startsWith("\\\\?\\");
25
+ if (isExtendedLengthPath) {
26
+ return anyPath;
27
+ }
28
+ return anyPath.replaceAll("\\", "/");
29
+ }
30
+ async function globFiles({
31
+ cwd,
32
+ globOptions,
33
+ files
34
+ }) {
35
+ return FastGlob.glob(files, {
36
+ cwd,
37
+ ...globOptions
38
+ }).then((result) => result.map((file) => getAbsolutePath(cwd, file)));
39
+ }
40
+ function getOutputPath({ options }, entry) {
41
+ return path.join(
42
+ options.cwd,
43
+ options.outputDir,
44
+ path.relative(options.cwd, path.dirname(entry.file)),
45
+ `${path.basename(entry.file, path.extname(entry.file))}${options.outputExt}`
46
+ );
47
+ }
48
+
49
+ // src/loader/mdx.ts
50
+ import { createProcessor } from "@mdx-js/mdx";
51
+ import grayMatter from "gray-matter";
52
+
53
+ // src/utils/git-timpstamp.ts
54
+ import path2 from "node:path";
55
+ import fs from "node:fs";
56
+ import { spawn } from "cross-spawn";
57
+ var cache = /* @__PURE__ */ new Map();
58
+ function getGitTimestamp(file) {
59
+ const cachedTimestamp = cache.get(file);
60
+ if (cachedTimestamp) return Promise.resolve(cachedTimestamp);
61
+ return new Promise((resolve, reject) => {
62
+ const cwd = path2.dirname(file);
63
+ if (!fs.existsSync(cwd)) {
64
+ resolve(void 0);
65
+ return;
66
+ }
67
+ const fileName = path2.basename(file);
68
+ const child = spawn("git", ["log", "-1", '--pretty="%ai"', fileName], {
69
+ cwd
70
+ });
71
+ let output;
72
+ child.stdout.on("data", (d) => output = new Date(String(d)));
73
+ child.on("close", () => {
74
+ if (output) cache.set(file, output);
75
+ resolve(output);
76
+ });
77
+ child.on("error", reject);
78
+ });
79
+ }
80
+
81
+ // src/remark-plugins/utils.ts
82
+ import { valueToEstree } from "estree-util-value-to-estree";
83
+ function getMdastExport(name, value) {
84
+ return {
85
+ type: "mdxjsEsm",
86
+ value: "",
87
+ data: {
88
+ estree: {
89
+ type: "Program",
90
+ sourceType: "module",
91
+ body: [
92
+ {
93
+ type: "ExportNamedDeclaration",
94
+ specifiers: [],
95
+ source: null,
96
+ declaration: {
97
+ type: "VariableDeclaration",
98
+ kind: "const",
99
+ declarations: [
100
+ {
101
+ type: "VariableDeclarator",
102
+ id: {
103
+ type: "Identifier",
104
+ name
105
+ },
106
+ init: valueToEstree(value)
107
+ }
108
+ ]
109
+ }
110
+ }
111
+ ]
112
+ }
113
+ }
114
+ };
115
+ }
116
+
117
+ // src/remark-plugins/remark-exports.ts
118
+ function remarkMdxExport({ values }) {
119
+ return (tree, vfile) => {
120
+ for (const name of values) {
121
+ if (!(name in vfile.data)) return;
122
+ tree.children.unshift(getMdastExport(name, vfile.data[name]));
123
+ }
124
+ };
125
+ }
126
+
127
+ // src/remark-plugins/remark-absolute-import.ts
128
+ import * as path3 from "node:path";
129
+ import { visit } from "unist-util-visit";
130
+ function remarkAbsoluteImport({
131
+ compiler,
132
+ transformFormats
133
+ }) {
134
+ return async (tree, vfile) => {
135
+ const transforms = [];
136
+ visit(tree, "mdxjsEsm", (node) => {
137
+ const body = node.data?.estree?.body ?? [];
138
+ for (const statement of body) {
139
+ if (statement.type !== "ImportDeclaration" || typeof statement.source.value !== "string")
140
+ continue;
141
+ const value = statement.source.value;
142
+ if (!value.startsWith("./") && !value.startsWith("../")) continue;
143
+ const file = path3.join(path3.dirname(vfile.path), value);
144
+ if (transformFormats.includes(path3.extname(file).slice(1))) {
145
+ const transform = compiler.compileFile(file).then((entry) => {
146
+ statement.source.value = getImportPath(
147
+ getOutputPath(compiler, entry)
148
+ );
149
+ delete statement.source.raw;
150
+ return entry;
151
+ });
152
+ transforms.push(transform);
153
+ continue;
154
+ }
155
+ const replace = getImportPath(file);
156
+ statement.source.value = replace;
157
+ delete statement.source.raw;
158
+ }
159
+ });
160
+ vfile.data.ctx = { dependencies: await Promise.all(transforms) };
161
+ };
162
+ }
163
+
164
+ // src/loader/mdx.ts
165
+ function pluggable(enable, value) {
166
+ return enable ? [value] : [];
167
+ }
168
+ function getProcessor(compiler, options) {
169
+ if (!options.format) throw new Error("format is required");
170
+ compiler._mdxCache ||= /* @__PURE__ */ new Map();
171
+ let processor = compiler._mdxCache.get(options.format);
172
+ if (!processor) {
173
+ processor = createProcessor(options);
174
+ compiler._mdxCache.set(options.format, processor);
175
+ }
176
+ return processor;
177
+ }
178
+ var loadMDX = ({
179
+ lastModifiedTime,
180
+ format: forceFormat,
181
+ remarkExports = ["frontmatter", "lastModified"],
182
+ enableAbsoluteImport = true,
183
+ ...rest
184
+ } = {}) => {
185
+ return async function transform(file, source) {
186
+ const { content, data: frontmatter } = grayMatter(source);
187
+ const detectedFormat = file.endsWith(".mdx") ? "mdx" : "md";
188
+ const format = forceFormat ?? detectedFormat;
189
+ let timestamp;
190
+ const processor = getProcessor(this, {
191
+ format,
192
+ development: process.env.NODE_ENV === "development",
193
+ ...rest,
194
+ remarkPlugins: [
195
+ ...rest.remarkPlugins ?? [],
196
+ ...pluggable(enableAbsoluteImport, [
197
+ remarkAbsoluteImport,
198
+ {
199
+ compiler: this,
200
+ transformFormats: Object.keys(this.loaders)
201
+ }
202
+ ]),
203
+ [remarkMdxExport, { values: remarkExports }]
204
+ ]
205
+ });
206
+ if (lastModifiedTime === "git")
207
+ timestamp = (await getGitTimestamp(file))?.getTime();
208
+ const vfile = await processor.process({
209
+ value: content,
210
+ path: file,
211
+ data: {
212
+ lastModified: timestamp,
213
+ frontmatter
214
+ }
215
+ });
216
+ return {
217
+ dependencies: vfile.data.ctx.dependencies,
218
+ content: String(vfile),
219
+ _mdx: {
220
+ vfile
221
+ }
222
+ };
223
+ };
224
+ };
225
+
226
+ // src/loader/json.ts
227
+ var loadJson = () => {
228
+ return (_file, source) => {
229
+ const parsed = JSON.parse(source);
230
+ return {
231
+ content: `export default ${JSON.stringify(parsed)}`
232
+ };
233
+ };
234
+ };
235
+
236
+ // src/compiler/emit.ts
237
+ import * as path4 from "node:path";
238
+ import * as fs2 from "node:fs/promises";
239
+ async function emit() {
240
+ const entires = await this.compile();
241
+ const emits = entires.map(async (entry) => this.emitEntry(entry));
242
+ this._emit = await Promise.all(emits);
243
+ }
244
+ async function emitEntry(entry) {
245
+ this._emitCache ||= /* @__PURE__ */ new WeakMap();
246
+ const cached = this._emitCache.get(entry);
247
+ if (cached) return cached;
248
+ const outputPath = getOutputPath(this, entry);
249
+ await fs2.mkdir(path4.dirname(outputPath), { recursive: true });
250
+ await fs2.writeFile(outputPath, entry.content);
251
+ if (entry.dependencies) {
252
+ await Promise.all(entry.dependencies.map((dep) => this.emitEntry(dep)));
253
+ }
254
+ const output = {
255
+ ...entry,
256
+ outputPath
257
+ };
258
+ this._emitCache.set(entry, output);
259
+ return output;
260
+ }
261
+
262
+ // src/compiler/compile.ts
263
+ import * as fs3 from "node:fs/promises";
264
+ import * as path5 from "node:path";
265
+
266
+ // src/loader/entry-point.ts
267
+ function loadEntryPoint(entries) {
268
+ const { mode = "import" } = this.options.entryPoint ?? {};
269
+ let content;
270
+ switch (mode) {
271
+ case "import":
272
+ content = generateImport(this, entries);
273
+ break;
274
+ default:
275
+ content = generateLazy(this, entries);
276
+ break;
277
+ }
278
+ return {
279
+ format: "js",
280
+ file: getAbsolutePath(this.options.cwd, "./index.js"),
281
+ content,
282
+ _entryPoint: {}
283
+ };
284
+ }
285
+ function generateImport(compiler, output) {
286
+ const { fullPath = false } = compiler.options.entryPoint ?? {};
287
+ const formats = /* @__PURE__ */ new Map();
288
+ output.forEach((entry, i) => {
289
+ const b = formats.get(entry.format) ?? { imports: [], entries: [] };
290
+ formats.set(entry.format, b);
291
+ const importPath = getImportPath(getOutputPath(compiler, entry));
292
+ const file = fullPath ? entry.file : getRelativePath(compiler.options.cwd, entry.file);
293
+ const name = `p_${i.toString()}`;
294
+ b.imports.push(`import * as ${name} from ${JSON.stringify(importPath)};`);
295
+ b.entries.push(`{
296
+ ...${name},
297
+ file: ${JSON.stringify(file)},
298
+ }`);
299
+ });
300
+ const imports = Array.from(formats.values()).flatMap((f) => f.imports).join("\n");
301
+ const entires = Array.from(formats.entries()).map(([k, v]) => `${k}: [${v.entries.join(",")}]`).join(",");
302
+ return `${imports}
303
+ export default {${entires}};`;
304
+ }
305
+ function generateLazy(compiler, output) {
306
+ const entries = [];
307
+ for (const entry of output) {
308
+ const fronmatter = entry._mdx ? entry._mdx.vfile.data.frontmatter : {};
309
+ const importPath = getImportPath(getOutputPath(compiler, entry));
310
+ const line = `{
311
+ file: ${JSON.stringify(entry.file)},
312
+ info: ${JSON.stringify(fronmatter)},
313
+ load: () => import(${JSON.stringify(importPath)})
314
+ }`;
315
+ entries.push(line);
316
+ }
317
+ return `export default [${entries.join(",\n")}]`;
318
+ }
319
+
320
+ // src/compiler/compile.ts
321
+ async function compile() {
322
+ const output = [];
323
+ await Promise.all(
324
+ this.files.map(async (file) => {
325
+ const entry = await this.compileFile(file);
326
+ output.push(entry);
327
+ })
328
+ );
329
+ output.push(loadEntryPoint.call(this, output));
330
+ this._output = output;
331
+ return output;
332
+ }
333
+ async function compileFile(file) {
334
+ this._compileCache ||= /* @__PURE__ */ new Map();
335
+ const cache2 = this._compileCache.get(file);
336
+ if (cache2) return cache2;
337
+ const format = path5.extname(file).slice(1);
338
+ const content = (await fs3.readFile(file)).toString();
339
+ const loader = this.loaders[format];
340
+ const output = await loader?.call(this, file, content);
341
+ if (!output) {
342
+ throw new Error(`Unknown format: ${format}`);
343
+ }
344
+ const entry = {
345
+ file,
346
+ format,
347
+ ...output
348
+ };
349
+ this._compileCache.set(file, entry);
350
+ return entry;
351
+ }
352
+ function removeCache(compiler, file) {
353
+ compiler._compileCache?.delete(file);
354
+ }
355
+
356
+ // src/compiler/watch.ts
357
+ import { watch as watchFn } from "chokidar";
358
+ function watch() {
359
+ void this.emit();
360
+ const watcher = watchFn(this.options.files, { cwd: this.options.cwd });
361
+ watcher.on("all", (eventName, relativePath) => {
362
+ const absolutePath = getAbsolutePath(this.options.cwd, relativePath);
363
+ if (eventName === "add" && !this.files.includes(absolutePath)) {
364
+ this.files.push(absolutePath);
365
+ void this.emit();
366
+ }
367
+ if (eventName === "unlink") {
368
+ this.files = this.files.filter((file) => file !== absolutePath);
369
+ removeCache(this, absolutePath);
370
+ void this.emit();
371
+ }
372
+ if (eventName === "change") {
373
+ console.log("update", relativePath);
374
+ removeCache(this, absolutePath);
375
+ void this.compileFile(absolutePath).then(async (entry) => {
376
+ await this.emitEntry(entry);
377
+ });
378
+ }
379
+ });
380
+ return watcher;
381
+ }
382
+
383
+ // src/compiler/index.ts
384
+ var defaultOptions = {
385
+ cwd: process.cwd(),
386
+ outputDir: "./dist",
387
+ outputExt: ".js"
388
+ };
389
+ async function createCompiler(options) {
390
+ const compilerOptions = {
391
+ ...defaultOptions,
392
+ ...options
393
+ };
394
+ const files = await globFiles(compilerOptions);
395
+ return {
396
+ files,
397
+ options: compilerOptions,
398
+ compile,
399
+ emitEntry,
400
+ watch,
401
+ emit,
402
+ compileFile,
403
+ loaders: createLoaders(compilerOptions)
404
+ };
405
+ }
406
+ function createLoaders(options) {
407
+ const mdx = loadMDX(options.mdxOptions);
408
+ return {
409
+ mdx,
410
+ md: mdx,
411
+ json: loadJson(),
412
+ ...options.loaders
413
+ };
414
+ }
8
415
  export {
9
416
  createCompiler,
10
417
  defaultConfig,
11
- defaultConfigPath,
12
418
  loadEntryPoint,
13
419
  loadMDX
14
420
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fuma-content",
3
- "version": "0.0.0",
3
+ "version": "0.0.2",
4
4
  "description": "Write content for web apps",
5
5
  "keywords": [
6
6
  "Content",
@@ -9,7 +9,6 @@
9
9
  "repository": "github:fuma-nama/fuma-content",
10
10
  "license": "MIT",
11
11
  "type": "module",
12
- "bin": "./dist/cli/index.js",
13
12
  "author": "Fuma Nama",
14
13
  "files": [
15
14
  "dist/*"
@@ -36,12 +35,12 @@
36
35
  "dependencies": {
37
36
  "@mdx-js/mdx": "^3.0.0",
38
37
  "chokidar": "^3.5.3",
39
- "clipanion": "4.0.0-rc.3",
40
38
  "cross-spawn": "^7.0.3",
41
39
  "estree-util-value-to-estree": "^3.0.1",
42
40
  "fast-glob": "^3.3.2",
43
41
  "gray-matter": "^4.0.3",
44
42
  "micromatch": "^4.0.5",
43
+ "unist-util-visit": "^5.0.0",
45
44
  "zod": "^3.22.4"
46
45
  },
47
46
  "devDependencies": {
@@ -1,347 +0,0 @@
1
- // src/constants.ts
2
- var defaultConfig = {
3
- files: ["./content/**/*"]
4
- };
5
- var defaultConfigPath = "./fc.config.js";
6
-
7
- // src/loader/mdx.ts
8
- import { createProcessor } from "@mdx-js/mdx";
9
- import grayMatter from "gray-matter";
10
-
11
- // src/utils/git-timpstamp.ts
12
- import path from "node:path";
13
- import fs from "node:fs";
14
- import { spawn } from "cross-spawn";
15
- var cache = /* @__PURE__ */ new Map();
16
- function getGitTimestamp(file) {
17
- const cachedTimestamp = cache.get(file);
18
- if (cachedTimestamp)
19
- return Promise.resolve(cachedTimestamp);
20
- return new Promise((resolve, reject) => {
21
- const cwd = path.dirname(file);
22
- if (!fs.existsSync(cwd)) {
23
- resolve(void 0);
24
- return;
25
- }
26
- const fileName = path.basename(file);
27
- const child = spawn("git", ["log", "-1", '--pretty="%ai"', fileName], {
28
- cwd
29
- });
30
- let output;
31
- child.stdout.on("data", (d) => output = new Date(String(d)));
32
- child.on("close", () => {
33
- if (output)
34
- cache.set(file, output);
35
- resolve(output);
36
- });
37
- child.on("error", reject);
38
- });
39
- }
40
-
41
- // src/remark-plugins/utils.ts
42
- import { valueToEstree } from "estree-util-value-to-estree";
43
- function getMdastExport(name, value) {
44
- return {
45
- type: "mdxjsEsm",
46
- value: "",
47
- data: {
48
- estree: {
49
- type: "Program",
50
- sourceType: "module",
51
- body: [
52
- {
53
- type: "ExportNamedDeclaration",
54
- specifiers: [],
55
- source: null,
56
- declaration: {
57
- type: "VariableDeclaration",
58
- kind: "const",
59
- declarations: [
60
- {
61
- type: "VariableDeclarator",
62
- id: {
63
- type: "Identifier",
64
- name
65
- },
66
- init: valueToEstree(value)
67
- }
68
- ]
69
- }
70
- }
71
- ]
72
- }
73
- }
74
- };
75
- }
76
-
77
- // src/remark-plugins/remark-exports.ts
78
- function remarkMdxExport({ values }) {
79
- return (tree, vfile) => {
80
- for (const name of values) {
81
- if (!(name in vfile.data))
82
- return;
83
- tree.children.unshift(getMdastExport(name, vfile.data[name]));
84
- }
85
- };
86
- }
87
-
88
- // src/loader/mdx.ts
89
- var cache2 = /* @__PURE__ */ new Map();
90
- var loadMDX = ({
91
- lastModifiedTime,
92
- format: forceFormat,
93
- remarkExports = ["frontmatter"],
94
- ...rest
95
- } = {}) => {
96
- return async (filePath, source) => {
97
- const { content, data: frontmatter } = grayMatter(source);
98
- const detectedFormat = filePath.endsWith(".mdx") ? "mdx" : "md";
99
- const format = forceFormat ?? detectedFormat;
100
- let timestamp;
101
- let processor = cache2.get(format);
102
- if (processor === void 0) {
103
- processor = createProcessor({
104
- format,
105
- development: process.env.NODE_ENV === "development",
106
- ...rest,
107
- remarkPlugins: [
108
- ...rest.remarkPlugins ?? [],
109
- [remarkMdxExport, { values: remarkExports }]
110
- ]
111
- });
112
- cache2.set(format, processor);
113
- }
114
- if (lastModifiedTime === "git")
115
- timestamp = (await getGitTimestamp(filePath))?.getTime();
116
- const file = await processor.process({
117
- value: content,
118
- path: filePath,
119
- data: {
120
- lastModified: timestamp,
121
- frontmatter
122
- }
123
- });
124
- return {
125
- content: String(file),
126
- _mdx: {
127
- vfile: file
128
- }
129
- };
130
- };
131
- };
132
-
133
- // src/loader/entry-point.ts
134
- import { pathToFileURL } from "node:url";
135
-
136
- // src/utils/path.ts
137
- import * as path2 from "node:path";
138
- import FastGlob from "fast-glob";
139
- function getAbsolutePath(cwd, relativePath) {
140
- return FastGlob.escapePath(path2.join(cwd, relativePath));
141
- }
142
- function getRelativePath(cwd, absolutePath) {
143
- return path2.join(
144
- path2.relative(cwd, path2.dirname(absolutePath)),
145
- path2.basename(absolutePath)
146
- );
147
- }
148
- async function globFiles({
149
- cwd,
150
- globOptions,
151
- files
152
- }) {
153
- return FastGlob.glob(files, {
154
- cwd,
155
- ...globOptions
156
- }).then((result) => result.map((file) => getAbsolutePath(cwd, file)));
157
- }
158
- function getOutputPath({ options }, entry) {
159
- return path2.join(
160
- options.cwd,
161
- options.outputDir,
162
- path2.relative(options.cwd, path2.dirname(entry.file)),
163
- `${path2.basename(entry.file, path2.extname(entry.file))}${options.outputExt}`
164
- );
165
- }
166
-
167
- // src/loader/entry-point.ts
168
- function loadEntryPoint(entries) {
169
- const { mode = "import" } = this.options.entryPoint ?? {};
170
- let content;
171
- switch (mode) {
172
- case "import":
173
- content = generateImport(this, entries);
174
- break;
175
- default:
176
- content = generateLazy(this, entries);
177
- break;
178
- }
179
- return {
180
- format: "js",
181
- file: getAbsolutePath(this.options.cwd, "./index.js"),
182
- content,
183
- _entryPoint: {}
184
- };
185
- }
186
- function generateImport(compiler, output) {
187
- const { fullPath = false } = compiler.options.entryPoint ?? {};
188
- const formats = /* @__PURE__ */ new Map();
189
- output.forEach((entry, i) => {
190
- const b = formats.get(entry.format) ?? { imports: [], entries: [] };
191
- formats.set(entry.format, b);
192
- const importPath = pathToFileURL(getOutputPath(compiler, entry));
193
- const file = fullPath ? entry.file : getRelativePath(compiler.options.cwd, entry.file);
194
- const name = `p_${i}`;
195
- b.imports.push(`import * as ${name} from ${JSON.stringify(importPath)};`);
196
- b.entries.push(`{
197
- ...${name},
198
- format: ${JSON.stringify(entry.format)},
199
- file: ${JSON.stringify(file)},
200
- }`);
201
- });
202
- const imports = Array.from(formats.values()).flatMap((f) => f.imports).join("\n");
203
- const entires = Array.from(formats.entries()).map(([k, v]) => `${k}: [${v.entries.join(",")}]`).join(",");
204
- return `${imports}
205
- export default {${entires}};`;
206
- }
207
- function generateLazy(compiler, output) {
208
- const entries = [];
209
- for (const entry of output) {
210
- const fronmatter = entry._mdx ? entry._mdx.vfile.data.frontmatter : {};
211
- const importPath = pathToFileURL(getOutputPath(compiler, entry));
212
- const line = `{
213
- file: ${JSON.stringify(entry.file)},
214
- info: ${JSON.stringify(fronmatter)},
215
- load: () => import(${JSON.stringify(importPath)})
216
- }`;
217
- entries.push(line);
218
- }
219
- return `export default [${entries.join(",\n")}]`;
220
- }
221
-
222
- // src/loader/json.ts
223
- var loadJson = () => {
224
- return (_file, source) => {
225
- const parsed = JSON.parse(source);
226
- return {
227
- content: `export default ${JSON.stringify(parsed)}`
228
- };
229
- };
230
- };
231
-
232
- // src/compiler/emit.ts
233
- import * as path3 from "node:path";
234
- import * as fs2 from "node:fs/promises";
235
- async function emit() {
236
- const entires = await this.compile();
237
- const emits = entires.map(async (entry) => this.emitEntry(entry));
238
- this._emit = await Promise.all(emits);
239
- }
240
- async function emitEntry(entry) {
241
- const outputPath = getOutputPath(this, entry);
242
- await fs2.mkdir(path3.dirname(outputPath), { recursive: true });
243
- await fs2.writeFile(outputPath, entry.content);
244
- return {
245
- ...entry,
246
- outputPath
247
- };
248
- }
249
-
250
- // src/compiler/compile.ts
251
- import * as fs3 from "node:fs/promises";
252
- import * as path4 from "node:path";
253
- async function compile() {
254
- this._output = await Promise.all(
255
- this.files.map((file) => this.compileFile(file))
256
- );
257
- this._output.push(loadEntryPoint.call(this, this._output));
258
- return this._output;
259
- }
260
- async function compileFile(file) {
261
- const cache3 = this._cache.get(file);
262
- if (cache3)
263
- return cache3;
264
- const format = path4.extname(file).slice(1);
265
- const content = (await fs3.readFile(file)).toString();
266
- const loader = this.loaders[format];
267
- const output = await loader?.call(this, file, content);
268
- if (!output) {
269
- throw new Error(`Unknown format: ${format}`);
270
- }
271
- const entry = {
272
- file,
273
- format,
274
- ...output
275
- };
276
- this._cache.set(file, entry);
277
- return entry;
278
- }
279
-
280
- // src/compiler/watch.ts
281
- import { watch as watchFn } from "chokidar";
282
- function watch() {
283
- void this.emit();
284
- const watcher = watchFn(this.options.files, { cwd: this.options.cwd });
285
- watcher.on("all", (eventName, path5) => {
286
- const absolutePath = getAbsolutePath(this.options.cwd, path5);
287
- if (eventName === "add" && !this.files.includes(absolutePath)) {
288
- this.files.push(absolutePath);
289
- void this.emit();
290
- }
291
- if (eventName === "unlink") {
292
- this.files = this.files.filter((file) => file !== absolutePath);
293
- this._cache.delete(absolutePath);
294
- void this.emit();
295
- }
296
- if (eventName === "change") {
297
- console.log("update", path5);
298
- this._cache.delete(absolutePath);
299
- void this.compileFile(absolutePath).then(async (entry) => {
300
- await this.emitEntry(entry);
301
- });
302
- }
303
- });
304
- return watcher;
305
- }
306
-
307
- // src/compiler/index.ts
308
- var defaultOptions = {
309
- cwd: process.cwd(),
310
- outputDir: "./dist",
311
- outputExt: ".js"
312
- };
313
- async function createCompiler(options) {
314
- const compilerOptions = {
315
- ...defaultOptions,
316
- ...options
317
- };
318
- const files = await globFiles(compilerOptions);
319
- return {
320
- files,
321
- options: compilerOptions,
322
- compile,
323
- emitEntry,
324
- watch,
325
- emit,
326
- compileFile,
327
- loaders: createLoaders(compilerOptions),
328
- _cache: /* @__PURE__ */ new Map()
329
- };
330
- }
331
- function createLoaders(options) {
332
- const mdx = loadMDX(options.mdxOptions);
333
- return {
334
- mdx,
335
- md: mdx,
336
- json: loadJson(),
337
- ...options.loaders
338
- };
339
- }
340
-
341
- export {
342
- defaultConfig,
343
- defaultConfigPath,
344
- loadMDX,
345
- loadEntryPoint,
346
- createCompiler
347
- };
@@ -1 +0,0 @@
1
- #!/usr/bin/env node
package/dist/cli/index.js DELETED
@@ -1,55 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- createCompiler,
4
- defaultConfig,
5
- defaultConfigPath
6
- } from "../chunk-UDFHC2Y3.js";
7
-
8
- // src/cli/index.ts
9
- import { Cli, Command, Option } from "clipanion";
10
-
11
- // src/utils/load-config.ts
12
- import * as path from "node:path";
13
- import { pathToFileURL } from "node:url";
14
- import * as fs from "node:fs";
15
- async function loadConfig(configFile = defaultConfigPath) {
16
- const configPath = path.resolve(configFile);
17
- if (!fs.existsSync(configPath))
18
- return defaultConfig;
19
- const importPath = pathToFileURL(configPath).href;
20
- const result = await import(`${importPath}?x=${Date.now()}`);
21
- return "default" in result ? result.default : result;
22
- }
23
-
24
- // src/cli/index.ts
25
- var BuildCommand = class extends Command {
26
- static paths = [[`build`]];
27
- config = Option.String({ required: false });
28
- async execute() {
29
- const config = await loadConfig(this.config);
30
- const compiler = await createCompiler(config);
31
- await compiler.emit();
32
- this.context.stdout.write(`Build successful
33
- `);
34
- }
35
- };
36
- var WatchCommand = class extends Command {
37
- static paths = [[`watch`]];
38
- config = Option.String({ required: false });
39
- async execute() {
40
- const config = await loadConfig(this.config);
41
- const compiler = await createCompiler(config);
42
- this.context.stdout.write(`Started server
43
- `);
44
- compiler.watch();
45
- }
46
- };
47
- var [node, app, ...args] = process.argv;
48
- var cli = new Cli({
49
- binaryLabel: `fuma-content-cli`,
50
- binaryName: `${node} ${app}`,
51
- binaryVersion: `1.0.0`
52
- });
53
- cli.register(BuildCommand);
54
- cli.register(WatchCommand);
55
- void cli.runExit(args);