@hamur/adapter-svelte 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +31 -2
  3. package/dist/chunks/browser-index-324qgh1c.js +190 -0
  4. package/dist/chunks/browser-index-evqp5a71.js +64 -0
  5. package/dist/chunks/browser-index-xc6081e3.js +9 -0
  6. package/dist/src/adapter.js +480 -0
  7. package/dist/src/index.js +1161 -0
  8. package/dist/src/runtime/client.js +65 -0
  9. package/dist/src/runtime/island.js +72 -0
  10. package/dist/src/runtime/server.js +142 -0
  11. package/dist/types/src/activation.d.ts +15 -0
  12. package/dist/types/src/adapter.d.ts +2 -0
  13. package/dist/types/src/async-data.d.ts +21 -0
  14. package/dist/types/src/boundary-error.d.ts +9 -0
  15. package/dist/types/src/client-only.d.ts +6 -0
  16. package/dist/types/src/context.d.ts +87 -0
  17. package/dist/types/src/deferred.svelte.d.ts +6 -0
  18. package/dist/types/src/effect.svelte.d.ts +2 -0
  19. package/dist/types/src/hydrating.d.ts +4 -0
  20. package/dist/types/src/index.d.ts +270 -0
  21. package/dist/types/src/island-html.d.ts +13 -0
  22. package/dist/types/src/keepalive.d.ts +11 -0
  23. package/dist/types/src/lazy-hydration.d.ts +25 -0
  24. package/dist/types/src/markdown-page.d.ts +9 -0
  25. package/dist/types/src/plugin.d.ts +52 -0
  26. package/dist/types/src/runtime/client.d.ts +12 -0
  27. package/dist/types/src/runtime/hmr.d.ts +28 -0
  28. package/dist/types/src/runtime/hydration-dev.d.ts +1 -0
  29. package/dist/types/src/runtime/hydration.d.ts +8 -0
  30. package/dist/types/src/runtime/island.d.ts +8 -0
  31. package/dist/types/src/runtime/server.d.ts +12 -0
  32. package/dist/types/src/server-component.d.ts +3 -0
  33. package/dist/types/src/store.d.ts +7 -0
  34. package/dist/types/src/svg.d.ts +10 -0
  35. package/package.json +58 -4
  36. package/src/Announcer.svelte +26 -0
  37. package/src/Await.svelte +43 -0
  38. package/src/AwaitAsync.svelte +42 -0
  39. package/src/BodyAttrs.svelte +7 -0
  40. package/src/Caught.svelte +41 -0
  41. package/src/ClientComponent.svelte +35 -0
  42. package/src/ClientFallback.svelte +46 -0
  43. package/src/ClientOnly.svelte +22 -0
  44. package/src/DefaultErrorPage.svelte +15 -0
  45. package/src/DevOnly.svelte +12 -0
  46. package/src/ErrorBoundary.svelte +14 -0
  47. package/src/FallbackEffect.svelte +9 -0
  48. package/src/Form.svelte +96 -0
  49. package/src/HeadLink.svelte +7 -0
  50. package/src/HeadMeta.svelte +7 -0
  51. package/src/HeadScript.svelte +7 -0
  52. package/src/HeadStyle.svelte +7 -0
  53. package/src/HeadTitle.svelte +6 -0
  54. package/src/HtmlAttrs.svelte +7 -0
  55. package/src/HttpHeader.svelte +7 -0
  56. package/src/HttpStatusCode.svelte +7 -0
  57. package/src/Island.svelte +59 -0
  58. package/src/IslandChildren.svelte +7 -0
  59. package/src/KeptOutlet.svelte +46 -0
  60. package/src/KeptPage.svelte +55 -0
  61. package/src/LazyHydration.svelte +54 -0
  62. package/src/Link.svelte +209 -0
  63. package/src/LoadingIndicator.svelte +18 -0
  64. package/src/MarkdownNodes.svelte +36 -0
  65. package/src/MarkdownRenderer.svelte +20 -0
  66. package/src/MarkdownSlots.svelte +33 -0
  67. package/src/Navigate.svelte +10 -0
  68. package/src/Nest.svelte +83 -0
  69. package/src/Outlet.svelte +31 -0
  70. package/src/Rethrow.svelte +7 -0
  71. package/src/Root.svelte +29 -0
  72. package/src/RouteAnnouncer.svelte +47 -0
  73. package/src/Scoped.svelte +11 -0
  74. package/src/ServerComponent.svelte +19 -0
  75. package/src/ServerComponentClient.svelte +64 -0
  76. package/src/ServerIsland.svelte +26 -0
  77. package/src/Slotted.svelte +11 -0
  78. package/src/Thrown.svelte +9 -0
  79. package/src/Time.svelte +23 -0
  80. package/src/activation.ts +51 -0
  81. package/src/adapter.ts +24 -0
  82. package/src/async-data.ts +105 -0
  83. package/src/boundary-error.ts +77 -0
  84. package/src/client-only.ts +8 -0
  85. package/src/context.ts +227 -0
  86. package/src/deferred.svelte.ts +33 -0
  87. package/src/effect.svelte.ts +7 -0
  88. package/src/env.d.ts +3 -0
  89. package/src/hydrating.ts +18 -0
  90. package/src/index.ts +1337 -0
  91. package/src/island-html.ts +58 -0
  92. package/src/keepalive.ts +12 -0
  93. package/src/lazy-hydration.ts +89 -0
  94. package/src/markdown-page.ts +17 -0
  95. package/src/plugin.ts +558 -0
  96. package/src/runtime/client.ts +61 -0
  97. package/src/runtime/hmr.ts +177 -0
  98. package/src/runtime/hydration-dev.ts +22 -0
  99. package/src/runtime/hydration.ts +7 -0
  100. package/src/runtime/island.ts +94 -0
  101. package/src/runtime/server.ts +87 -0
  102. package/src/server-component.ts +13 -0
  103. package/src/store.ts +31 -0
  104. package/src/svelte.d.ts +5 -0
  105. package/src/svg.ts +30 -0
  106. package/src/webmcp.d.ts +18 -0
