@ox-content/vite-plugin-svelte 3.1.2-beta.0 → 3.1.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.cjs CHANGED
@@ -21,12 +21,19 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
21
  enumerable: true
22
22
  }) : target, mod));
23
23
  //#endregion
24
+ const require_html_host_client = require("./html-host-client2.cjs");
25
+ let _ox_content_vite_plugin = require("@ox-content/vite-plugin");
26
+ let svelte_compiler = require("svelte/compiler");
24
27
  let fs = require("fs");
25
28
  fs = __toESM(fs, 1);
26
29
  let path = require("path");
27
30
  path = __toESM(path, 1);
28
- let _ox_content_vite_plugin = require("@ox-content/vite-plugin");
29
- let svelte_compiler = require("svelte/compiler");
31
+ let node_path = require("node:path");
32
+ node_path = __toESM(node_path, 1);
33
+ let node_fs = require("node:fs");
34
+ node_fs = __toESM(node_fs, 1);
35
+ let node_fs_promises = require("node:fs/promises");
36
+ node_fs_promises = __toESM(node_fs_promises, 1);
30
37
  //#region src/transform.ts
31
38
  const COMPONENT_REGEX = /<([A-Z][a-zA-Z0-9]*)\s*([^>]*?)\s*(?:\/>|>([\s\S]*?)<\/\1>)/g;
32
39
  const PROP_REGEX = /([a-zA-Z0-9-]+)(?:=(?:"([^"]*)"|'([^']*)'|{([^}]*)}|\[([^\]]*)\]))?/g;
@@ -116,8 +123,8 @@ async function transformMarkdownWithSvelte(code, id, options) {
116
123
  }),
117
124
  srcDir: options.srcDir
118
125
  });
119
- if (options.mdxDocumentProps) return compileSvelteResult(generateMdxDocumentPropsSvelteModule(transformed.html, discovered.usedComponents, frontmatter, options, id, discovered.localBindings, documentExpressions.expressions), id, discovered.usedComponents, frontmatter, options.ssr);
120
- return compileSvelteResult(generateSvelteModule(options.renderIsland ? await (0, _ox_content_vite_plugin.applyIslandSsrHtml)(transformed.html, options.renderIsland, id, discovered.usedComponents) : transformed.html, discovered.usedComponents, discovered.usedComponents, frontmatter, options, id, discovered.localBindings), id, discovered.usedComponents, frontmatter, options.ssr);
126
+ if (options.mdxDocumentProps) return compileSvelteResult(generateMdxDocumentPropsSvelteModule(transformed.html, discovered.usedComponents, frontmatter, options, id, discovered.localBindings, documentExpressions.expressions), id, discovered.usedComponents, frontmatter, options);
127
+ return compileSvelteResult(generateSvelteModule(options.renderIsland ? await (0, _ox_content_vite_plugin.applyIslandSsrHtml)(transformed.html, options.renderIsland, id, discovered.usedComponents) : transformed.html, discovered.usedComponents, discovered.usedComponents, frontmatter, options, id, discovered.localBindings), id, discovered.usedComponents, frontmatter, options);
121
128
  }
122
129
  const usedComponents = [];
123
130
  const islands = [];
@@ -151,20 +158,63 @@ async function transformMarkdownWithSvelte(code, id, options) {
151
158
  lastIndex = matchEnd;
152
159
  }
153
160
  processedContent += markdownContent.slice(lastIndex);
154
- return compileSvelteResult(generateSvelteModule(injectIslandMarkers((await (0, _ox_content_vite_plugin.transformMarkdown)(processedContent, id, baseOptions)).html, islands), usedComponents, islands, frontmatter, options, id), id, usedComponents, frontmatter, options.ssr);
161
+ return compileSvelteResult(generateSvelteModule(injectIslandMarkers((await (0, _ox_content_vite_plugin.transformMarkdown)(processedContent, id, baseOptions)).html, islands), usedComponents, islands, frontmatter, options, id), id, usedComponents, frontmatter, options);
155
162
  }
