@better-translate/md 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jorge Alvarenga
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @better-translate/md
2
+
3
+ `@better-translate/md` loads localized Markdown and MDX files on top of an existing Better Translate translator. Use it when docs, blog posts, or content pages should follow the same locale setup as your app.
4
+
5
+ Full docs: [better-translate-placeholder.com/en/docs/adapters/md](https://better-translate-placeholder.com/en/docs/adapters/md)
@@ -0,0 +1,236 @@
1
+ // src/types.ts
2
+ var MarkdownDocumentNotFoundError = class extends Error {
3
+ fallbackLocale;
4
+ id;
5
+ lookedUpPaths;
6
+ requestedLocale;
7
+ constructor(options) {
8
+ super(
9
+ `Markdown document "${options.id}" was not found for locale "${options.requestedLocale}" or fallback locale "${options.fallbackLocale}".`
10
+ );
11
+ this.name = "MarkdownDocumentNotFoundError";
12
+ this.id = options.id;
13
+ this.requestedLocale = options.requestedLocale;
14
+ this.fallbackLocale = options.fallbackLocale;
15
+ this.lookedUpPaths = options.lookedUpPaths;
16
+ }
17
+ };
18
+
19
+ // src/collection.ts
20
+ import { compile } from "@mdx-js/mdx";
21
+ import matter from "gray-matter";
22
+ import { access, readdir, readFile } from "fs/promises";
23
+ import { join, posix, relative, resolve } from "path";
24
+ import { unified } from "unified";
25
+ import remarkParse from "remark-parse";
26
+ import remarkRehype from "remark-rehype";
27
+ import rehypeStringify from "rehype-stringify";
28
+ var DEFAULT_EXTENSIONS = [
29
+ ".mdx",
30
+ ".md"
31
+ ];
32
+ function isMarkdownDocumentExtension(value) {
33
+ return value === ".md" || value === ".mdx";
34
+ }
35
+ function normalizeExtensions(extensions) {
36
+ const resolvedExtensions = extensions ?? DEFAULT_EXTENSIONS;
37
+ if (resolvedExtensions.length === 0) {
38
+ throw new Error(
39
+ "Markdown helpers require at least one supported extension."
40
+ );
41
+ }
42
+ const uniqueExtensions = [...new Set(resolvedExtensions)];
43
+ if (!uniqueExtensions.every(isMarkdownDocumentExtension)) {
44
+ throw new Error(
45
+ 'Markdown helpers only support ".md" and ".mdx" extensions.'
46
+ );
47
+ }
48
+ return uniqueExtensions;
49
+ }
50
+ function normalizeDocumentId(documentId) {
51
+ const trimmedDocumentId = documentId.trim();
52
+ if (!trimmedDocumentId) {
53
+ throw new Error("Markdown document ids cannot be empty.");
54
+ }
55
+ const normalizedDocumentId = posix.normalize(trimmedDocumentId.replaceAll("\\", "/").replace(/^\/+/, "")).replace(/\/+$/, "");
56
+ if (normalizedDocumentId === "." || normalizedDocumentId.startsWith("../") || normalizedDocumentId.includes("/../")) {
57
+ throw new Error(
58
+ `Markdown document id "${documentId}" cannot escape the configured rootDir.`
59
+ );
60
+ }
61
+ return normalizedDocumentId;
62
+ }
63
+ async function pathExists(pathname) {
64
+ try {
65
+ await access(pathname);
66
+ return true;
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+ async function walkDirectory(directory) {
72
+ const entries = await readdir(directory, {
73
+ withFileTypes: true
74
+ });
75
+ const files = await Promise.all(
76
+ entries.map(async (entry) => {
77
+ const entryPath = join(directory, entry.name);
78
+ if (entry.isDirectory()) {
79
+ return walkDirectory(entryPath);
80
+ }
81
+ if (entry.isFile()) {
82
+ return [entryPath];
83
+ }
84
+ return [];
85
+ })
86
+ );
87
+ return files.flat();
88
+ }
89
+ function assertSupportedLocale(locale, supportedLocales) {
90
+ if (!supportedLocales.includes(locale)) {
91
+ throw new Error(
92
+ `The locale "${locale}" is not included in the translator's supported locales.`
93
+ );
94
+ }
95
+ }
96
+ async function compileMarkdownDocument(document) {
97
+ if (document.kind === "mdx") {
98
+ const compiled = String(
99
+ await compile(document.source, {
100
+ format: "mdx",
101
+ jsx: true,
102
+ jsxImportSource: "react",
103
+ outputFormat: "program"
104
+ })
105
+ );
106
+ const compiledDocument2 = {
107
+ code: compiled,
108
+ compiled,
109
+ frontmatter: document.frontmatter,
110
+ id: document.id,
111
+ kind: "mdx",
112
+ locale: document.locale,
113
+ path: document.path,
114
+ requestedLocale: document.requestedLocale,
115
+ source: document.source,
116
+ usedFallback: document.usedFallback
117
+ };
118
+ return compiledDocument2;
119
+ }
120
+ const html = String(
121
+ await unified().use(remarkParse).use(remarkRehype).use(rehypeStringify).process(document.source)
122
+ );
123
+ const compiledDocument = {
124
+ compiled: html,
125
+ frontmatter: document.frontmatter,
126
+ html,
127
+ id: document.id,
128
+ kind: "md",
129
+ locale: document.locale,
130
+ path: document.path,
131
+ requestedLocale: document.requestedLocale,
132
+ source: document.source,
133
+ usedFallback: document.usedFallback
134
+ };
135
+ return compiledDocument;
136
+ }
137
+ function createCandidatePaths(rootDir, locale, documentId, extensions) {
138
+ const documentSegments = documentId.split("/");
139
+ const basePath = join(rootDir, locale, ...documentSegments);
140
+ return extensions.map((extension) => ({
141
+ extension,
142
+ path: `${basePath}${extension}`
143
+ }));
144
+ }
145
+ function createMarkdownCollection({
146
+ translator,
147
+ rootDir,
148
+ extensions
149
+ }) {
150
+ const resolvedRootDir = resolve(rootDir);
151
+ const supportedLocales = translator.getSupportedLocales();
152
+ const defaultLocale = translator.defaultLocale;
153
+ const fallbackLocale = translator.fallbackLocale;
154
+ const resolvedExtensions = normalizeExtensions(extensions);
155
+ const listDocuments = async () => {
156
+ const localeDirectory = join(resolvedRootDir, defaultLocale);
157
+ if (!await pathExists(localeDirectory)) {
158
+ return [];
159
+ }
160
+ const files = await walkDirectory(localeDirectory);
161
+ const documentIds = /* @__PURE__ */ new Set();
162
+ for (const filePath of files) {
163
+ const extension = resolvedExtensions.find(
164
+ (candidate) => filePath.endsWith(candidate)
165
+ );
166
+ if (!extension) {
167
+ continue;
168
+ }
169
+ const relativePath = relative(localeDirectory, filePath);
170
+ const normalizedPath = relativePath.split("\\").join("/");
171
+ const documentId = normalizedPath.slice(0, -extension.length);
172
+ documentIds.add(documentId);
173
+ }
174
+ return [...documentIds].sort();
175
+ };
176
+ const getDocument = async (documentId, options) => {
177
+ const normalizedDocumentId = normalizeDocumentId(documentId);
178
+ const requestedLocale = options?.locale ?? defaultLocale;
179
+ assertSupportedLocale(requestedLocale, supportedLocales);
180
+ const localeSearchOrder = requestedLocale === fallbackLocale ? [requestedLocale] : [requestedLocale, fallbackLocale];
181
+ const lookedUpPaths = [];
182
+ for (const locale of localeSearchOrder) {
183
+ const candidatePaths = createCandidatePaths(
184
+ resolvedRootDir,
185
+ locale,
186
+ normalizedDocumentId,
187
+ resolvedExtensions
188
+ );
189
+ for (const candidate of candidatePaths) {
190
+ lookedUpPaths.push(candidate.path);
191
+ if (!await pathExists(candidate.path)) {
192
+ continue;
193
+ }
194
+ const fileContents = await readFile(candidate.path, "utf8");
195
+ const parsedFile = matter(fileContents);
196
+ return {
197
+ frontmatter: parsedFile.data,
198
+ id: normalizedDocumentId,
199
+ kind: candidate.extension === ".mdx" ? "mdx" : "md",
200
+ locale,
201
+ path: candidate.path,
202
+ requestedLocale,
203
+ source: parsedFile.content,
204
+ usedFallback: locale !== requestedLocale
205
+ };
206
+ }
207
+ }
208
+ throw new MarkdownDocumentNotFoundError({
209
+ fallbackLocale,
210
+ id: normalizedDocumentId,
211
+ lookedUpPaths,
212
+ requestedLocale
213
+ });
214
+ };
215
+ async function compileDocument(documentOrId, options) {
216
+ const document = typeof documentOrId === "string" ? await getDocument(documentOrId, options) : documentOrId;
217
+ return compileMarkdownDocument(document);
218
+ }
219
+ return {
220
+ compileDocument,
221
+ getDocument,
222
+ listDocuments
223
+ };
224
+ }
225
+ function createMarkdownHelpers(translator, options) {
226
+ return createMarkdownCollection({
227
+ ...options,
228
+ translator
229
+ });
230
+ }
231
+
232
+ export {
233
+ MarkdownDocumentNotFoundError,
234
+ createMarkdownCollection,
235
+ createMarkdownHelpers
236
+ };
package/dist/index.cjs ADDED
@@ -0,0 +1,276 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ MarkdownDocumentNotFoundError: () => MarkdownDocumentNotFoundError,
34
+ createMarkdownCollection: () => createMarkdownCollection,
35
+ createMarkdownHelpers: () => createMarkdownHelpers
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/collection.ts
40
+ var import_mdx = require("@mdx-js/mdx");
41
+ var import_gray_matter = __toESM(require("gray-matter"), 1);
42
+ var import_promises = require("fs/promises");
43
+ var import_node_path = require("path");
44
+ var import_unified = require("unified");
45
+ var import_remark_parse = __toESM(require("remark-parse"), 1);
46
+ var import_remark_rehype = __toESM(require("remark-rehype"), 1);
47
+ var import_rehype_stringify = __toESM(require("rehype-stringify"), 1);
48
+
49
+ // src/types.ts
50
+ var MarkdownDocumentNotFoundError = class extends Error {
51
+ fallbackLocale;
52
+ id;
53
+ lookedUpPaths;
54
+ requestedLocale;
55
+ constructor(options) {
56
+ super(
57
+ `Markdown document "${options.id}" was not found for locale "${options.requestedLocale}" or fallback locale "${options.fallbackLocale}".`
58
+ );
59
+ this.name = "MarkdownDocumentNotFoundError";
60
+ this.id = options.id;
61
+ this.requestedLocale = options.requestedLocale;
62
+ this.fallbackLocale = options.fallbackLocale;
63
+ this.lookedUpPaths = options.lookedUpPaths;
64
+ }
65
+ };
66
+
67
+ // src/collection.ts
68
+ var DEFAULT_EXTENSIONS = [
69
+ ".mdx",
70
+ ".md"
71
+ ];
72
+ function isMarkdownDocumentExtension(value) {
73
+ return value === ".md" || value === ".mdx";
74
+ }
75
+ function normalizeExtensions(extensions) {
76
+ const resolvedExtensions = extensions ?? DEFAULT_EXTENSIONS;
77
+ if (resolvedExtensions.length === 0) {
78
+ throw new Error(
79
+ "Markdown helpers require at least one supported extension."
80
+ );
81
+ }
82
+ const uniqueExtensions = [...new Set(resolvedExtensions)];
83
+ if (!uniqueExtensions.every(isMarkdownDocumentExtension)) {
84
+ throw new Error(
85
+ 'Markdown helpers only support ".md" and ".mdx" extensions.'
86
+ );
87
+ }
88
+ return uniqueExtensions;
89
+ }
90
+ function normalizeDocumentId(documentId) {
91
+ const trimmedDocumentId = documentId.trim();
92
+ if (!trimmedDocumentId) {
93
+ throw new Error("Markdown document ids cannot be empty.");
94
+ }
95
+ const normalizedDocumentId = import_node_path.posix.normalize(trimmedDocumentId.replaceAll("\\", "/").replace(/^\/+/, "")).replace(/\/+$/, "");
96
+ if (normalizedDocumentId === "." || normalizedDocumentId.startsWith("../") || normalizedDocumentId.includes("/../")) {
97
+ throw new Error(
98
+ `Markdown document id "${documentId}" cannot escape the configured rootDir.`
99
+ );
100
+ }
101
+ return normalizedDocumentId;
102
+ }
103
+ async function pathExists(pathname) {
104
+ try {
105
+ await (0, import_promises.access)(pathname);
106
+ return true;
107
+ } catch {
108
+ return false;
109
+ }
110
+ }
111
+ async function walkDirectory(directory) {
112
+ const entries = await (0, import_promises.readdir)(directory, {
113
+ withFileTypes: true
114
+ });
115
+ const files = await Promise.all(
116
+ entries.map(async (entry) => {
117
+ const entryPath = (0, import_node_path.join)(directory, entry.name);
118
+ if (entry.isDirectory()) {
119
+ return walkDirectory(entryPath);
120
+ }
121
+ if (entry.isFile()) {
122
+ return [entryPath];
123
+ }
124
+ return [];
125
+ })
126
+ );
127
+ return files.flat();
128
+ }
129
+ function assertSupportedLocale(locale, supportedLocales) {
130
+ if (!supportedLocales.includes(locale)) {
131
+ throw new Error(
132
+ `The locale "${locale}" is not included in the translator's supported locales.`
133
+ );
134
+ }
135
+ }
136
+ async function compileMarkdownDocument(document) {
137
+ if (document.kind === "mdx") {
138
+ const compiled = String(
139
+ await (0, import_mdx.compile)(document.source, {
140
+ format: "mdx",
141
+ jsx: true,
142
+ jsxImportSource: "react",
143
+ outputFormat: "program"
144
+ })
145
+ );
146
+ const compiledDocument2 = {
147
+ code: compiled,
148
+ compiled,
149
+ frontmatter: document.frontmatter,
150
+ id: document.id,
151
+ kind: "mdx",
152
+ locale: document.locale,
153
+ path: document.path,
154
+ requestedLocale: document.requestedLocale,
155
+ source: document.source,
156
+ usedFallback: document.usedFallback
157
+ };
158
+ return compiledDocument2;
159
+ }
160
+ const html = String(
161
+ await (0, import_unified.unified)().use(import_remark_parse.default).use(import_remark_rehype.default).use(import_rehype_stringify.default).process(document.source)
162
+ );
163
+ const compiledDocument = {
164
+ compiled: html,
165
+ frontmatter: document.frontmatter,
166
+ html,
167
+ id: document.id,
168
+ kind: "md",
169
+ locale: document.locale,
170
+ path: document.path,
171
+ requestedLocale: document.requestedLocale,
172
+ source: document.source,
173
+ usedFallback: document.usedFallback
174
+ };
175
+ return compiledDocument;
176
+ }
177
+ function createCandidatePaths(rootDir, locale, documentId, extensions) {
178
+ const documentSegments = documentId.split("/");
179
+ const basePath = (0, import_node_path.join)(rootDir, locale, ...documentSegments);
180
+ return extensions.map((extension) => ({
181
+ extension,
182
+ path: `${basePath}${extension}`
183
+ }));
184
+ }
185
+ function createMarkdownCollection({
186
+ translator,
187
+ rootDir,
188
+ extensions
189
+ }) {
190
+ const resolvedRootDir = (0, import_node_path.resolve)(rootDir);
191
+ const supportedLocales = translator.getSupportedLocales();
192
+ const defaultLocale = translator.defaultLocale;
193
+ const fallbackLocale = translator.fallbackLocale;
194
+ const resolvedExtensions = normalizeExtensions(extensions);
195
+ const listDocuments = async () => {
196
+ const localeDirectory = (0, import_node_path.join)(resolvedRootDir, defaultLocale);
197
+ if (!await pathExists(localeDirectory)) {
198
+ return [];
199
+ }
200
+ const files = await walkDirectory(localeDirectory);
201
+ const documentIds = /* @__PURE__ */ new Set();
202
+ for (const filePath of files) {
203
+ const extension = resolvedExtensions.find(
204
+ (candidate) => filePath.endsWith(candidate)
205
+ );
206
+ if (!extension) {
207
+ continue;
208
+ }
209
+ const relativePath = (0, import_node_path.relative)(localeDirectory, filePath);
210
+ const normalizedPath = relativePath.split("\\").join("/");
211
+ const documentId = normalizedPath.slice(0, -extension.length);
212
+ documentIds.add(documentId);
213
+ }
214
+ return [...documentIds].sort();
215
+ };
216
+ const getDocument = async (documentId, options) => {
217
+ const normalizedDocumentId = normalizeDocumentId(documentId);
218
+ const requestedLocale = options?.locale ?? defaultLocale;
219
+ assertSupportedLocale(requestedLocale, supportedLocales);
220
+ const localeSearchOrder = requestedLocale === fallbackLocale ? [requestedLocale] : [requestedLocale, fallbackLocale];
221
+ const lookedUpPaths = [];
222
+ for (const locale of localeSearchOrder) {
223
+ const candidatePaths = createCandidatePaths(
224
+ resolvedRootDir,
225
+ locale,
226
+ normalizedDocumentId,
227
+ resolvedExtensions
228
+ );
229
+ for (const candidate of candidatePaths) {
230
+ lookedUpPaths.push(candidate.path);
231
+ if (!await pathExists(candidate.path)) {
232
+ continue;
233
+ }
234
+ const fileContents = await (0, import_promises.readFile)(candidate.path, "utf8");
235
+ const parsedFile = (0, import_gray_matter.default)(fileContents);
236
+ return {
237
+ frontmatter: parsedFile.data,
238
+ id: normalizedDocumentId,
239
+ kind: candidate.extension === ".mdx" ? "mdx" : "md",
240
+ locale,
241
+ path: candidate.path,
242
+ requestedLocale,
243
+ source: parsedFile.content,
244
+ usedFallback: locale !== requestedLocale
245
+ };
246
+ }
247
+ }
248
+ throw new MarkdownDocumentNotFoundError({
249
+ fallbackLocale,
250
+ id: normalizedDocumentId,
251
+ lookedUpPaths,
252
+ requestedLocale
253
+ });
254
+ };
255
+ async function compileDocument(documentOrId, options) {
256
+ const document = typeof documentOrId === "string" ? await getDocument(documentOrId, options) : documentOrId;
257
+ return compileMarkdownDocument(document);
258
+ }
259
+ return {
260
+ compileDocument,
261
+ getDocument,
262
+ listDocuments
263
+ };
264
+ }
265
+ function createMarkdownHelpers(translator, options) {
266
+ return createMarkdownCollection({
267
+ ...options,
268
+ translator
269
+ });
270
+ }
271
+ // Annotate the CommonJS export names for ESM import in node:
272
+ 0 && (module.exports = {
273
+ MarkdownDocumentNotFoundError,
274
+ createMarkdownCollection,
275
+ createMarkdownHelpers
276
+ });
@@ -0,0 +1,8 @@
1
+ import { A as AnyBetterTranslateTranslator, M as MarkdownCollectionConfig, a as MarkdownCollection, I as InferLocale, b as MarkdownHelpersOptions } from './types-OuJ3t7i_.cjs';
2
+ export { C as CompiledMarkdownHtmlDocument, c as CompiledMarkdownMdxDocument, d as CompiledMarkdownResult, L as LocalizedMarkdownDocument, e as MarkdownDocumentExtension, f as MarkdownDocumentNotFoundError, g as MarkdownDocumentOptions, h as MarkdownServerHelpers } from './types-OuJ3t7i_.cjs';
3
+ import '@better-translate/core';
4
+
5
+ declare function createMarkdownCollection<TTranslator extends AnyBetterTranslateTranslator>({ translator, rootDir, extensions, }: MarkdownCollectionConfig<TTranslator>): MarkdownCollection<InferLocale<TTranslator>>;
6
+ declare function createMarkdownHelpers<TTranslator extends AnyBetterTranslateTranslator>(translator: TTranslator, options: MarkdownHelpersOptions): MarkdownCollection<InferLocale<TTranslator>>;
7
+
8
+ export { AnyBetterTranslateTranslator, InferLocale, MarkdownCollection, MarkdownCollectionConfig, MarkdownHelpersOptions, createMarkdownCollection, createMarkdownHelpers };
@@ -0,0 +1,8 @@
1
+ import { A as AnyBetterTranslateTranslator, M as MarkdownCollectionConfig, a as MarkdownCollection, I as InferLocale, b as MarkdownHelpersOptions } from './types-OuJ3t7i_.js';
2
+ export { C as CompiledMarkdownHtmlDocument, c as CompiledMarkdownMdxDocument, d as CompiledMarkdownResult, L as LocalizedMarkdownDocument, e as MarkdownDocumentExtension, f as MarkdownDocumentNotFoundError, g as MarkdownDocumentOptions, h as MarkdownServerHelpers } from './types-OuJ3t7i_.js';
3
+ import '@better-translate/core';
4
+
5
+ declare function createMarkdownCollection<TTranslator extends AnyBetterTranslateTranslator>({ translator, rootDir, extensions, }: MarkdownCollectionConfig<TTranslator>): MarkdownCollection<InferLocale<TTranslator>>;
6
+ declare function createMarkdownHelpers<TTranslator extends AnyBetterTranslateTranslator>(translator: TTranslator, options: MarkdownHelpersOptions): MarkdownCollection<InferLocale<TTranslator>>;
7
+
8
+ export { AnyBetterTranslateTranslator, InferLocale, MarkdownCollection, MarkdownCollectionConfig, MarkdownHelpersOptions, createMarkdownCollection, createMarkdownHelpers };
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ import {
2
+ MarkdownDocumentNotFoundError,
3
+ createMarkdownCollection,
4
+ createMarkdownHelpers
5
+ } from "./chunk-ADG3GJBA.js";
6
+ export {
7
+ MarkdownDocumentNotFoundError,
8
+ createMarkdownCollection,
9
+ createMarkdownHelpers
10
+ };
@@ -0,0 +1,345 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/server.ts
31
+ var server_exports = {};
32
+ __export(server_exports, {
33
+ createMarkdownServerHelpers: () => createMarkdownServerHelpers
34
+ });
35
+ module.exports = __toCommonJS(server_exports);
36
+ var import_react = require("react");
37
+ var import_server = require("@better-translate/core/server");
38
+
39
+ // src/collection.ts
40
+ var import_mdx = require("@mdx-js/mdx");
41
+ var import_gray_matter = __toESM(require("gray-matter"), 1);
42
+ var import_promises = require("fs/promises");
43
+ var import_node_path = require("path");
44
+ var import_unified = require("unified");
45
+ var import_remark_parse = __toESM(require("remark-parse"), 1);
46
+ var import_remark_rehype = __toESM(require("remark-rehype"), 1);
47
+ var import_rehype_stringify = __toESM(require("rehype-stringify"), 1);
48
+
49
+ // src/types.ts
50
+ var MarkdownDocumentNotFoundError = class extends Error {
51
+ fallbackLocale;
52
+ id;
53
+ lookedUpPaths;
54
+ requestedLocale;
55
+ constructor(options) {
56
+ super(
57
+ `Markdown document "${options.id}" was not found for locale "${options.requestedLocale}" or fallback locale "${options.fallbackLocale}".`
58
+ );
59
+ this.name = "MarkdownDocumentNotFoundError";
60
+ this.id = options.id;
61
+ this.requestedLocale = options.requestedLocale;
62
+ this.fallbackLocale = options.fallbackLocale;
63
+ this.lookedUpPaths = options.lookedUpPaths;
64
+ }
65
+ };
66
+
67
+ // src/collection.ts
68
+ var DEFAULT_EXTENSIONS = [
69
+ ".mdx",
70
+ ".md"
71
+ ];
72
+ function isMarkdownDocumentExtension(value) {
73
+ return value === ".md" || value === ".mdx";
74
+ }
75
+ function normalizeExtensions(extensions) {
76
+ const resolvedExtensions = extensions ?? DEFAULT_EXTENSIONS;
77
+ if (resolvedExtensions.length === 0) {
78
+ throw new Error(
79
+ "Markdown helpers require at least one supported extension."
80
+ );
81
+ }
82
+ const uniqueExtensions = [...new Set(resolvedExtensions)];
83
+ if (!uniqueExtensions.every(isMarkdownDocumentExtension)) {
84
+ throw new Error(
85
+ 'Markdown helpers only support ".md" and ".mdx" extensions.'
86
+ );
87
+ }
88
+ return uniqueExtensions;
89
+ }
90
+ function normalizeDocumentId(documentId) {
91
+ const trimmedDocumentId = documentId.trim();
92
+ if (!trimmedDocumentId) {
93
+ throw new Error("Markdown document ids cannot be empty.");
94
+ }
95
+ const normalizedDocumentId = import_node_path.posix.normalize(trimmedDocumentId.replaceAll("\\", "/").replace(/^\/+/, "")).replace(/\/+$/, "");
96
+ if (normalizedDocumentId === "." || normalizedDocumentId.startsWith("../") || normalizedDocumentId.includes("/../")) {
97
+ throw new Error(
98
+ `Markdown document id "${documentId}" cannot escape the configured rootDir.`
99
+ );
100
+ }
101
+ return normalizedDocumentId;
102
+ }
103
+ async function pathExists(pathname) {
104
+ try {
105
+ await (0, import_promises.access)(pathname);
106
+ return true;
107
+ } catch {
108
+ return false;
109
+ }
110
+ }
111
+ async function walkDirectory(directory) {
112
+ const entries = await (0, import_promises.readdir)(directory, {
113
+ withFileTypes: true
114
+ });
115
+ const files = await Promise.all(
116
+ entries.map(async (entry) => {
117
+ const entryPath = (0, import_node_path.join)(directory, entry.name);
118
+ if (entry.isDirectory()) {
119
+ return walkDirectory(entryPath);
120
+ }
121
+ if (entry.isFile()) {
122
+ return [entryPath];
123
+ }
124
+ return [];
125
+ })
126
+ );
127
+ return files.flat();
128
+ }
129
+ function assertSupportedLocale(locale, supportedLocales) {
130
+ if (!supportedLocales.includes(locale)) {
131
+ throw new Error(
132
+ `The locale "${locale}" is not included in the translator's supported locales.`
133
+ );
134
+ }
135
+ }
136
+ async function compileMarkdownDocument(document) {
137
+ if (document.kind === "mdx") {
138
+ const compiled = String(
139
+ await (0, import_mdx.compile)(document.source, {
140
+ format: "mdx",
141
+ jsx: true,
142
+ jsxImportSource: "react",
143
+ outputFormat: "program"
144
+ })
145
+ );
146
+ const compiledDocument2 = {
147
+ code: compiled,
148
+ compiled,
149
+ frontmatter: document.frontmatter,
150
+ id: document.id,
151
+ kind: "mdx",
152
+ locale: document.locale,
153
+ path: document.path,
154
+ requestedLocale: document.requestedLocale,
155
+ source: document.source,
156
+ usedFallback: document.usedFallback
157
+ };
158
+ return compiledDocument2;
159
+ }
160
+ const html = String(
161
+ await (0, import_unified.unified)().use(import_remark_parse.default).use(import_remark_rehype.default).use(import_rehype_stringify.default).process(document.source)
162
+ );
163
+ const compiledDocument = {
164
+ compiled: html,
165
+ frontmatter: document.frontmatter,
166
+ html,
167
+ id: document.id,
168
+ kind: "md",
169
+ locale: document.locale,
170
+ path: document.path,
171
+ requestedLocale: document.requestedLocale,
172
+ source: document.source,
173
+ usedFallback: document.usedFallback
174
+ };
175
+ return compiledDocument;
176
+ }
177
+ function createCandidatePaths(rootDir, locale, documentId, extensions) {
178
+ const documentSegments = documentId.split("/");
179
+ const basePath = (0, import_node_path.join)(rootDir, locale, ...documentSegments);
180
+ return extensions.map((extension) => ({
181
+ extension,
182
+ path: `${basePath}${extension}`
183
+ }));
184
+ }
185
+ function createMarkdownCollection({
186
+ translator,
187
+ rootDir,
188
+ extensions
189
+ }) {
190
+ const resolvedRootDir = (0, import_node_path.resolve)(rootDir);
191
+ const supportedLocales = translator.getSupportedLocales();
192
+ const defaultLocale = translator.defaultLocale;
193
+ const fallbackLocale = translator.fallbackLocale;
194
+ const resolvedExtensions = normalizeExtensions(extensions);
195
+ const listDocuments = async () => {
196
+ const localeDirectory = (0, import_node_path.join)(resolvedRootDir, defaultLocale);
197
+ if (!await pathExists(localeDirectory)) {
198
+ return [];
199
+ }
200
+ const files = await walkDirectory(localeDirectory);
201
+ const documentIds = /* @__PURE__ */ new Set();
202
+ for (const filePath of files) {
203
+ const extension = resolvedExtensions.find(
204
+ (candidate) => filePath.endsWith(candidate)
205
+ );
206
+ if (!extension) {
207
+ continue;
208
+ }
209
+ const relativePath = (0, import_node_path.relative)(localeDirectory, filePath);
210
+ const normalizedPath = relativePath.split("\\").join("/");
211
+ const documentId = normalizedPath.slice(0, -extension.length);
212
+ documentIds.add(documentId);
213
+ }
214
+ return [...documentIds].sort();
215
+ };
216
+ const getDocument = async (documentId, options) => {
217
+ const normalizedDocumentId = normalizeDocumentId(documentId);
218
+ const requestedLocale = options?.locale ?? defaultLocale;
219
+ assertSupportedLocale(requestedLocale, supportedLocales);
220
+ const localeSearchOrder = requestedLocale === fallbackLocale ? [requestedLocale] : [requestedLocale, fallbackLocale];
221
+ const lookedUpPaths = [];
222
+ for (const locale of localeSearchOrder) {
223
+ const candidatePaths = createCandidatePaths(
224
+ resolvedRootDir,
225
+ locale,
226
+ normalizedDocumentId,
227
+ resolvedExtensions
228
+ );
229
+ for (const candidate of candidatePaths) {
230
+ lookedUpPaths.push(candidate.path);
231
+ if (!await pathExists(candidate.path)) {
232
+ continue;
233
+ }
234
+ const fileContents = await (0, import_promises.readFile)(candidate.path, "utf8");
235
+ const parsedFile = (0, import_gray_matter.default)(fileContents);
236
+ return {
237
+ frontmatter: parsedFile.data,
238
+ id: normalizedDocumentId,
239
+ kind: candidate.extension === ".mdx" ? "mdx" : "md",
240
+ locale,
241
+ path: candidate.path,
242
+ requestedLocale,
243
+ source: parsedFile.content,
244
+ usedFallback: locale !== requestedLocale
245
+ };
246
+ }
247
+ }
248
+ throw new MarkdownDocumentNotFoundError({
249
+ fallbackLocale,
250
+ id: normalizedDocumentId,
251
+ lookedUpPaths,
252
+ requestedLocale
253
+ });
254
+ };
255
+ async function compileDocument(documentOrId, options) {
256
+ const document = typeof documentOrId === "string" ? await getDocument(documentOrId, options) : documentOrId;
257
+ return compileMarkdownDocument(document);
258
+ }
259
+ return {
260
+ compileDocument,
261
+ getDocument,
262
+ listDocuments
263
+ };
264
+ }
265
+
266
+ // src/server.ts
267
+ function createMarkdownServerHelpers(requestConfig, options) {
268
+ const readRequestConfig = (0, import_react.cache)(async () => {
269
+ const resolved = await requestConfig();
270
+ const translator = resolved.translator;
271
+ return {
272
+ locale: resolved.locale,
273
+ translator
274
+ };
275
+ });
276
+ const readCollection = (0, import_react.cache)(async () => {
277
+ const { translator } = await readRequestConfig();
278
+ return createMarkdownCollection({
279
+ ...options,
280
+ translator
281
+ });
282
+ });
283
+ async function getCollection() {
284
+ return await readCollection();
285
+ }
286
+ async function getResolvedLocale(options2) {
287
+ const { locale: configLocale, translator } = await readRequestConfig();
288
+ const locale = options2 && "config" in options2 ? options2.config?.locale ?? options2.locale : options2?.locale;
289
+ return (0, import_server.resolveRequestLocale)(translator, {
290
+ locale,
291
+ requestLocale: (0, import_server.getRequestLocale)(),
292
+ configLocale
293
+ });
294
+ }
295
+ async function getDirection(options2) {
296
+ const [{ translator }, locale] = await Promise.all([
297
+ readRequestConfig(),
298
+ getResolvedLocale(options2)
299
+ ]);
300
+ return translator.getDirection({
301
+ config: typeof options2?.config?.rtl === "boolean" ? {
302
+ rtl: options2.config.rtl
303
+ } : void 0,
304
+ locale
305
+ });
306
+ }
307
+ async function isRtl(options2) {
308
+ return await getDirection(options2) === "rtl";
309
+ }
310
+ async function getDocument(documentId, requestOptions) {
311
+ const [locale, collection] = await Promise.all([
312
+ getResolvedLocale(requestOptions),
313
+ readCollection()
314
+ ]);
315
+ return collection.getDocument(documentId, {
316
+ locale
317
+ });
318
+ }
319
+ async function compileDocument(documentOrId, requestOptions) {
320
+ if (typeof documentOrId !== "string") {
321
+ return (await readCollection()).compileDocument(documentOrId);
322
+ }
323
+ const [locale, collection] = await Promise.all([
324
+ getResolvedLocale(requestOptions),
325
+ readCollection()
326
+ ]);
327
+ return collection.compileDocument(documentOrId, {
328
+ locale
329
+ });
330
+ }
331
+ return {
332
+ compileDocument,
333
+ getCollection,
334
+ async getAvailableLanguages() {
335
+ return (await readRequestConfig()).translator.getAvailableLanguages();
336
+ },
337
+ getDirection,
338
+ getDocument,
339
+ isRtl
340
+ };
341
+ }
342
+ // Annotate the CommonJS export names for ESM import in node:
343
+ 0 && (module.exports = {
344
+ createMarkdownServerHelpers
345
+ });
@@ -0,0 +1,12 @@
1
+ import { ConfiguredTranslator, TranslationMessages } from '@better-translate/core';
2
+ import { I as InferLocale, b as MarkdownHelpersOptions, h as MarkdownServerHelpers } from './types-OuJ3t7i_.cjs';
3
+
4
+ type AnyTranslator = ConfiguredTranslator<any, TranslationMessages>;
5
+ type RequestConfig<TTranslator extends AnyTranslator, TLocale extends InferLocale<TTranslator> = InferLocale<TTranslator>> = {
6
+ locale?: TLocale;
7
+ translator: TTranslator;
8
+ };
9
+ type RequestConfigFactory<TTranslator extends AnyTranslator, TLocale extends InferLocale<TTranslator> = InferLocale<TTranslator>> = () => RequestConfig<TTranslator, TLocale> | Promise<RequestConfig<TTranslator, TLocale>>;
10
+ declare function createMarkdownServerHelpers<TTranslator extends AnyTranslator, TLocale extends InferLocale<TTranslator> = InferLocale<TTranslator>>(requestConfig: RequestConfigFactory<TTranslator, TLocale>, options: MarkdownHelpersOptions): MarkdownServerHelpers<TLocale>;
11
+
12
+ export { type RequestConfig, type RequestConfigFactory, createMarkdownServerHelpers };
@@ -0,0 +1,12 @@
1
+ import { ConfiguredTranslator, TranslationMessages } from '@better-translate/core';
2
+ import { I as InferLocale, b as MarkdownHelpersOptions, h as MarkdownServerHelpers } from './types-OuJ3t7i_.js';
3
+
4
+ type AnyTranslator = ConfiguredTranslator<any, TranslationMessages>;
5
+ type RequestConfig<TTranslator extends AnyTranslator, TLocale extends InferLocale<TTranslator> = InferLocale<TTranslator>> = {
6
+ locale?: TLocale;
7
+ translator: TTranslator;
8
+ };
9
+ type RequestConfigFactory<TTranslator extends AnyTranslator, TLocale extends InferLocale<TTranslator> = InferLocale<TTranslator>> = () => RequestConfig<TTranslator, TLocale> | Promise<RequestConfig<TTranslator, TLocale>>;
10
+ declare function createMarkdownServerHelpers<TTranslator extends AnyTranslator, TLocale extends InferLocale<TTranslator> = InferLocale<TTranslator>>(requestConfig: RequestConfigFactory<TTranslator, TLocale>, options: MarkdownHelpersOptions): MarkdownServerHelpers<TLocale>;
11
+
12
+ export { type RequestConfig, type RequestConfigFactory, createMarkdownServerHelpers };
package/dist/server.js ADDED
@@ -0,0 +1,88 @@
1
+ import {
2
+ createMarkdownCollection
3
+ } from "./chunk-ADG3GJBA.js";
4
+
5
+ // src/server.ts
6
+ import { cache } from "react";
7
+ import {
8
+ getRequestLocale as getStoredRequestLocale,
9
+ resolveRequestLocale
10
+ } from "@better-translate/core/server";
11
+ function createMarkdownServerHelpers(requestConfig, options) {
12
+ const readRequestConfig = cache(async () => {
13
+ const resolved = await requestConfig();
14
+ const translator = resolved.translator;
15
+ return {
16
+ locale: resolved.locale,
17
+ translator
18
+ };
19
+ });
20
+ const readCollection = cache(async () => {
21
+ const { translator } = await readRequestConfig();
22
+ return createMarkdownCollection({
23
+ ...options,
24
+ translator
25
+ });
26
+ });
27
+ async function getCollection() {
28
+ return await readCollection();
29
+ }
30
+ async function getResolvedLocale(options2) {
31
+ const { locale: configLocale, translator } = await readRequestConfig();
32
+ const locale = options2 && "config" in options2 ? options2.config?.locale ?? options2.locale : options2?.locale;
33
+ return resolveRequestLocale(translator, {
34
+ locale,
35
+ requestLocale: getStoredRequestLocale(),
36
+ configLocale
37
+ });
38
+ }
39
+ async function getDirection(options2) {
40
+ const [{ translator }, locale] = await Promise.all([
41
+ readRequestConfig(),
42
+ getResolvedLocale(options2)
43
+ ]);
44
+ return translator.getDirection({
45
+ config: typeof options2?.config?.rtl === "boolean" ? {
46
+ rtl: options2.config.rtl
47
+ } : void 0,
48
+ locale
49
+ });
50
+ }
51
+ async function isRtl(options2) {
52
+ return await getDirection(options2) === "rtl";
53
+ }
54
+ async function getDocument(documentId, requestOptions) {
55
+ const [locale, collection] = await Promise.all([
56
+ getResolvedLocale(requestOptions),
57
+ readCollection()
58
+ ]);
59
+ return collection.getDocument(documentId, {
60
+ locale
61
+ });
62
+ }
63
+ async function compileDocument(documentOrId, requestOptions) {
64
+ if (typeof documentOrId !== "string") {
65
+ return (await readCollection()).compileDocument(documentOrId);
66
+ }
67
+ const [locale, collection] = await Promise.all([
68
+ getResolvedLocale(requestOptions),
69
+ readCollection()
70
+ ]);
71
+ return collection.compileDocument(documentOrId, {
72
+ locale
73
+ });
74
+ }
75
+ return {
76
+ compileDocument,
77
+ getCollection,
78
+ async getAvailableLanguages() {
79
+ return (await readRequestConfig()).translator.getAvailableLanguages();
80
+ },
81
+ getDirection,
82
+ getDocument,
83
+ isRtl
84
+ };
85
+ }
86
+ export {
87
+ createMarkdownServerHelpers
88
+ };
@@ -0,0 +1,70 @@
1
+ import { ConfiguredTranslator, TranslationMessages, TranslationLanguageMetadata, TranslationConfig, TranslationDirection } from '@better-translate/core';
2
+
3
+ type AnyBetterTranslateTranslator = ConfiguredTranslator<any, TranslationMessages>;
4
+ type InferLocale<TTranslator extends AnyBetterTranslateTranslator> = TTranslator extends ConfiguredTranslator<infer TLocale, TranslationMessages> ? TLocale : never;
5
+ type MarkdownDocumentExtension = ".md" | ".mdx";
6
+ interface MarkdownHelpersOptions {
7
+ rootDir: string;
8
+ extensions?: readonly MarkdownDocumentExtension[];
9
+ }
10
+ interface MarkdownCollectionConfig<TTranslator extends AnyBetterTranslateTranslator> extends MarkdownHelpersOptions {
11
+ translator: TTranslator;
12
+ }
13
+ interface MarkdownDocumentOptions<TLocale extends string> {
14
+ locale?: TLocale;
15
+ }
16
+ interface MarkdownDirectionOptions<TLocale extends string> {
17
+ locale?: TLocale;
18
+ config?: TranslationConfig<TLocale>;
19
+ }
20
+ interface LocalizedMarkdownDocument<TLocale extends string> {
21
+ frontmatter: Record<string, unknown>;
22
+ id: string;
23
+ kind: "md" | "mdx";
24
+ locale: TLocale;
25
+ path: string;
26
+ requestedLocale: TLocale;
27
+ source: string;
28
+ usedFallback: boolean;
29
+ }
30
+ interface CompiledMarkdownDocumentBase<TLocale extends string> extends LocalizedMarkdownDocument<TLocale> {
31
+ compiled: string;
32
+ }
33
+ interface CompiledMarkdownHtmlDocument<TLocale extends string> extends CompiledMarkdownDocumentBase<TLocale> {
34
+ html: string;
35
+ kind: "md";
36
+ }
37
+ interface CompiledMarkdownMdxDocument<TLocale extends string> extends CompiledMarkdownDocumentBase<TLocale> {
38
+ code: string;
39
+ kind: "mdx";
40
+ }
41
+ type CompiledMarkdownResult<TLocale extends string = string> = CompiledMarkdownHtmlDocument<TLocale> | CompiledMarkdownMdxDocument<TLocale>;
42
+ interface MarkdownCollection<TLocale extends string> {
43
+ compileDocument(documentId: string, options?: MarkdownDocumentOptions<TLocale>): Promise<CompiledMarkdownResult<TLocale>>;
44
+ compileDocument(document: LocalizedMarkdownDocument<TLocale>): Promise<CompiledMarkdownResult<TLocale>>;
45
+ getDocument(documentId: string, options?: MarkdownDocumentOptions<TLocale>): Promise<LocalizedMarkdownDocument<TLocale>>;
46
+ listDocuments(): Promise<string[]>;
47
+ }
48
+ interface MarkdownServerHelpers<TLocale extends string> {
49
+ compileDocument(documentId: string, options?: MarkdownDocumentOptions<TLocale>): Promise<CompiledMarkdownResult<TLocale>>;
50
+ compileDocument(document: LocalizedMarkdownDocument<TLocale>): Promise<CompiledMarkdownResult<TLocale>>;
51
+ getCollection(): Promise<MarkdownCollection<TLocale>>;
52
+ getAvailableLanguages(): Promise<readonly TranslationLanguageMetadata<TLocale>[]>;
53
+ getDirection(options?: MarkdownDirectionOptions<TLocale>): Promise<TranslationDirection>;
54
+ getDocument(documentId: string, options?: MarkdownDocumentOptions<TLocale>): Promise<LocalizedMarkdownDocument<TLocale>>;
55
+ isRtl(options?: MarkdownDirectionOptions<TLocale>): Promise<boolean>;
56
+ }
57
+ declare class MarkdownDocumentNotFoundError extends Error {
58
+ readonly fallbackLocale: string;
59
+ readonly id: string;
60
+ readonly lookedUpPaths: readonly string[];
61
+ readonly requestedLocale: string;
62
+ constructor(options: {
63
+ fallbackLocale: string;
64
+ id: string;
65
+ lookedUpPaths: readonly string[];
66
+ requestedLocale: string;
67
+ });
68
+ }
69
+
70
+ export { type AnyBetterTranslateTranslator as A, type CompiledMarkdownHtmlDocument as C, type InferLocale as I, type LocalizedMarkdownDocument as L, type MarkdownCollectionConfig as M, type MarkdownCollection as a, type MarkdownHelpersOptions as b, type CompiledMarkdownMdxDocument as c, type CompiledMarkdownResult as d, type MarkdownDocumentExtension as e, MarkdownDocumentNotFoundError as f, type MarkdownDocumentOptions as g, type MarkdownServerHelpers as h };
@@ -0,0 +1,70 @@
1
+ import { ConfiguredTranslator, TranslationMessages, TranslationLanguageMetadata, TranslationConfig, TranslationDirection } from '@better-translate/core';
2
+
3
+ type AnyBetterTranslateTranslator = ConfiguredTranslator<any, TranslationMessages>;
4
+ type InferLocale<TTranslator extends AnyBetterTranslateTranslator> = TTranslator extends ConfiguredTranslator<infer TLocale, TranslationMessages> ? TLocale : never;
5
+ type MarkdownDocumentExtension = ".md" | ".mdx";
6
+ interface MarkdownHelpersOptions {
7
+ rootDir: string;
8
+ extensions?: readonly MarkdownDocumentExtension[];
9
+ }
10
+ interface MarkdownCollectionConfig<TTranslator extends AnyBetterTranslateTranslator> extends MarkdownHelpersOptions {
11
+ translator: TTranslator;
12
+ }
13
+ interface MarkdownDocumentOptions<TLocale extends string> {
14
+ locale?: TLocale;
15
+ }
16
+ interface MarkdownDirectionOptions<TLocale extends string> {
17
+ locale?: TLocale;
18
+ config?: TranslationConfig<TLocale>;
19
+ }
20
+ interface LocalizedMarkdownDocument<TLocale extends string> {
21
+ frontmatter: Record<string, unknown>;
22
+ id: string;
23
+ kind: "md" | "mdx";
24
+ locale: TLocale;
25
+ path: string;
26
+ requestedLocale: TLocale;
27
+ source: string;
28
+ usedFallback: boolean;
29
+ }
30
+ interface CompiledMarkdownDocumentBase<TLocale extends string> extends LocalizedMarkdownDocument<TLocale> {
31
+ compiled: string;
32
+ }
33
+ interface CompiledMarkdownHtmlDocument<TLocale extends string> extends CompiledMarkdownDocumentBase<TLocale> {
34
+ html: string;
35
+ kind: "md";
36
+ }
37
+ interface CompiledMarkdownMdxDocument<TLocale extends string> extends CompiledMarkdownDocumentBase<TLocale> {
38
+ code: string;
39
+ kind: "mdx";
40
+ }
41
+ type CompiledMarkdownResult<TLocale extends string = string> = CompiledMarkdownHtmlDocument<TLocale> | CompiledMarkdownMdxDocument<TLocale>;
42
+ interface MarkdownCollection<TLocale extends string> {
43
+ compileDocument(documentId: string, options?: MarkdownDocumentOptions<TLocale>): Promise<CompiledMarkdownResult<TLocale>>;
44
+ compileDocument(document: LocalizedMarkdownDocument<TLocale>): Promise<CompiledMarkdownResult<TLocale>>;
45
+ getDocument(documentId: string, options?: MarkdownDocumentOptions<TLocale>): Promise<LocalizedMarkdownDocument<TLocale>>;
46
+ listDocuments(): Promise<string[]>;
47
+ }
48
+ interface MarkdownServerHelpers<TLocale extends string> {
49
+ compileDocument(documentId: string, options?: MarkdownDocumentOptions<TLocale>): Promise<CompiledMarkdownResult<TLocale>>;
50
+ compileDocument(document: LocalizedMarkdownDocument<TLocale>): Promise<CompiledMarkdownResult<TLocale>>;
51
+ getCollection(): Promise<MarkdownCollection<TLocale>>;
52
+ getAvailableLanguages(): Promise<readonly TranslationLanguageMetadata<TLocale>[]>;
53
+ getDirection(options?: MarkdownDirectionOptions<TLocale>): Promise<TranslationDirection>;
54
+ getDocument(documentId: string, options?: MarkdownDocumentOptions<TLocale>): Promise<LocalizedMarkdownDocument<TLocale>>;
55
+ isRtl(options?: MarkdownDirectionOptions<TLocale>): Promise<boolean>;
56
+ }
57
+ declare class MarkdownDocumentNotFoundError extends Error {
58
+ readonly fallbackLocale: string;
59
+ readonly id: string;
60
+ readonly lookedUpPaths: readonly string[];
61
+ readonly requestedLocale: string;
62
+ constructor(options: {
63
+ fallbackLocale: string;
64
+ id: string;
65
+ lookedUpPaths: readonly string[];
66
+ requestedLocale: string;
67
+ });
68
+ }
69
+
70
+ export { type AnyBetterTranslateTranslator as A, type CompiledMarkdownHtmlDocument as C, type InferLocale as I, type LocalizedMarkdownDocument as L, type MarkdownCollectionConfig as M, type MarkdownCollection as a, type MarkdownHelpersOptions as b, type CompiledMarkdownMdxDocument as c, type CompiledMarkdownResult as d, type MarkdownDocumentExtension as e, MarkdownDocumentNotFoundError as f, type MarkdownDocumentOptions as g, type MarkdownServerHelpers as h };
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@better-translate/md",
3
+ "version": "1.0.0",
4
+ "description": "Markdown and MDX helpers for Better Translate.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "main": "./dist/index.cjs",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "require": "./dist/index.cjs"
16
+ },
17
+ "./server": {
18
+ "types": "./dist/server.d.ts",
19
+ "import": "./dist/server.js",
20
+ "require": "./dist/server.cjs"
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "files": ["dist", "LICENSE", "README.md"],
25
+ "scripts": {
26
+ "build": "tsup src/index.ts src/server.ts --format esm,cjs --dts --clean",
27
+ "check-types": "tsc --noEmit",
28
+ "test": "bun test tests/runtime",
29
+ "test:types": "tsc -p tests/types/tsconfig.json --noEmit"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/jralvarenga/better-translate.git",
37
+ "directory": "packages/md"
38
+ },
39
+ "homepage": "https://github.com/jralvarenga/better-translate/tree/main/packages/md#readme",
40
+ "bugs": {
41
+ "url": "https://github.com/jralvarenga/better-translate/issues"
42
+ },
43
+ "dependencies": {
44
+ "@mdx-js/mdx": "^3.1.1",
45
+ "@better-translate/core": "workspace:^",
46
+ "gray-matter": "^4.0.3",
47
+ "rehype-stringify": "^10.0.1",
48
+ "remark-parse": "^11.0.0",
49
+ "remark-rehype": "^11.1.2",
50
+ "unified": "^11.0.5"
51
+ },
52
+ "peerDependencies": {
53
+ "react": "^19.0.0"
54
+ },
55
+ "peerDependenciesMeta": {
56
+ "react": {
57
+ "optional": true
58
+ }
59
+ },
60
+ "devDependencies": {
61
+ "@repo/typescript-config": "*"
62
+ },
63
+ "keywords": ["i18n", "l10n", "markdown", "mdx", "translations", "typescript"]
64
+ }