@@ -0,0 +1,480 @@
1
+ // @bun
2
+ // packages/adapter-svelte/src/adapter.ts
3
+ import { ADAPTER_CONTRACT, defineAdapter } from "hamur/adapter";
4
+ import { clientComponentModule, serverComponentModule } from "hamur/adapter/build";
5
+
6
+ // packages/adapter-svelte/src/plugin.ts
7
+ import { realpathSync } from "fs";
8
+ import { join, relative } from "path";
9
+ import { DiagnosticError } from "hamur/kit";
10
+ import { compile, compileModule, parse, preprocess } from "svelte/compiler";
11
+ var STYLE_NS = "hamur-svelte-style";
12
+ var HMR_RUNTIME = join(import.meta.dir + "/../../src", "runtime/hmr.ts");
13
+ var CLIENT_RUNTIME = join(import.meta.dir + "/../../src", "runtime/client.ts");
14
+ var HYDRATION_DEV = join(import.meta.dir + "/../../src", "runtime/hydration-dev.ts");
15
+ var AWAIT = join(import.meta.dir + "/../../src", "Await.svelte");
16
+ var AWAIT_ASYNC = join(import.meta.dir + "/../../src", "AwaitAsync.svelte");
17
+ var PREPROCESSED = {
18
+ scss: "sass",
19
+ sass: "sass",
20
+ less: "less",
21
+ styl: "stylus",
22
+ stylus: "stylus"
23
+ };
24
+ var STYLE_TAG = /<style\b([^>]*)>/g;
25
+ var LANG_ATTRIBUTE = /\blang\s*=\s*["']?(\w+)/;
26
+ var STYLE_BLOCK = /(<style\b[^>]*>)([\s\S]*?)(<\/style>)/g;
27
+ var DEFAULT_EXPORT = /^export default (\w+);$/gm;
28
+ var NOT_A_MODULE = /^svelte(?:\/|$)|^#hamur\/|\.(?:css|scss|sass|less|styl|svg|png|jpe?g|gif|webp|avif|ico|json|txt|md|wasm|html)(?:\?.*)?$|\?/i;
29
+ function devOnlyNames(source) {
30
+ const names = new Set;
31
+ for (const found of source.matchAll(/import\s*\{([^}]*)\}\s*from\s*["']@hamur\/adapter-svelte["']/g)) {
32
+ for (const part of found[1].split(",")) {
33
+ const [imported, local = imported] = part.trim().split(/\s+as\s+/).map((name) => name.trim());
34
+ if (imported === "DevOnly" && local)
35
+ names.add(local);
36
+ }
37
+ }
38
+ return names;
39
+ }
40
+ function dropDevOnlyMarkup(source) {
41
+ const names = devOnlyNames(source);
42
+ if (!names.size)
43
+ return source;
44
+ let root;
45
+ try {
46
+ root = parse(source, { modern: true });
47
+ } catch {
48
+ return source;
49
+ }
50
+ const cuts = [];
51
+ const seen = new Set;
52
+ const visit = (node) => {
53
+ if (typeof node !== "object" || node === null || seen.has(node))
54
+ return;
55
+ seen.add(node);
56
+ if (Array.isArray(node))
57
+ return node.forEach(visit);
58
+ const element = node;
59
+ if (element.type === "Component" && element.name !== undefined && names.has(element.name) && element.fragment) {
60
+ for (const child of element.fragment.nodes) {
61
+ if (child.type === "SnippetBlock" && child.expression?.name === "fallback")
62
+ visit(child);
63
+ else
64
+ cuts.push([child.start, child.end]);
65
+ }
66
+ return;
67
+ }
68
+ for (const [key, value] of Object.entries(node))
69
+ if (key !== "metadata" && key !== "parent")
70
+ visit(value);
71
+ };
72
+ visit(root.fragment);
73
+ let out = source;
74
+ for (const [start, end] of cuts.sort((a, b) => b[0] - a[0]))
75
+ out = `${out.slice(0, start)}${out.slice(start, end).replace(/[^\n]/g, "")}${out.slice(end)}`;
76
+ return out;
77
+ }
78
+ function locateRootElement(source, file) {
79
+ let root;
80
+ try {
81
+ const scriptsOnly = source.replace(STYLE_BLOCK, (_, open, body, close) => `${open}${body.replace(/[^\n]/g, " ")}${close}`);
82
+ root = parse(scriptsOnly, { filename: file, modern: true });
83
+ } catch {
84
+ return source;
85
+ }
86
+ const significant = root.fragment.nodes.filter((node) => node.type === "Text" ? (node.data ?? "").trim() !== "" : node.type !== "Comment" && node.type !== "SnippetBlock");
87
+ const [node] = significant;
88
+ if (significant.length !== 1 || node.type !== "RegularElement")
89
+ return source;
90
+ const before = source.slice(0, node.start);
91
+ const line = before.split(`
92
+ `).length;
93
+ const column = node.start - (before.lastIndexOf(`
94
+ `) + 1) + 1;
95
+ const at = node.start + 1 + node.name.length;
96
+ return `${source.slice(0, at)} data-hamur-src="${file}:${line}:${column}"${source.slice(at)}`;
97
+ }
98
+ var ESM_ENV_IMPORT = /import\s*\{([^}]*)\}\s*from\s*(["'])esm-env\2\s*;?/g;
99
+ var ESM_ENV_VALUES = { DEV: "false", BROWSER: "true", NODE: "false" };
100
+ function foldEsmEnv(source) {
101
+ return source.replace(ESM_ENV_IMPORT, (whole, list) => {
102
+ const declarations = [];
103
+ for (const part of list.split(",")) {
104
+ if (part.trim() === "")
105
+ continue;
106
+ const match = /^\s*(\w+)(?:\s+as\s+(\w+))?\s*$/.exec(part);
107
+ const value = match && ESM_ENV_VALUES[match[1]];
108
+ if (!match || value === undefined)
109
+ return whole;
110
+ declarations.push(`${match[2] ?? match[1]} = ${value}`);
111
+ }
112
+ return declarations.length === 0 ? whole : `const ${declarations.join(", ")};`;
113
+ });
114
+ }
115
+ function located(error, path, source, rootDir, lineOf = (line) => line) {
116
+ const { message, code, start: compiled } = error ?? {};
117
+ if (typeof message !== "string" || typeof compiled?.line !== "number" || typeof compiled.column !== "number")
118
+ return error;
119
+ const start = { line: lineOf(compiled.line), column: compiled.column };
120
+ const shown = rootDir === undefined ? path : relative(rootDir, path);
121
+ const file = shown === "" || shown.startsWith("..") ? path : shown.split("\\").join("/");
122
+ const column = start.column + 1;
123
+ const [first, ...rest] = message.split(`
124
+ `);
125
+ const lineText = source.split(/\r?\n/)[start.line - 1];
126
+ const lines = [`${file}:${start.line}:${column}: ${first}`];
127
+ if (lineText !== undefined) {
128
+ const gutter = String(start.line);
129
+ const pad = [...lineText.slice(0, start.column)].map((char) => char === "\t" ? "\t" : " ").join("");
130
+ lines.push(` ${gutter} | ${lineText}`, ` ${" ".repeat(gutter.length)} | ${pad}^`);
131
+ }
132
+ return Object.assign(new Error([...lines, ...rest].join(`
133
+ `), { cause: error }), code === undefined ? {} : { code });
134
+ }
135
+ function withInlineMap(code, map, path, written, rootDir, shift = 0) {
136
+ if (!map)
137
+ return code;
138
+ const file = relative(rootDir, path).split("\\").join("/");
139
+ const inline = { ...map, sources: [file], sourcesContent: [written], mappings: ";".repeat(shift) + map.mappings };
140
+ return `${code}
141
+ //# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(inline)).toString("base64")}`;
142
+ }
143
+ var ASYNC_HINT = "Svelte async SSR is experimental: set experimental.svelteAsync: true";
144
+ function hinted(error) {
145
+ if (error?.code !== "experimental_async")
146
+ return error;
147
+ error.message += `
148
+ ${ASYNC_HINT}`;
149
+ return error;
150
+ }
151
+ async function preprocessStyles(source, path, preprocessStyle) {
152
+ const langs = [...source.matchAll(STYLE_TAG)].map((tag) => LANG_ATTRIBUTE.exec(tag[1])?.[1]).filter((lang) => lang !== undefined && (lang in PREPROCESSED));
153
+ if (langs.length === 0)
154
+ return;
155
+ const lines = (text) => text.split(`
156
+ `).length - 1;
157
+ const blocks = [];
158
+ let cursor = 0;
159
+ const processed = await preprocess(source, {
160
+ name: "hamur-style",
161
+ async style({ content, attributes }) {
162
+ const at = source.indexOf(content, cursor);
163
+ cursor = at + content.length;
164
+ const lang = String(attributes.lang ?? "");
165
+ if (!(lang in PREPROCESSED))
166
+ return;
167
+ if (!preprocessStyle)
168
+ throw new DiagnosticError("HAMUR_E4201", `<style lang="${lang}"> needs the @hamur/css module: install @hamur/css and ${PREPROCESSED[lang]} and add "@hamur/css" to modules`);
169
+ const line = lines(source.slice(0, at)) + 1;
170
+ const css = await preprocessStyle({ lang, code: content, file: path });
171
+ blocks.push({ line, before: lines(content), after: lines(css.code) });
172
+ return { code: css.code, dependencies: css.dependencies };
173
+ }
174
+ }, { filename: path });
175
+ const lineOf = (line) => {
176
+ let shift = 0;
177
+ for (const block of blocks.sort((a, b) => a.line - b.line)) {
178
+ const from = block.line + shift;
179
+ if (line < from)
180
+ break;
181
+ if (line < from + block.after)
182
+ return block.line;
183
+ shift += block.after - block.before;
184
+ }
185
+ return line - shift;
186
+ };
187
+ return { code: processed.code, original: source, map: processed.map, lineOf };
188
+ }
189
+ function compileSvelte(path, source, target, hmr = false, rootDir, svelteAsync = false, preprocessed, dev = false) {
190
+ try {
191
+ const result = compile(source, {
192
+ filename: path,
193
+ generate: target,
194
+ css: "external",
195
+ dev,
196
+ hmr,
197
+ ...preprocessed?.map ? { sourcemap: preprocessed.map } : {},
198
+ ...svelteAsync ? { experimental: { async: true } } : {}
199
+ });
200
+ return { code: result.js.code, css: result.css?.code, map: result.js.map };
201
+ } catch (error) {
202
+ throw located(svelteAsync ? error : hinted(error), path, preprocessed?.original ?? source, rootDir, preprocessed?.lineOf);
203
+ }
204
+ }
205
+ function compileSvelteModule(path, source, target, rootDir, svelteAsync = false, dev = false) {
206
+ const js = path.endsWith(".ts") ? new Bun.Transpiler({ loader: "ts" }).transformSync(source) : source;
207
+ try {
208
+ return compileModule(js, {
209
+ filename: path,
210
+ generate: target,
211
+ dev,
212
+ ...svelteAsync ? { experimental: { async: true } } : {}
213
+ }).js.code;
214
+ } catch (error) {
215
+ throw located(svelteAsync ? error : hinted(error), path, js, rootDir);
216
+ }
217
+ }
218
+ function appModuleId(rootDir, buildDir) {
219
+ let real = rootDir;
220
+ try {
221
+ real = realpathSync(rootDir);
222
+ } catch {}
223
+ const roots = [...new Set([rootDir, real])];
224
+ const build = relative(rootDir, buildDir);
225
+ const inBuild = (id) => build !== "" && !build.startsWith("..") && (id === build || id.startsWith(`${build}/`));
226
+ return (path) => {
227
+ if (path.includes("/node_modules/"))
228
+ return;
229
+ for (const root of roots) {
230
+ const id = relative(root, path);
231
+ if (!id.startsWith("..") && !id.startsWith("/"))
232
+ return inBuild(id) ? undefined : id;
233
+ }
234
+ return;
235
+ };
236
+ }
237
+ function stateRune(init) {
238
+ if (init?.type !== "CallExpression")
239
+ return;
240
+ const { callee } = init;
241
+ if (callee.type === "Identifier" && callee.name === "$state")
242
+ return "$state";
243
+ if (callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && callee.object.name === "$state" && callee.property.name === "raw")
244
+ return "$state.raw";
245
+ return;
246
+ }
247
+ function hotTransform(source, file, rootDir, runtime = HMR_RUNTIME) {
248
+ let ast;
249
+ try {
250
+ const scriptsOnly = source.replace(STYLE_BLOCK, (_, open, body, close) => `${open}${body.replace(/[^\n]/g, " ")}${close}`);
251
+ ast = parse(scriptsOnly, { filename: file, modern: true });
252
+ } catch {
253
+ return source;
254
+ }
255
+ const { instance, module } = ast;
256
+ const edits = [];
257
+ const names = [];
258
+ const signature = [];
259
+ for (const statement of instance?.content.body ?? []) {
260
+ if (statement.type !== "VariableDeclaration")
261
+ continue;
262
+ for (const declarator of statement.declarations) {
263
+ const rune = stateRune(declarator.init);
264
+ if (declarator.id.type !== "Identifier" || !rune)
265
+ continue;
266
+ const args = declarator.init.arguments;
267
+ const i = names.length;
268
+ names.push(declarator.id.name);
269
+ signature.push(`${declarator.id.name}=${rune}(${args.length ? source.slice(args[0].start, args.at(-1).end) : ""})`);
270
+ if (args.length)
271
+ edits.push({
272
+ at: args[0].start,
273
+ end: args[0].end,
274
+ text: `__hamurHotI.take(${i}, (${source.slice(args[0].start, args[0].end)}))`
275
+ });
276
+ else
277
+ edits.push({ at: declarator.init.end - 1, text: `__hamurHotI.take(${i}, undefined)` });
278
+ }
279
+ }
280
+ if (instance) {
281
+ edits.push({ at: instance.content.start, text: "const __hamurHotI = __hamurHotM.enter();" });
282
+ if (names.length)
283
+ edits.push({
284
+ at: instance.content.body.at(-1).end,
285
+ text: `;__hamurHotI.read(() => [${names.join(", ")}]);`
286
+ });
287
+ }
288
+ const dependencies = new Set;
289
+ for (const script of [module, instance])
290
+ for (const statement of script?.content.body ?? [])
291
+ if (statement.type === "ImportDeclaration" && statement.importKind !== "type" && !NOT_A_MODULE.test(statement.source.value))
292
+ dependencies.add(statement.source.value);
293
+ const deps = [...dependencies];
294
+ const head = [
295
+ `import { hotModule as __hamurHot } from ${JSON.stringify(runtime)};`,
296
+ ...deps.map((path, index) => `import * as __hamurHotDep${index} from ${JSON.stringify(path)};`),
297
+ `const __hamurHotM = __hamurHot(import.meta.hot ? import.meta.hot.data.hamur : undefined, ${JSON.stringify(relative(rootDir, file))}, ${JSON.stringify(signature.join(";"))}, ${JSON.stringify(String(Bun.hash(source)))}, [${deps.map((_, index) => `__hamurHotDep${index}`).join(", ")}]);`,
298
+ `if (import.meta.hot) import.meta.hot.data.hamur = __hamurHotM;`
299
+ ].join(" ");
300
+ if (module)
301
+ edits.push({ at: module.content.start, text: head });
302
+ else {
303
+ const lang = instance && /\slang\s*=\s*["']ts["']/.test(source.slice(instance.start, instance.content.start)) ? ` lang="ts"` : "";
304
+ edits.push({ at: instance?.start ?? 0, text: `<script module${lang}>${head}</script>` });
305
+ }
306
+ let out = source;
307
+ for (const { at, end = at, text } of edits.sort((a, b) => b.at - a.at))
308
+ out = `${out.slice(0, at)}${text}${out.slice(end)}`;
309
+ return out;
310
+ }
311
+ function hotTail(code) {
312
+ const names = [...code.matchAll(DEFAULT_EXPORT)];
313
+ return names.length === 1 ? `${code}
314
+ __hamurHotM.component(${names[0][1]});` : code;
315
+ }
316
+ function styleGuard(styled) {
317
+ return `if (import.meta.hot) { const was = import.meta.hot.data.hamurStyled; import.meta.hot.data.hamurStyled = ${styled}; if (was !== undefined && was !== ${styled}) location.reload(); }`;
318
+ }
319
+ function sameFile(a, b) {
320
+ try {
321
+ return realpathSync(a) === realpathSync(b);
322
+ } catch {
323
+ return false;
324
+ }
325
+ }
326
+ function svelteEsmEnv() {
327
+ return {
328
+ name: "hamur-svelte-esm-env",
329
+ filter: { id: /[\\/]node_modules[\\/]svelte[\\/]src[\\/].*\.js$/ },
330
+ transform(code) {
331
+ const folded = foldEsmEnv(code);
332
+ return folded === code ? undefined : folded;
333
+ }
334
+ };
335
+ }
336
+ function sveltePlugin(ctx) {
337
+ const { target, dev, hmr, svelteAsync = false } = ctx;
338
+ const isAwait = (path) => path === AWAIT || svelteAsync && sameFile(path, AWAIT);
339
+ const styles = new Map;
340
+ const appModule = hmr && target === "client" ? appModuleId(ctx.rootDir, ctx.buildDir) : () => {
341
+ return;
342
+ };
343
+ const locatable = dev ? appModuleId(ctx.rootDir, ctx.buildDir) : () => {
344
+ return;
345
+ };
346
+ return {
347
+ name: `hamur-svelte-${target}`,
348
+ setup(build) {
349
+ build.onLoad({ filter: /\.svelte$/, namespace: "file" }, async ({ path }) => {
350
+ const written = await Bun.file(isAwait(path) && svelteAsync ? AWAIT_ASYNC : path).text();
351
+ const file = locatable(path);
352
+ const marked = dev ? file === undefined ? written : locateRootElement(written, file) : dropDevOnlyMarkup(written);
353
+ const id = appModule(path);
354
+ const hot = id === undefined ? marked : hotTransform(marked, join(ctx.rootDir, id), ctx.rootDir);
355
+ const preprocessed = await preprocessStyles(hot, path, ctx.preprocessStyle);
356
+ let compiled;
357
+ try {
358
+ compiled = compileSvelte(path, preprocessed?.code ?? hot, target, hmr, ctx.rootDir, svelteAsync, preprocessed, dev);
359
+ } catch (error) {
360
+ if (hot !== written) {
361
+ const plain = await preprocessStyles(written, path, ctx.preprocessStyle);
362
+ compileSvelte(path, plain?.code ?? written, target, hmr, ctx.rootDir, svelteAsync, plain, dev);
363
+ }
364
+ throw error;
365
+ }
366
+ const code = hot === marked ? compiled.code : hotTail(compiled.code);
367
+ const css = target === "client" ? compiled.css : undefined;
368
+ if (css)
369
+ styles.set(`${path}.css`, css);
370
+ const head = [
371
+ css ? `import ${JSON.stringify(`${STYLE_NS}:${path}.css`)};` : "",
372
+ hot === marked ? "" : styleGuard(!!css)
373
+ ].join("");
374
+ if (head === "")
375
+ return { contents: withInlineMap(code, compiled.map, path, written, ctx.rootDir), loader: "js" };
376
+ return {
377
+ contents: `${head}
378
+ ${withInlineMap(code, compiled.map, path, written, ctx.rootDir, 1)}`,
379
+ loader: "js"
380
+ };
381
+ });
382
+ build.onLoad({ filter: /\.svelte\.(ts|js)$/, namespace: "file" }, async ({ path }) => ({
383
+ contents: compileSvelteModule(path, await Bun.file(path).text(), target, ctx.rootDir, svelteAsync, dev),
384
+ loader: "js"
385
+ }));
386
+ build.onResolve({ filter: new RegExp(`^${STYLE_NS}:`) }, ({ path }) => ({
387
+ path: path.slice(STYLE_NS.length + 1),
388
+ namespace: STYLE_NS
389
+ }));
390
+ build.onLoad({ filter: /.*/, namespace: STYLE_NS }, async ({ path }) => {
391
+ const first = styles.get(path);
392
+ if (first !== undefined && !hmr) {
393
+ styles.delete(path);
394
+ return { contents: first, loader: "css" };
395
+ }
396
+ const file = path.slice(0, -".css".length);
397
+ const written = await Bun.file(file).text();
398
+ const preprocessed = await preprocessStyles(written, file, ctx.preprocessStyle);
399
+ return {
400
+ contents: compileSvelte(file, preprocessed?.code ?? written, "client", hmr, ctx.rootDir, svelteAsync, preprocessed, dev).css ?? "",
401
+ loader: "css"
402
+ };
403
+ });
404
+ }
405
+ };
406
+ }
407
+ function svelteHydrationPlugin() {
408
+ return {
409
+ name: "hamur-svelte-hydration",
410
+ filter: { id: new RegExp(`^${CLIENT_RUNTIME.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`) },
411
+ transform: (code) => `import ${JSON.stringify(HYDRATION_DEV)}; ${code}`
412
+ };
413
+ }
414
+
415
+ // packages/adapter-svelte/src/svg.ts
416
+ import { svgCode } from "hamur/adapter";
417
+ var attributesCode = (code, attrs) => Object.entries(attrs).map(([name, value]) => ` ${name}={${code.value(value)}}`).join("");
418
+ function nodeCode(code, node) {
419
+ if (typeof node === "string" || Array.isArray(node))
420
+ return `{${code.value(node)}}`;
421
+ return `<${node.tag}${attributesCode(code, code.attrs(node))}>${node.children.map((child) => nodeCode(code, child)).join("")}</${node.tag}>`;
422
+ }
423
+ function module(svg) {
424
+ const code = svgCode(svg, { title: "title", props: "rest" });
425
+ const hidden = code.hidden ? `
426
+ const hidden = $derived(${code.hidden} ? "true" : undefined);` : "";
427
+ const contents = `<script>
428
+ let { title, ...rest } = $props();
429
+ const id = $props.id();
430
+ const uid = id.replace(/[^\\w-]/g, "_");${hidden}
431
+ </script>
432
+
433
+ <svg${attributesCode(code, svg.attrs)}${code.hidden ? " aria-hidden={hidden}" : ""} {...rest}>{#if title != null}<title>{title}</title>{/if}${svg.children.map((child) => nodeCode(code, child)).join("")}</svg>
434
+ `;
435
+ return { contents, extension: ".svelte" };
436
+ }
437
+ var svgComponent = {
438
+ types: `import("svelte").Component<import("svelte/elements").SVGAttributes<SVGSVGElement> & { title?: string }>`,
439
+ module
440
+ };
441
+
442
+ // packages/adapter-svelte/src/markdown-page.ts
443
+ import { markdownPageCode } from "hamur/adapter/build";
444
+ function module2(source) {
445
+ const { imports, value, props, head } = markdownPageCode(source);
446
+ const contents = `<script>
447
+ ${imports}import { MarkdownRenderer, useHead } from "@hamur/adapter-svelte";
448
+
449
+ const value = ${value};${head ? `
450
+ useHead(${head});` : ""}
451
+ </script>
452
+
453
+ <MarkdownRenderer {...${props}} />
454
+ `;
455
+ return { contents, extension: ".svelte" };
456
+ }
457
+ var markdownComponent = { module: module2 };
458
+
459
+ // packages/adapter-svelte/src/adapter.ts
460
+ var adapter_default = defineAdapter({
461
+ name: "svelte",
462
+ contract: ADAPTER_CONTRACT,
463
+ extensions: [".svelte"],
464
+ clientEntry: "@hamur/adapter-svelte/runtime/client",
465
+ serverEntry: "@hamur/adapter-svelte/runtime/server",
466
+ keepAliveOutlet: "@hamur/adapter-svelte/runtime/keepalive",
467
+ islandEntry: "@hamur/adapter-svelte/runtime/island",
468
+ errorPage: "@hamur/adapter-svelte/error-page",
469
+ plugins: (ctx) => [sveltePlugin(ctx)],
470
+ transforms: (ctx) => ctx.target === "client" ? ctx.dev ? [svelteHydrationPlugin()] : [svelteEsmEnv()] : [],
471
+ peers: ["svelte"],
472
+ trustedTypesPolicies: ["svelte-trusted-html"],
473
+ svgComponent,
474
+ markdownComponent,
475
+ serverComponent: { module: (component) => serverComponentModule(component, "@hamur/adapter-svelte/runtime") },
476
+ clientComponent: { module: (component) => clientComponentModule(component, "@hamur/adapter-svelte/runtime") }
477
+ });
478
+ export {
479
+ adapter_default as default
480
+ };