156
- function compileSvelteResult(svelteCode, id, usedComponents, frontmatter, ssr = false) {
163
+ async function compileSvelteResult(svelteCode, id, usedComponents, frontmatter, options) {
164
+ const compiled = normalizeSvelteCompilerResult(await resolveSvelteCompiler(options.compiler)(svelteCode, {
165
+ filename: id,
166
+ generate: options.ssr ? "server" : "client",
167
+ runes: options.runes
168
+ }), id);
157
169
  return {
158
- code: `${(0, svelte_compiler.compile)(svelteCode, {
159
- filename: id,
160
- generate: ssr ? "server" : "client",
161
- runes: true
162
- }).js.code}\nexport const frontmatter = ${JSON.stringify(frontmatter)};`,
163
- map: null,
170
+ code: `${compiled.code}\nexport const frontmatter = ${JSON.stringify(frontmatter)};`,
171
+ map: compiled.map,
172
+ warnings: compiled.warnings,
164
173
  usedComponents,
165
174
  frontmatter
166
175
  };
167
176
  }
177
+ function resolveSvelteCompiler(compiler) {
178
+ if (!compiler) return svelte_compiler.compile;
179
+ if (typeof compiler === "function") return compiler;
180
+ return compiler.compile;
181
+ }
182
+ function normalizeSvelteCompilerResult(result, id) {
183
+ let value = result;
184
+ if (typeof value === "string") {
185
+ const source = value;
186
+ try {
187
+ value = JSON.parse(source);
188
+ } catch {
189
+ return {
190
+ code: source,
191
+ map: null,
192
+ warnings: []
193
+ };
194
+ }
195
+ }
196
+ if (!value || typeof value !== "object") throwUnsupportedCompilerResult(id);
197
+ const output = value;
198
+ const js = output.js;
199
+ const warnings = Array.isArray(output.warnings) ? output.warnings : [];
200
+ if (typeof js === "string") return {
201
+ code: js,
202
+ map: null,
203
+ warnings
204
+ };
205
+ if (js && typeof js === "object") {
206
+ const jsOutput = js;
207
+ if (typeof jsOutput.code === "string") return {
208
+ code: jsOutput.code,
209
+ map: jsOutput.map ?? null,
210
+ warnings
211
+ };
212
+ }
213
+ throwUnsupportedCompilerResult(id);
214
+ }
215
+ function throwUnsupportedCompilerResult(id) {
216
+ throw new Error(`[ox-content-svelte] Compiler for ${id} returned an unsupported result. Expected { js: { code } } or a compatible JSON string.`);
217
+ }
168
218
  function createIslandMarker(islandId) {
169
219
  return `${ISLAND_MARKER_PREFIX}${islandId}${ISLAND_MARKER_SUFFIX}`;
170
220
  }
@@ -744,7 +794,7 @@ function findMdxIslandRanges(html) {
744
794
  let match;
745
795
  while ((match = openRe.exec(html)) !== null) {
746
796
  const tag = match[1];
747
- const name = decodeHtmlAttr(match[3] ?? "");
797
+ const name = decodeHtmlAttr$1(match[3] ?? "");
748
798
  if (!name) continue;
749
799
  const openStart = match.index;
750
800
  const openEnd = match.index + match[0].length;
@@ -799,7 +849,7 @@ function indexOfTagOpen(html, openNeedle, from) {
799
849
  }
800
850
  function matchAttr(attrs, name) {
801
851
  const match = new RegExp(`\\b${name}="([^"]*)"`, "i").exec(attrs);
802
- return match?.[1] === void 0 ? void 0 : decodeHtmlAttr(match[1]);
852
+ return match?.[1] === void 0 ? void 0 : decodeHtmlAttr$1(match[1]);
803
853
  }
804
854
  function readMdxIslandPayload(island) {
805
855
  const fromAttr = island.propsAttr ? tryParseJson(island.propsAttr) : void 0;
@@ -844,7 +894,7 @@ function tryParseJson(value) {
844
894
  return;
845
895
  }
846
896
  }
847
- function decodeHtmlAttr(value) {
897
+ function decodeHtmlAttr$1(value) {
848
898
  return value.replaceAll("&quot;", "\"").replaceAll("&#39;", "'").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
849
899
  }
850
900
  function assertSvelteComponentName(name, filePath) {
@@ -965,12 +1015,634 @@ function createSvelteMarkdownEnvironment(mode, options) {
965
1015
  };
966
1016
  }
967
1017
  //#endregion
968
- //#region src/index.ts
1018
+ //#region src/components.ts
969
1019
  /**
970
- * Vite Plugin for Ox Content Svelte Integration
971
- *
972
- * Uses Vite's Environment API to enable embedding Svelte components in Markdown.
1020
+ * Resolves the `components` option into a name → path map, expanding glob
1021
+ * patterns against the Vite project root.
1022
+ */
1023
+ async function resolveComponentsGlob(componentsOption, root) {
1024
+ if (typeof componentsOption === "object" && !Array.isArray(componentsOption)) return componentsOption;
1025
+ const patterns = Array.isArray(componentsOption) ? componentsOption : [componentsOption];
1026
+ const result = {};
1027
+ for (const pattern of patterns) for (const file of await globFiles(pattern, root)) {
1028
+ const baseName = path.basename(file, path.extname(file));
1029
+ const relativePath = "./" + path.relative(root, file).replace(/\\/g, "/");
1030
+ result[toPascalCase(baseName)] = relativePath;
1031
+ }
1032
+ return result;
1033
+ }
1034
+ async function globFiles(pattern, root) {
1035
+ const files = [];
1036
+ const normalized = pattern.replace(/\\/g, "/").replace(/^\.\//, "");
1037
+ if (!hasWildcard(normalized)) {
1038
+ const fullPath = path.resolve(root, normalized);
1039
+ if (fs.existsSync(fullPath)) files.push(fullPath);
1040
+ return files;
1041
+ }
1042
+ const baseDir = path.resolve(root, staticPrefix(normalized));
1043
+ if (!fs.existsSync(baseDir)) return files;
1044
+ const segments = normalized.split("/");
1045
+ const crossesDirectories = normalized.includes("**") || segments.slice(0, -1).some(hasWildcard);
1046
+ const candidates = [];
1047
+ if (crossesDirectories) await walkDir(baseDir, candidates);
1048
+ else {
1049
+ const entries = await fs.promises.readdir(baseDir, { withFileTypes: true });
1050
+ for (const entry of entries) if (entry.isFile()) candidates.push(path.join(baseDir, entry.name));
1051
+ }
1052
+ const matcher = globToRegExp(normalized);
1053
+ for (const candidate of candidates) if (matcher.test(path.relative(root, candidate).replace(/\\/g, "/"))) files.push(candidate);
1054
+ return files;
1055
+ }
1056
+ /** Whether a pattern (or one segment of it) contains a wildcard `globToRegExp` expands. */
1057
+ function hasWildcard(pattern) {
1058
+ return pattern.includes("*") || pattern.includes("?");
1059
+ }
1060
+ /** Leading path segments of a pattern that contain no wildcard. */
1061
+ function staticPrefix(pattern) {
1062
+ const segments = [];
1063
+ for (const segment of pattern.split("/")) {
1064
+ if (hasWildcard(segment)) break;
1065
+ segments.push(segment);
1066
+ }
1067
+ return segments.join("/");
1068
+ }
1069
+ /**
1070
+ * Translates a glob into an anchored `RegExp`: `**` crosses directory
1071
+ * boundaries, `*` and `?` stay within one segment.
973
1072
  */
1073
+ function globToRegExp(pattern) {
1074
+ let source = "";
1075
+ let index = 0;
1076
+ while (index < pattern.length) {
1077
+ const char = pattern[index];
1078
+ if (char === "*") {
1079
+ if (pattern[index + 1] === "*") {
1080
+ index += 2;
1081
+ if (pattern[index] === "/") {
1082
+ index += 1;
1083
+ source += "(?:[^/]+/)*";
1084
+ } else source += ".*";
1085
+ continue;
1086
+ }
1087
+ source += "[^/]*";
1088
+ } else if (char === "?") source += "[^/]";
1089
+ else source += char.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1090
+ index += 1;
1091
+ }
1092
+ return new RegExp(`^${source}$`);
1093
+ }
1094
+ async function walkDir(dir, files) {
1095
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
1096
+ for (const entry of entries) {
1097
+ const fullPath = path.join(dir, entry.name);
1098
+ if (entry.isDirectory()) await walkDir(fullPath, files);
1099
+ else if (entry.isFile()) files.push(fullPath);
1100
+ }
1101
+ }
1102
+ function toPascalCase(str) {
1103
+ return str.replace(/[-_](\w)/g, (_, c) => c.toUpperCase()).replace(/^\w/, (c) => c.toUpperCase());
1104
+ }
1105
+ //#endregion
1106
+ //#region src/html-host-default-renderer.ts
1107
+ const defaultRenderSvelteHtmlComponent = async (component, props, slotHtml) => {
1108
+ const [{ render }, { createRawSnippet }] = await Promise.all([import("svelte/server"), import("svelte")]);
1109
+ const rendered = render(component, { props: slotHtml ? {
1110
+ ...props,
1111
+ children: createRawSnippet(() => ({ render: () => slotHtml }))
1112
+ } : props });
1113
+ return rendered.html ?? rendered.body ?? "";
1114
+ };
1115
+ //#endregion
1116
+ //#region src/html-host.ts
1117
+ const ISLAND_JSON_SCRIPT = /^\s*<script type="application\/json">[\s\S]*?<\/script>/;
1118
+ async function renderSvelteHtmlHost(input) {
1119
+ const diagnostics = [];
1120
+ const modules = resolveHostModules(input, diagnostics);
1121
+ const byName = new Map(modules.map((module) => [module.name, module]));
1122
+ const cache = /* @__PURE__ */ new Map();
1123
+ const renderComponent = input.renderComponent ?? defaultRenderSvelteHtmlComponent;
1124
+ return {
1125
+ html: markClientModules(await (0, _ox_content_vite_plugin.applyIslandSsrHtml)(input.html, async (name, props, _filePath, slotHtml) => {
1126
+ const module = byName.get(name);
1127
+ if (!module) {
1128
+ diagnostics.push({
1129
+ code: "missing-component",
1130
+ message: `Svelte island "${name}" is not registered for this document.`,
1131
+ documentPath: input.documentPath,
1132
+ component: name
1133
+ });
1134
+ return slotHtml ?? "";
1135
+ }
1136
+ const component = await loadComponent(input, module, cache, diagnostics);
1137
+ if (!component) return slotHtml ?? "";
1138
+ try {
1139
+ return await renderComponent(component, props, slotHtml || void 0, {
1140
+ component: name,
1141
+ moduleId: module.serverModuleId,
1142
+ documentPath: input.documentPath
1143
+ });
1144
+ } catch (error) {
1145
+ diagnostics.push({
1146
+ code: "ssr-failed",
1147
+ message: `Svelte island "${name}" failed to render: ${errorMessage(error)}`,
1148
+ documentPath: input.documentPath,
1149
+ component: name,
1150
+ moduleId: module.serverModuleId
1151
+ });
1152
+ return slotHtml ?? "";
1153
+ }
1154
+ }, input.documentPath, modules.map((module) => module.name)), modules),
1155
+ modules,
1156
+ clientModules: modules.flatMap((module) => module.clientModuleId ? [{
1157
+ name: module.name,
1158
+ moduleId: module.clientModuleId,
1159
+ exportName: module.exportName
1160
+ }] : []),
1161
+ diagnostics
1162
+ };
1163
+ }
1164
+ function createSvelteHtmlHostHydrate(input) {
1165
+ return (element, props) => {
1166
+ const name = element.dataset.oxIsland;
1167
+ if (!name) return;
1168
+ const component = componentFromRegistry(input.components, name);
1169
+ if (!component) return;
1170
+ const slotHtml = readIslandSlotHtml(element);
1171
+ element.innerHTML = "";
1172
+ return input.render(component, props, element, slotHtml || void 0);
1173
+ };
1174
+ }
1175
+ function resolveHostModules(input, diagnostics) {
1176
+ const names = (0, _ox_content_vite_plugin.collectMdxIslandNamesFromHtml)(input.html);
1177
+ const local = (0, _ox_content_vite_plugin.resolveDocumentComponentImports)({
1178
+ imports: input.imports ?? [],
1179
+ documentPath: input.documentPath,
1180
+ contentRoot: input.contentRoot ?? (0, _ox_content_vite_plugin.resolveContentRootPath)(input),
1181
+ srcDir: input.srcDir
1182
+ });
1183
+ for (const diagnostic of local.diagnostics) diagnostics.push({
1184
+ ...diagnostic,
1185
+ documentPath: input.documentPath
1186
+ });
1187
+ const localBindings = new Map(local.bindings.map((binding) => [binding.localName, binding]));
1188
+ const modules = [];
1189
+ for (const name of names) {
1190
+ const localBinding = localBindings.get(name);
1191
+ const serverModuleId = localBinding ? localBinding.resolvedPath : componentPath(input.components ?? {}, name, input.root);
1192
+ if (!serverModuleId) {
1193
+ diagnostics.push({
1194
+ code: "missing-component",
1195
+ message: `Svelte island "${name}" is not registered for this document.`,
1196
+ documentPath: input.documentPath,
1197
+ component: name
1198
+ });
1199
+ continue;
1200
+ }
1201
+ const module = {
1202
+ name,
1203
+ serverModuleId,
1204
+ exportName: localBinding?.imported ?? "default",
1205
+ source: localBinding ? "document" : "components"
1206
+ };
1207
+ const clientModuleId = input.resolveClientModule?.(module, { documentPath: input.documentPath });
1208
+ modules.push(clientModuleId ? {
1209
+ ...module,
1210
+ clientModuleId
1211
+ } : module);
1212
+ }
1213
+ return modules;
1214
+ }
1215
+ async function loadComponent(input, module, cache, diagnostics) {
1216
+ let pending = cache.get(module.serverModuleId);
1217
+ if (!pending) {
1218
+ pending = input.loadModule(module.serverModuleId);
1219
+ cache.set(module.serverModuleId, pending);
1220
+ }
1221
+ let exports;
1222
+ try {
1223
+ exports = await pending;
1224
+ } catch (error) {
1225
+ diagnostics.push({
1226
+ code: "module-load-failed",
1227
+ message: `Svelte island module "${module.serverModuleId}" failed to load: ${errorMessage(error)}`,
1228
+ documentPath: input.documentPath,
1229
+ component: module.name,
1230
+ moduleId: module.serverModuleId
1231
+ });
1232
+ return;
1233
+ }
1234
+ const component = exportedValue(exports, module.exportName);
1235
+ if (!component) diagnostics.push({
1236
+ code: "missing-export",
1237
+ message: `Svelte island "${module.name}" could not find export "${module.exportName}".`,
1238
+ documentPath: input.documentPath,
1239
+ component: module.name,
1240
+ moduleId: module.serverModuleId
1241
+ });
1242
+ return component == null ? void 0 : component;
1243
+ }
1244
+ function componentPath(components, name, root = process.cwd()) {
1245
+ const specifier = components[name];
1246
+ if (!specifier) return;
1247
+ return node_path.default.resolve(root, specifier.replace(/^\.\//, ""));
1248
+ }
1249
+ function exportedValue(exports, exportName) {
1250
+ if (!exports || typeof exports !== "object") return;
1251
+ return exports[exportName];
1252
+ }
1253
+ function componentFromRegistry(registry, name) {
1254
+ return isReadonlyMap(registry) ? registry.get(name) : registry[name];
1255
+ }
1256
+ function isReadonlyMap(value) {
1257
+ return typeof value.get === "function";
1258
+ }
1259
+ function readIslandSlotHtml(element) {
1260
+ const fromAttr = element.dataset.oxContent;
1261
+ if (fromAttr) return fromAttr;
1262
+ if (element.dataset.oxSsr === "true") return "";
1263
+ return element.innerHTML.replace(ISLAND_JSON_SCRIPT, "");
1264
+ }
1265
+ function markClientModules(html, modules) {
1266
+ const clientModules = new Map(modules.filter((module) => module.clientModuleId).map((module) => [module.name, module]));
1267
+ if (clientModules.size === 0) return html;
1268
+ return html.replace(/<(div|span)\b([^>]*\bdata-ox-island="([^"]+)"[^>]*)>/gi, (openTag, _tag, _attrs, encodedName) => {
1269
+ const module = clientModules.get(decodeHtmlAttr(encodedName));
1270
+ if (!module?.clientModuleId) return openTag;
1271
+ const attrs = [];
1272
+ if (!hasAttr(openTag, "data-ox-module")) attrs.push(`data-ox-module="${escapeDoubleQuotedAttr(module.clientModuleId)}"`);
1273
+ if (!hasAttr(openTag, "data-ox-export")) attrs.push(`data-ox-export="${escapeDoubleQuotedAttr(module.exportName)}"`);
1274
+ return attrs.length === 0 ? openTag : openTag.replace(/>$/, ` ${attrs.join(" ")}>`);
1275
+ });
1276
+ }
1277
+ function escapeDoubleQuotedAttr(value) {
1278
+ return value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1279
+ }
1280
+ function decodeHtmlAttr(value) {
1281
+ return value.replaceAll("&quot;", "\"").replaceAll("&#39;", "'").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
1282
+ }
1283
+ function hasAttr(openTag, name) {
1284
+ return new RegExp(`\\s${name}(?:\\s*=|\\s|>|$)`, "i").test(openTag);
1285
+ }
1286
+ function errorMessage(error) {
1287
+ return error instanceof Error ? error.message : String(error);
1288
+ }
1289
+ //#endregion
1290
+ //#region src/html-host-registry-paths.ts
1291
+ function toSvelteHtmlHostClientModuleId(moduleId, root = process.cwd()) {
1292
+ const [pathname, suffix = ""] = splitModuleSuffix(moduleId);
1293
+ if (isBareSpecifier(pathname) || pathname.startsWith("/@fs/")) return `${pathname}${suffix}`;
1294
+ const rootPath = node_path.default.resolve(root);
1295
+ const realRoot = existingRealpath(rootPath) ?? rootPath;
1296
+ const absolute = node_path.default.isAbsolute(pathname) ? node_path.default.resolve(pathname) : node_path.default.resolve(rootPath, pathname);
1297
+ const realAbsolute = existingRealpath(absolute);
1298
+ const isInsideRealRoot = realAbsolute ? isInsideRoot(realAbsolute, realRoot) : false;
1299
+ const isInsideLexicalRoot = isInsideRoot(absolute, rootPath);
1300
+ if (node_path.default.isAbsolute(pathname) && !isInsideRealRoot && !isInsideLexicalRoot) return node_fs.default.existsSync(pathname) ? `/@fs${toPosixPath(pathname)}${suffix}` : `${toPosixPath(pathname)}${suffix}`;
1301
+ const relativeRoot = isInsideRealRoot ? realRoot : rootPath;
1302
+ const relativePath = isInsideRealRoot && realAbsolute ? realAbsolute : absolute;
1303
+ return `/${node_path.default.relative(relativeRoot, relativePath).replace(/\\/g, "/")}${suffix}`;
1304
+ }
1305
+ function resolveDocumentPath(documentPath, root) {
1306
+ return node_path.default.isAbsolute(documentPath) ? (0, _ox_content_vite_plugin.stripViteQuery)(documentPath) : node_path.default.resolve(root, (0, _ox_content_vite_plugin.stripViteQuery)(documentPath));
1307
+ }
1308
+ function resolveWatchFile(file, root) {
1309
+ return node_path.default.isAbsolute(file) ? (0, _ox_content_vite_plugin.stripViteQuery)(file) : node_path.default.resolve(root, (0, _ox_content_vite_plugin.stripViteQuery)(file));
1310
+ }
1311
+ function shouldInvalidate(file, root, srcDir, watchFiles, extraWatchFiles) {
1312
+ const changed = node_path.default.resolve(file);
1313
+ if (watchFiles.some((watchFile) => changed === watchFile)) return true;
1314
+ if (extraWatchFiles?.some((watchFile) => changed === resolveWatchFile(watchFile, root))) return true;
1315
+ return isInsideRoot(changed, node_path.default.resolve(root, srcDir ?? "content"));
1316
+ }
1317
+ function splitModuleSuffix(moduleId) {
1318
+ const match = /[?#]/u.exec(moduleId);
1319
+ return match ? [moduleId.slice(0, match.index), moduleId.slice(match.index)] : [moduleId];
1320
+ }
1321
+ function isBareSpecifier(moduleId) {
1322
+ return !moduleId.startsWith(".") && !moduleId.startsWith("/") && !moduleId.includes("\\");
1323
+ }
1324
+ function isInsideRoot(file, root) {
1325
+ const relative = node_path.default.relative(node_path.default.resolve(root), node_path.default.resolve(file));
1326
+ return relative === "" || !relative.startsWith("..") && !node_path.default.isAbsolute(relative);
1327
+ }
1328
+ function existingRealpath(file) {
1329
+ try {
1330
+ return node_fs.default.realpathSync.native(file);
1331
+ } catch {
1332
+ return;
1333
+ }
1334
+ }
1335
+ function toPosixPath(file) {
1336
+ return file.replace(/\\/g, "/");
1337
+ }
1338
+ //#endregion
1339
+ //#region src/html-host-renderer.ts
1340
+ var SvelteHtmlHostRenderError = class extends Error {
1341
+ diagnostics;
1342
+ constructor(diagnostics) {
1343
+ super(formatSvelteHtmlHostDiagnostics(diagnostics));
1344
+ this.name = "SvelteHtmlHostRenderError";
1345
+ this.diagnostics = [...diagnostics];
1346
+ }
1347
+ };
1348
+ function createSvelteHtmlHostRenderer(input) {
1349
+ const policy = input.diagnostics ?? "throw";
1350
+ return async (html, context) => {
1351
+ const root = context.root ?? input.root;
1352
+ const result = await renderSvelteHtmlHost({
1353
+ html,
1354
+ documentPath: context.documentPath,
1355
+ root,
1356
+ srcDir: context.srcDir ?? input.srcDir,
1357
+ contentRoot: context.contentRoot ?? input.contentRoot,
1358
+ imports: context.imports,
1359
+ components: context.components ?? input.components,
1360
+ loadModule: input.loadModule,
1361
+ renderComponent: context.renderComponent ?? input.renderComponent,
1362
+ resolveClientModule: context.resolveClientModule ?? input.resolveClientModule ?? ((module) => toSvelteHtmlHostClientModuleId(module.serverModuleId, root))
1363
+ });
1364
+ if (policy === "throw" && result.diagnostics.length > 0) throw new SvelteHtmlHostRenderError(result.diagnostics);
1365
+ return result;
1366
+ };
1367
+ }
1368
+ function formatSvelteHtmlHostDiagnostics(diagnostics) {
1369
+ if (diagnostics.length === 0) return "Svelte HTML host rendering failed.";
1370
+ return diagnostics.map((diagnostic) => {
1371
+ const details = [
1372
+ diagnostic.documentPath,
1373
+ diagnostic.component && `component ${diagnostic.component}`,
1374
+ diagnostic.moduleId && `module ${diagnostic.moduleId}`
1375
+ ].filter(Boolean);
1376
+ return `${diagnostic.code}: ${diagnostic.message}${details.length > 0 ? ` (${details.join(", ")})` : ""}`;
1377
+ }).join("\n");
1378
+ }
1379
+ //#endregion
1380
+ //#region src/html-host-collection-documents.ts
1381
+ function createSvelteHtmlHostCollectionDocuments(input = {}) {
1382
+ return (context) => resolveSvelteHtmlHostCollectionDocuments(input, context);
1383
+ }
1384
+ async function resolveSvelteHtmlHostCollectionDocuments(input, context) {
1385
+ const options = resolveCollectionManifestOptions((0, _ox_content_vite_plugin.customHostOxContentOptions)(input.oxContent ?? {}));
1386
+ if (!options.collections.enabled) return [];
1387
+ const manifest = await (0, _ox_content_vite_plugin.buildCollectionManifest)(context.root, options);
1388
+ const names = resolveCollectionNames(input.collections, options.collections);
1389
+ const documents = /* @__PURE__ */ new Map();
1390
+ for (const name of names) for (const entry of manifest.collections[name] ?? []) {
1391
+ const document = await resolveCollectionDocument(context.root, options.srcDir, name, entry);
1392
+ if (!document) continue;
1393
+ if (input.select && !await input.select(document, context)) continue;
1394
+ documents.set(document.documentPath, document);
1395
+ }
1396
+ return [...documents.values()];
1397
+ }
1398
+ function resolveCollectionManifestOptions(oxContent) {
1399
+ const collections = withoutCollectionInclude((0, _ox_content_vite_plugin.resolveCollectionsOptions)(oxContent.collections));
1400
+ return {
1401
+ srcDir: oxContent.srcDir ?? "content",
1402
+ outDir: oxContent.outDir ?? "dist",
1403
+ base: oxContent.base ?? "/",
1404
+ extensions: (0, _ox_content_vite_plugin.normalizeMarkdownExtensions)(oxContent.extensions),
1405
+ collections,
1406
+ permalinks: (0, _ox_content_vite_plugin.resolvePermalinksOptions)(oxContent.permalinks),
1407
+ cascade: (0, _ox_content_vite_plugin.resolveCascadeOptions)(oxContent.cascade),
1408
+ gfm: oxContent.gfm ?? true,
1409
+ mdx: oxContent.mdx,
1410
+ footnotes: oxContent.footnotes ?? true,
1411
+ semanticFootnotes: oxContent.semanticFootnotes ?? false,
1412
+ taskLists: oxContent.taskLists ?? true,
1413
+ tables: oxContent.tables ?? true,
1414
+ strikethrough: oxContent.strikethrough ?? true,
1415
+ autolinks: oxContent.autolinks ?? oxContent.gfm ?? true,
1416
+ superscript: oxContent.superscript ?? false,
1417
+ subscript: oxContent.subscript ?? false,
1418
+ smartPunctuation: oxContent.smartPunctuation ?? false,
1419
+ autolinkTargetBlank: oxContent.autolinkTargetBlank ?? true,
1420
+ linkTargetBlank: oxContent.linkTargetBlank ?? true,
1421
+ sourceSpans: oxContent.sourceSpans ?? false,
1422
+ frontmatter: oxContent.frontmatter ?? true,
1423
+ tocMaxDepth: oxContent.tocMaxDepth ?? 3,
1424
+ cjkEmphasis: oxContent.cjkEmphasis ?? false
1425
+ };
1426
+ }
1427
+ function withoutCollectionInclude(collections) {
1428
+ return {
1429
+ enabled: collections.enabled,
1430
+ collections: Object.fromEntries(Object.entries(collections.collections).map(([name, collection]) => [name, {
1431
+ ...collection,
1432
+ include: []
1433
+ }]))
1434
+ };
1435
+ }
1436
+ function resolveCollectionNames(input, collections) {
1437
+ const available = Object.keys(collections.collections);
1438
+ if (!input) return available;
1439
+ const selected = new Set(Array.isArray(input) ? input : [input]);
1440
+ return available.filter((name) => selected.has(name));
1441
+ }
1442
+ async function resolveCollectionDocument(root, srcDir, collection, entry) {
1443
+ const candidate = node_path.default.resolve(root, srcDir, entry.source);
1444
+ let source;
1445
+ try {
1446
+ source = await node_fs_promises.default.readFile(candidate, "utf8");
1447
+ } catch {
1448
+ return;
1449
+ }
1450
+ return {
1451
+ collection,
1452
+ documentPath: candidate,
1453
+ entry,
1454
+ frontmatter: entry.frontmatter,
1455
+ path: entry.path,
1456
+ source
1457
+ };
1458
+ }
1459
+ //#endregion
1460
+ //#region src/html-host-registry.ts
1461
+ const SVELTE_HTML_HOST_MODULES_VIRTUAL_ID = "virtual:ox-content-svelte/html-host/modules";
1462
+ function createSvelteHtmlHostIslandRegistry(input = {}) {
1463
+ const virtualModuleId = input.virtualModuleId ?? "virtual:ox-content-svelte/html-host/modules";
1464
+ const resolvedVirtualModuleId = `\0${virtualModuleId}`;
1465
+ let config;
1466
+ let command = "build";
1467
+ let components;
1468
+ let cache;
1469
+ let resolved = {
1470
+ modules: [],
1471
+ watchFiles: []
1472
+ };
1473
+ const context = () => ({
1474
+ root: config?.root ?? input.root ?? process.cwd(),
1475
+ mode: config?.mode ?? "production",
1476
+ command
1477
+ });
1478
+ const resolve = async () => {
1479
+ cache ??= resolveSvelteHtmlHostIslandRegistry(input, context(), components).then((next) => {
1480
+ resolved = next;
1481
+ return next;
1482
+ });
1483
+ return cache;
1484
+ };
1485
+ const invalidate = () => {
1486
+ cache = void 0;
1487
+ };
1488
+ return {
1489
+ plugin: {
1490
+ name: "ox-content:svelte-html-host-island-registry",
1491
+ config(_config, env) {
1492
+ command = env.command;
1493
+ },
1494
+ async configResolved(resolvedConfig) {
1495
+ config = resolvedConfig;
1496
+ components = input.components ? await resolveComponentsGlob(input.components, resolvedConfig.root) : {};
1497
+ invalidate();
1498
+ },
1499
+ buildStart() {
1500
+ invalidate();
1501
+ },
1502
+ resolveId(id) {
1503
+ return id === virtualModuleId ? resolvedVirtualModuleId : null;
1504
+ },
1505
+ async load(id) {
1506
+ if (id !== resolvedVirtualModuleId) return null;
1507
+ return renderModulesVirtualModule(await resolve());
1508
+ },
1509
+ handleHotUpdate(ctx) {
1510
+ if (!shouldInvalidate(ctx.file, context().root, input.oxContent?.srcDir, resolved.watchFiles, input.watch)) return;
1511
+ invalidate();
1512
+ invalidateVirtualModule(ctx.server, resolvedVirtualModuleId);
1513
+ ctx.server.ws.send({ type: "full-reload" });
1514
+ return [];
1515
+ }
1516
+ },
1517
+ virtualModuleId,
1518
+ resolve,
1519
+ resolveClientModule(module) {
1520
+ return toSvelteHtmlHostClientModuleId(module.serverModuleId, context().root);
1521
+ }
1522
+ };
1523
+ }
1524
+ async function resolveSvelteHtmlHostIslandRegistry(input, context, resolvedComponents) {
1525
+ const components = resolvedComponents ?? (input.components ? await resolveComponentsGlob(input.components, context.root) : {});
1526
+ const documents = [...await resolveMaybe(input.documents, context) ?? [], ...await resolveInputCollectionDocuments(input, context) ?? []];
1527
+ const entries = await resolveMaybe(input.entries, context);
1528
+ const modules = /* @__PURE__ */ new Map();
1529
+ const watchFiles = /* @__PURE__ */ new Set();
1530
+ for (const file of input.watch ?? []) watchFiles.add(resolveWatchFile(file, context.root));
1531
+ for (const entry of entries ?? []) {
1532
+ addModule(modules, {
1533
+ name: entry.name ?? node_path.default.basename((0, _ox_content_vite_plugin.stripViteQuery)(entry.moduleId), node_path.default.extname(entry.moduleId)),
1534
+ moduleId: toSvelteHtmlHostClientModuleId(entry.moduleId, context.root),
1535
+ exportName: entry.exportName ?? "default"
1536
+ });
1537
+ if (entry.documentPath) watchFiles.add(resolveWatchFile(entry.documentPath, context.root));
1538
+ }
1539
+ const oxContent = (0, _ox_content_vite_plugin.customHostOxContentOptions)({
1540
+ ...input.oxContent,
1541
+ embeds: false
1542
+ });
1543
+ const srcDir = oxContent.srcDir ?? "content";
1544
+ const contentRoot = (0, _ox_content_vite_plugin.resolveContentRootPath)({
1545
+ root: context.root,
1546
+ srcDir
1547
+ });
1548
+ for (const document of documents) {
1549
+ const documentPath = resolveDocumentPath(document.documentPath, context.root);
1550
+ watchFiles.add(documentPath);
1551
+ for (const dependency of document.dependencies ?? []) watchFiles.add(resolveWatchFile(dependency, context.root));
1552
+ const materialized = await materializeDocument(document, documentPath, oxContent);
1553
+ if (!materialized) continue;
1554
+ const documentComponents = document.components ?? components;
1555
+ const discovered = await (0, _ox_content_vite_plugin.discoverDocumentMdxIslands)({
1556
+ source: materialized.source,
1557
+ html: materialized.html,
1558
+ components: documentComponents,
1559
+ imports: materialized.imports,
1560
+ documentPath,
1561
+ contentRoot,
1562
+ srcDir,
1563
+ root: context.root
1564
+ });
1565
+ const usedComponents = new Set(discovered.usedComponents);
1566
+ if (materialized.html) for (const name of (0, _ox_content_vite_plugin.intersectHydratableComponentNames)((0, _ox_content_vite_plugin.collectMdxIslandNamesFromHtml)(materialized.html), documentComponents, discovered.localBindings.keys())) usedComponents.add(name);
1567
+ for (const name of usedComponents) {
1568
+ const local = discovered.localBindings.get(name);
1569
+ const serverModuleId = local ? local.resolvedPath : resolveComponentPath(documentComponents, name, context.root);
1570
+ if (!serverModuleId) continue;
1571
+ addModule(modules, {
1572
+ name,
1573
+ moduleId: toSvelteHtmlHostClientModuleId(serverModuleId, context.root),
1574
+ exportName: local?.imported ?? "default"
1575
+ });
1576
+ }
1577
+ }
1578
+ return {
1579
+ modules: [...modules.values()].sort((a, b) => `${a.moduleId}\0${a.exportName}\0${a.name}`.localeCompare(`${b.moduleId}\0${b.exportName}\0${b.name}`)),
1580
+ watchFiles: [...watchFiles]
1581
+ };
1582
+ }
1583
+ function resolveInputCollectionDocuments(input, context) {
1584
+ if (!input.collectionDocuments) return void 0;
1585
+ return resolveSvelteHtmlHostCollectionDocuments(input.collectionDocuments.oxContent === void 0 ? {
1586
+ ...input.collectionDocuments,
1587
+ oxContent: input.oxContent
1588
+ } : input.collectionDocuments, context);
1589
+ }
1590
+ function renderModulesVirtualModule(registry) {
1591
+ return [
1592
+ "export const modules = {",
1593
+ ...[...new Set(registry.modules.map((module) => module.moduleId))].sort().map((moduleId) => ` ${JSON.stringify(moduleId)}: () => import(${JSON.stringify(moduleId)}),`),
1594
+ "};",
1595
+ `export const clientModules = ${JSON.stringify(registry.modules, null, 2)};`,
1596
+ "export default modules;",
1597
+ ""
1598
+ ].join("\n");
1599
+ }
1600
+ async function materializeDocument(document, documentPath, oxContent) {
1601
+ const source = document.source ?? await readOptional(documentPath);
1602
+ if (source === void 0 && document.html === void 0) return void 0;
1603
+ if (document.imports && document.html !== void 0) return {
1604
+ source: source ?? "",
1605
+ html: document.html,
1606
+ imports: document.imports
1607
+ };
1608
+ if (source === void 0) return {
1609
+ source: "",
1610
+ html: document.html,
1611
+ imports: document.imports ?? []
1612
+ };
1613
+ const rendered = await (0, _ox_content_vite_plugin.renderMarkdown)(source, documentPath, oxContent);
1614
+ return {
1615
+ source,
1616
+ html: document.html ?? rendered.html,
1617
+ imports: document.imports ?? rendered.imports
1618
+ };
1619
+ }
1620
+ async function readOptional(file) {
1621
+ try {
1622
+ return await node_fs_promises.default.readFile(file, "utf8");
1623
+ } catch {
1624
+ return;
1625
+ }
1626
+ }
1627
+ function addModule(modules, module) {
1628
+ modules.set(`${module.moduleId}\0${module.exportName}\0${module.name}`, module);
1629
+ }
1630
+ function resolveMaybe(value, context) {
1631
+ return typeof value === "function" ? value(context) : value;
1632
+ }
1633
+ function resolveComponentPath(components, name, root) {
1634
+ const specifier = components[name];
1635
+ if (!specifier) return void 0;
1636
+ if (isBareSpecifier(specifier) || specifier.startsWith("/@fs/")) return specifier;
1637
+ if (specifier.startsWith("/") && !node_path.default.isAbsolute(specifier)) return specifier;
1638
+ return node_path.default.isAbsolute(specifier) ? specifier : node_path.default.resolve(root, specifier);
1639
+ }
1640
+ function invalidateVirtualModule(server, resolvedVirtualModuleId) {
1641
+ const mod = server.moduleGraph.getModuleById(resolvedVirtualModuleId);
1642
+ if (mod) server.moduleGraph.invalidateModule(mod);
1643
+ }
1644
+ //#endregion
1645
+ //#region src/index.ts
974
1646
  const DEFAULT_MARKDOWN_EXTENSIONS = [
975
1647
  ".md",
976
1648
  ".markdown",
@@ -1054,6 +1726,7 @@ function oxContentSvelte(options = {}) {
1054
1726
  renderIsland: options.renderIsland,
1055
1727
  ssr: transformOptions?.ssr
1056
1728
  });
1729
+ for (const warning of result.warnings) this.warn(formatSvelteCompilerWarning(warning));
1057
1730
  return {
1058
1731
  code: result.code,
1059
1732
  map: result.map
@@ -1091,7 +1764,7 @@ function oxContentSvelte(options = {}) {
1091
1764
  name: "ox-content:svelte-hmr",
1092
1765
  apply: "serve",
1093
1766
  handleHotUpdate({ file, server, modules }) {
1094
- if (Array.from(componentMap.values()).some((path$1) => file.endsWith(path$1.replace(/^\.\//, "")))) {
1767
+ if (Array.from(componentMap.values()).some((path) => file.endsWith(path.replace(/^\.\//, "")))) {
1095
1768
  const mdModules = Array.from(server.moduleGraph.idToModuleMap.values()).filter((mod) => mod.file && isMarkdownFilePath(mod.file, resolved.extensions));
1096
1769
  if (mdModules.length > 0) {
1097
1770
  server.ws.send({
@@ -1126,11 +1799,16 @@ function resolveSvelteOptions(options) {
1126
1799
  tocMaxDepth: options.tocMaxDepth ?? 3,
1127
1800
  codeAnnotations: resolveCodeAnnotationsOptions(options.codeAnnotations),
1128
1801
  runes: options.runes ?? true,
1802
+ compiler: options.compiler,
1129
1803
  embeds: resolveBuiltinEmbedOptions(options.embeds),
1130
1804
  mdx: options.mdx,
1131
1805
  mdxDocumentProps: options.mdxDocumentProps ?? false
1132
1806
  };
1133
1807
  }
1808
+ function formatSvelteCompilerWarning(warning) {
1809
+ const message = `${warning.code ? `[${warning.code}] ` : ""}${warning.message}`;
1810
+ return warning.frame ? `${message}\n${warning.frame}` : message;
1811
+ }
1134
1812
  function resolveCodeAnnotationsOptions(options) {
1135
1813
  if (!options) return {
1136
1814
  enabled: false,
@@ -1154,8 +1832,8 @@ export { mount, unmount } from 'svelte';
1154
1832
  function generateComponentsModule(componentMap) {
1155
1833
  const imports = [];
1156
1834
  const exports = [];
1157
- componentMap.forEach((path$2, name) => {
1158
- imports.push(`import ${name} from '${path$2}';`);
1835
+ componentMap.forEach((path, name) => {
1836
+ imports.push(`import ${name} from '${path}';`);
1159
1837
  exports.push(` ${name},`);
1160
1838
  });
1161
1839
  return `
@@ -1168,49 +1846,17 @@ ${exports.join("\n")}
1168
1846
  export default components;
1169
1847
  `;
1170
1848
  }
1171
- async function resolveComponentsGlob(componentsOption, root) {
1172
- if (typeof componentsOption === "object" && !Array.isArray(componentsOption)) return componentsOption;
1173
- const patterns = Array.isArray(componentsOption) ? componentsOption : [componentsOption];
1174
- const result = {};
1175
- for (const pattern of patterns) {
1176
- const files = await globFiles(pattern, root);
1177
- for (const file of files) {
1178
- const componentName = toPascalCase(path.basename(file, path.extname(file)));
1179
- result[componentName] = "./" + path.relative(root, file).replace(/\\/g, "/");
1180
- }
1181
- }
1182
- return result;
1183
- }
1184
- async function globFiles(pattern, root) {
1185
- const files = [];
1186
- if (!pattern.includes("*")) {
1187
- const fullPath = path.resolve(root, pattern);
1188
- if (fs.existsSync(fullPath)) files.push(fullPath);
1189
- return files;
1190
- }
1191
- const parts = pattern.split("*");
1192
- const baseDir = path.resolve(root, parts[0]);
1193
- const ext = parts[1] || "";
1194
- if (!fs.existsSync(baseDir)) return files;
1195
- if (pattern.includes("**")) await walkDir(baseDir, files, ext);
1196
- else {
1197
- const entries = await fs.promises.readdir(baseDir, { withFileTypes: true });
1198
- for (const entry of entries) if (entry.isFile() && entry.name.endsWith(ext)) files.push(path.join(baseDir, entry.name));
1199
- }
1200
- return files;
1201
- }
1202
- async function walkDir(dir, files, ext) {
1203
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
1204
- for (const entry of entries) {
1205
- const fullPath = path.join(dir, entry.name);
1206
- if (entry.isDirectory()) await walkDir(fullPath, files, ext);
1207
- else if (entry.isFile() && entry.name.endsWith(ext)) files.push(fullPath);
1208
- }
1209
- }
1210
- function toPascalCase(str) {
1211
- return str.replace(/[-_](\w)/g, (_, c) => c.toUpperCase()).replace(/^\w/, (c) => c.toUpperCase());
1212
- }
1213
1849
  //#endregion
1850
+ exports.SVELTE_HTML_HOST_MODULES_VIRTUAL_ID = SVELTE_HTML_HOST_MODULES_VIRTUAL_ID;
1851
+ exports.SvelteHtmlHostRenderError = SvelteHtmlHostRenderError;
1852
+ exports.createSvelteHtmlHostCollectionDocuments = createSvelteHtmlHostCollectionDocuments;
1853
+ exports.createSvelteHtmlHostDomRenderer = require_html_host_client.createSvelteHtmlHostDomRenderer;
1854
+ exports.createSvelteHtmlHostHydrate = createSvelteHtmlHostHydrate;
1855
+ exports.createSvelteHtmlHostIslandRegistry = createSvelteHtmlHostIslandRegistry;
1856
+ exports.createSvelteHtmlHostLazyHydrate = require_html_host_client.createSvelteHtmlHostLazyHydrate;
1857
+ exports.createSvelteHtmlHostRenderer = createSvelteHtmlHostRenderer;
1858
+ exports.initSvelteHtmlHost = require_html_host_client.initSvelteHtmlHost;
1859
+ exports.loadSvelteHtmlHostDomRuntime = require_html_host_client.loadSvelteHtmlHostDomRuntime;
1214
1860
  Object.defineProperty(exports, "oxContent", {
1215
1861
  enumerable: true,
1216
1862
  get: function() {
@@ -1218,9 +1864,14 @@ Object.defineProperty(exports, "oxContent", {
1218
1864
  }
1219
1865
  });
1220
1866
  exports.oxContentSvelte = oxContentSvelte;
1867
+ exports.readSvelteHtmlHostSlot = require_html_host_client.readSvelteHtmlHostSlot;
1221
1868
  Object.defineProperty(exports, "renderHead", {
1222
1869
  enumerable: true,
1223
1870
  get: function() {
1224
1871
  return _ox_content_vite_plugin.renderHead;
1225
1872
  }
1226
1873
  });
1874
+ exports.renderSvelteHtmlHost = renderSvelteHtmlHost;
1875
+ exports.resolveSvelteHtmlHostCollectionDocuments = resolveSvelteHtmlHostCollectionDocuments;
1876
+ exports.resolveSvelteHtmlHostIslandRegistry = resolveSvelteHtmlHostIslandRegistry;
1877
+ exports.toSvelteHtmlHostClientModuleId = toSvelteHtmlHostClientModuleId;