@ogygia/compiler 0.0.0 → 0.14.1

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 (160) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -1
  3. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  4. package/dist/app-spec.d.ts +18 -0
  5. package/dist/app-spec.js +22 -0
  6. package/dist/blank-styles.d.ts +1 -0
  7. package/dist/blank-styles.js +24 -0
  8. package/dist/bom.d.ts +2 -0
  9. package/dist/bom.js +7 -0
  10. package/dist/build-cache.d.ts +13 -0
  11. package/dist/build-cache.js +65 -0
  12. package/dist/ctx.d.ts +238 -0
  13. package/dist/ctx.js +221 -0
  14. package/dist/dev/css-scope.d.ts +16 -0
  15. package/dist/dev/css-scope.js +32 -0
  16. package/dist/dev/dev-hmr.d.ts +24 -0
  17. package/dist/dev/dev-hmr.js +51 -0
  18. package/dist/dev/hmr.d.ts +34 -0
  19. package/dist/dev/hmr.js +52 -0
  20. package/dist/driver.d.ts +351 -0
  21. package/dist/driver.js +1402 -0
  22. package/dist/exports/index.d.ts +77 -0
  23. package/dist/exports/index.js +349 -0
  24. package/dist/exports/parse.d.ts +65 -0
  25. package/dist/exports/parse.js +251 -0
  26. package/dist/fouc-css.d.ts +112 -0
  27. package/dist/fouc-css.js +314 -0
  28. package/dist/free-vars.d.ts +32 -0
  29. package/dist/free-vars.js +454 -0
  30. package/dist/fs.d.ts +31 -0
  31. package/dist/fs.js +82 -0
  32. package/dist/ids.d.ts +49 -0
  33. package/dist/ids.js +52 -0
  34. package/dist/index.d.ts +23 -0
  35. package/dist/index.js +23 -0
  36. package/dist/kit.d.ts +204 -0
  37. package/dist/kit.js +554 -0
  38. package/dist/leg.d.ts +34 -0
  39. package/dist/leg.js +26 -0
  40. package/dist/link/analyses.d.ts +26 -0
  41. package/dist/link/analyses.js +237 -0
  42. package/dist/link/build-output.d.ts +47 -0
  43. package/dist/link/build-output.js +168 -0
  44. package/dist/link/caps.d.ts +32 -0
  45. package/dist/link/caps.js +39 -0
  46. package/dist/link/context-detect.d.ts +28 -0
  47. package/dist/link/context-detect.js +143 -0
  48. package/dist/link/emit-gate.d.ts +43 -0
  49. package/dist/link/emit-gate.js +55 -0
  50. package/dist/link/file-token.d.ts +11 -0
  51. package/dist/link/file-token.js +15 -0
  52. package/dist/link/island-deps.d.ts +183 -0
  53. package/dist/link/island-deps.js +802 -0
  54. package/dist/link/location-map.d.ts +24 -0
  55. package/dist/link/location-map.js +51 -0
  56. package/dist/link/own-reach.d.ts +15 -0
  57. package/dist/link/own-reach.js +188 -0
  58. package/dist/link/registry-stub.d.ts +50 -0
  59. package/dist/link/registry-stub.js +163 -0
  60. package/dist/link/relocations.d.ts +79 -0
  61. package/dist/link/relocations.js +204 -0
  62. package/dist/link/router-css.d.ts +38 -0
  63. package/dist/link/router-css.js +124 -0
  64. package/dist/link/runtime-entry.d.ts +103 -0
  65. package/dist/link/runtime-entry.js +183 -0
  66. package/dist/link/server-manifest.d.ts +25 -0
  67. package/dist/link/server-manifest.js +102 -0
  68. package/dist/link/transport.d.ts +42 -0
  69. package/dist/link/transport.js +91 -0
  70. package/dist/macros/dollar.d.ts +24 -0
  71. package/dist/macros/dollar.js +397 -0
  72. package/dist/macros/pipeline.d.ts +50 -0
  73. package/dist/macros/pipeline.js +133 -0
  74. package/dist/macros/source.d.ts +9 -0
  75. package/dist/macros/source.js +115 -0
  76. package/dist/macros/store.d.ts +22 -0
  77. package/dist/macros/store.js +217 -0
  78. package/dist/macros/wire.d.ts +17 -0
  79. package/dist/macros/wire.js +116 -0
  80. package/dist/map-chain.d.ts +18 -0
  81. package/dist/map-chain.js +42 -0
  82. package/dist/messages.d.ts +673 -0
  83. package/dist/messages.js +938 -0
  84. package/dist/ownership-stamps.d.ts +11 -0
  85. package/dist/ownership-stamps.js +112 -0
  86. package/dist/parse/oxc.d.ts +36 -0
  87. package/dist/parse/oxc.js +35 -0
  88. package/dist/parse/roots.d.ts +4 -0
  89. package/dist/parse/roots.js +27 -0
  90. package/dist/parse/scan.d.ts +65 -0
  91. package/dist/parse/scan.js +297 -0
  92. package/dist/parse/svelte-ast.d.ts +7 -0
  93. package/dist/parse/svelte-ast.js +99 -0
  94. package/dist/program.d.ts +140 -0
  95. package/dist/program.js +304 -0
  96. package/dist/queries.d.ts +105 -0
  97. package/dist/queries.js +326 -0
  98. package/dist/region/emit.d.ts +168 -0
  99. package/dist/region/emit.js +292 -0
  100. package/dist/region/identity.d.ts +32 -0
  101. package/dist/region/identity.js +46 -0
  102. package/dist/region/ir.d.ts +56 -0
  103. package/dist/region/ir.js +0 -0
  104. package/dist/region/marked-imports.d.ts +27 -0
  105. package/dist/region/marked-imports.js +265 -0
  106. package/dist/region/transform.d.ts +189 -0
  107. package/dist/region/transform.js +1565 -0
  108. package/dist/scan-facts.d.ts +36 -0
  109. package/dist/scan-facts.js +54 -0
  110. package/dist/script-request.d.ts +1 -0
  111. package/dist/script-request.js +33 -0
  112. package/dist/splice.d.ts +11 -0
  113. package/dist/splice.js +33 -0
  114. package/dist/transportables.d.ts +23 -0
  115. package/dist/transportables.js +144 -0
  116. package/dist/virtual/core.d.ts +158 -0
  117. package/dist/virtual/core.js +588 -0
  118. package/dist/virtual/resolver.d.ts +62 -0
  119. package/dist/virtual/resolver.js +265 -0
  120. package/dist/virtual/specifier.d.ts +10 -0
  121. package/dist/virtual/specifier.js +6 -0
  122. package/dist/virtual/table.d.ts +120 -0
  123. package/dist/virtual/table.js +54 -0
  124. package/dist/virtual/types.d.ts +17 -0
  125. package/dist/virtual/types.js +100 -0
  126. package/dist/virtual/value-names.d.ts +2 -0
  127. package/dist/virtual/value-names.js +18 -0
  128. package/dist/vite/definers.d.ts +16 -0
  129. package/dist/vite/definers.js +69 -0
  130. package/dist/vite/dev-maps.d.ts +34 -0
  131. package/dist/vite/dev-maps.js +91 -0
  132. package/dist/vite/index.d.ts +21 -0
  133. package/dist/vite/index.js +890 -0
  134. package/dist/vite/kit-dirs.d.ts +6 -0
  135. package/dist/vite/kit-dirs.js +53 -0
  136. package/dist/vite/late-island.d.ts +8 -0
  137. package/dist/vite/late-island.js +18 -0
  138. package/dist/vite/lazy-files.d.ts +2 -0
  139. package/dist/vite/lazy-files.js +72 -0
  140. package/dist/vite/options.d.ts +195 -0
  141. package/dist/vite/options.js +72 -0
  142. package/dist/vite/package-files.d.ts +3 -0
  143. package/dist/vite/package-files.js +88 -0
  144. package/dist/vite/paths.d.ts +16 -0
  145. package/dist/vite/paths.js +39 -0
  146. package/dist/vite/plugin-api.d.ts +316 -0
  147. package/dist/vite/plugin-api.js +328 -0
  148. package/dist/vite/route-watch.d.ts +15 -0
  149. package/dist/vite/route-watch.js +32 -0
  150. package/dist/vite/session.d.ts +28 -0
  151. package/dist/vite/session.js +43 -0
  152. package/dist/vite/sourcemaps.d.ts +19 -0
  153. package/dist/vite/sourcemaps.js +75 -0
  154. package/dist/vite/style-preprocess.d.ts +2 -0
  155. package/dist/vite/style-preprocess.js +84 -0
  156. package/dist/vite/svelte-entries.d.ts +4 -0
  157. package/dist/vite/svelte-entries.js +10 -0
  158. package/dist/vite/svelte-options.d.ts +20 -0
  159. package/dist/vite/svelte-options.js +22 -0
  160. package/package.json +87 -12
@@ -0,0 +1,251 @@
1
+ import { parse_module } from "../parse/oxc.js";
2
+ // src/exports/parse.ts
3
+ const name_of = (n) => {
4
+ if (!n) return "";
5
+ if (n.type === "Identifier") return n.name ?? "";
6
+ return typeof n.value === "string" ? n.value : String(n.value);
7
+ };
8
+ const ATTRIBUTES_CLAUSE_RE = /\s+(?:with|assert)\s*\{[\s\S]*\}/;
9
+ function program_body(code, id) {
10
+ const { program, ok } = parse_module(code, id);
11
+ if (!ok || !program) return null;
12
+ return program.body;
13
+ }
14
+ function attributes_text(code, node) {
15
+ const attrs = node.attributes;
16
+ if (!attrs || attrs.length === 0) return "";
17
+ const source = node.source;
18
+ const tail = code.slice(source.end, node.end);
19
+ return ATTRIBUTES_CLAUSE_RE.exec(tail)?.[0] ?? "";
20
+ }
21
+ function attribute_keys(node) {
22
+ const attrs = node.attributes;
23
+ if (!attrs || attrs.length === 0) return [];
24
+ return attrs.map((a) => name_of(a.key));
25
+ }
26
+ function imports_of(code, body) {
27
+ const out = [];
28
+ for (const node of body) {
29
+ if (node.type !== "ImportDeclaration") continue;
30
+ const source = node.source;
31
+ const specifiers = node.specifiers ?? [];
32
+ const specs = specifiers.map((s) => {
33
+ const local = name_of(s.local);
34
+ if (s.type === "ImportDefaultSpecifier") return {
35
+ kind: "default",
36
+ imported: "default",
37
+ local,
38
+ type_only: false
39
+ };
40
+ if (s.type === "ImportNamespaceSpecifier") return {
41
+ kind: "namespace",
42
+ imported: "*",
43
+ local,
44
+ type_only: false
45
+ };
46
+ return {
47
+ kind: "named",
48
+ imported: name_of(s.imported),
49
+ local,
50
+ type_only: s.importKind === "type"
51
+ };
52
+ });
53
+ out.push({
54
+ start: node.start,
55
+ end: node.end,
56
+ source: source.value,
57
+ attributes: attributes_text(code, node),
58
+ attribute_keys: attribute_keys(node),
59
+ type_only: node.importKind === "type",
60
+ side_effect: specifiers.length === 0,
61
+ specs
62
+ });
63
+ }
64
+ return out;
65
+ }
66
+ /**
67
+ * Every top-level import of the module, with ranges the rewriter overwrites. Declarations that
68
+ * cannot be rewritten (bare side-effect imports, namespace imports) are returned too, flagged, so
69
+ * a caller sees the whole picture. Null on a syntax error.
70
+ */
71
+ function analyze_imports(code, id) {
72
+ const body = program_body(code, id);
73
+ return body ? imports_of(code, body) : null;
74
+ }
75
+ const TYPE_ONLY_DECLS = /* @__PURE__ */ new Set([
76
+ "TSTypeAliasDeclaration",
77
+ "TSInterfaceDeclaration",
78
+ "TSDeclareFunction",
79
+ "TSModuleDeclaration"
80
+ ]);
81
+ /**
82
+ * The export shape of a module. `pure` is the barrel test: the module contributes NO code of its
83
+ * own — every statement is an import, a re-export, an `export {}` of imported bindings, a type
84
+ * declaration, or an empty export. A module with any own declaration, expression statement, or
85
+ * `export default <expr>` is IMPURE (it runs something), and is only rewritten when forced.
86
+ * Null on a syntax error (or a file oxc cannot read as a module).
87
+ */
88
+ function analyze_exports(code, id) {
89
+ const body = program_body(code, id);
90
+ if (!body) return null;
91
+ const imports = imports_of(code, body);
92
+ const bound = /* @__PURE__ */ new Map();
93
+ for (const d of imports) for (const s of d.specs) bound.set(s.local, {
94
+ source: d.source,
95
+ imported: s.imported,
96
+ kind: s.kind
97
+ });
98
+ const exports = [];
99
+ const own = /* @__PURE__ */ new Set();
100
+ const exported_namespaces = /* @__PURE__ */ new Set();
101
+ let pure = true;
102
+ for (const node of body) switch (node.type) {
103
+ case "ImportDeclaration": continue;
104
+ case "ExportAllDeclaration": {
105
+ const source = node.source.value;
106
+ const exported = node.exported;
107
+ if (exported) exports.push({
108
+ kind: "star_ns",
109
+ exported: name_of(exported),
110
+ source
111
+ });
112
+ else exports.push({
113
+ kind: "star",
114
+ source,
115
+ type_only: node.exportKind === "type"
116
+ });
117
+ continue;
118
+ }
119
+ case "ExportNamedDeclaration": {
120
+ const decl = node.declaration;
121
+ if (decl) {
122
+ if (TYPE_ONLY_DECLS.has(decl.type)) {
123
+ for (const n of declared_names(decl)) exports.push({
124
+ kind: "own",
125
+ exported: n
126
+ });
127
+ continue;
128
+ }
129
+ pure = false;
130
+ for (const n of declared_names(decl)) {
131
+ own.add(n);
132
+ exports.push({
133
+ kind: "own",
134
+ exported: n
135
+ });
136
+ }
137
+ continue;
138
+ }
139
+ const source = node.source ? node.source.value : null;
140
+ const specifiers = node.specifiers ?? [];
141
+ const type_decl = node.exportKind === "type";
142
+ for (const s of specifiers) {
143
+ const local = name_of(s.local);
144
+ const exported = name_of(s.exported);
145
+ const type_only = type_decl || s.exportKind === "type";
146
+ if (source) {
147
+ exports.push({
148
+ kind: "reexport",
149
+ exported,
150
+ imported: local,
151
+ source,
152
+ type_only
153
+ });
154
+ continue;
155
+ }
156
+ const b = bound.get(local);
157
+ if (b) {
158
+ if (b.kind === "namespace") {
159
+ exported_namespaces.add(local);
160
+ exports.push({
161
+ kind: "star_ns",
162
+ exported,
163
+ source: b.source
164
+ });
165
+ } else exports.push({
166
+ kind: "reexport",
167
+ exported,
168
+ imported: b.imported,
169
+ source: b.source,
170
+ type_only
171
+ });
172
+ } else {
173
+ own.add(exported);
174
+ exports.push({
175
+ kind: "own",
176
+ exported
177
+ });
178
+ if (!type_only) pure = false;
179
+ }
180
+ }
181
+ continue;
182
+ }
183
+ case "ExportDefaultDeclaration": {
184
+ const decl = node.declaration;
185
+ if (decl.type === "Identifier") {
186
+ const b = bound.get(name_of(decl));
187
+ if (b && b.kind !== "namespace") {
188
+ exports.push({
189
+ kind: "reexport",
190
+ exported: "default",
191
+ imported: b.imported,
192
+ source: b.source,
193
+ type_only: false
194
+ });
195
+ continue;
196
+ }
197
+ }
198
+ pure = false;
199
+ own.add("default");
200
+ exports.push({
201
+ kind: "own",
202
+ exported: "default"
203
+ });
204
+ continue;
205
+ }
206
+ default:
207
+ if (TYPE_ONLY_DECLS.has(node.type)) continue;
208
+ if (node.type === "EmptyStatement") continue;
209
+ pure = false;
210
+ }
211
+ for (const d of imports) {
212
+ if (d.type_only) continue;
213
+ if (d.side_effect) pure = false;
214
+ for (const s of d.specs) if (s.kind === "namespace" && !exported_namespaces.has(s.local)) pure = false;
215
+ }
216
+ return {
217
+ imports,
218
+ exports,
219
+ pure,
220
+ own
221
+ };
222
+ }
223
+ function declared_names(decl) {
224
+ const out = [];
225
+ const id = decl.id;
226
+ if (id && id.type === "Identifier") out.push(name_of(id));
227
+ const declarations = decl.declarations;
228
+ if (declarations) for (const d of declarations) collect_pattern(d.id, out);
229
+ return out;
230
+ }
231
+ function collect_pattern(p, out) {
232
+ if (!p) return;
233
+ switch (p.type) {
234
+ case "Identifier":
235
+ out.push(name_of(p));
236
+ return;
237
+ case "ObjectPattern":
238
+ for (const prop of p.properties) collect_pattern(prop.type === "RestElement" ? prop.argument : prop.value, out);
239
+ return;
240
+ case "ArrayPattern":
241
+ for (const el of p.elements) if (el) collect_pattern(el, out);
242
+ return;
243
+ case "AssignmentPattern":
244
+ collect_pattern(p.left, out);
245
+ return;
246
+ case "RestElement":
247
+ collect_pattern(p.argument, out);
248
+ return;
249
+ }
250
+ }
251
+ export { analyze_exports, analyze_imports };
@@ -0,0 +1,112 @@
1
+ import { ExportIndex } from "./exports/index.js";
2
+ import { AppAlias } from "./app-spec.js";
3
+ import { CompileOptions } from "svelte/compiler";
4
+ export declare const FOUC_CSS_PREFIX: string;
5
+ export declare const FOUC_SCOPED_PREFIX: string;
6
+ /** @param relPosix */
7
+ export declare function foucCssVirtualId(relPosix: string): string;
8
+ /** @param relPosix */
9
+ export declare function foucScopedVirtualId(relPosix: string): string;
10
+ /** @param id */
11
+ export declare function isFoucCssId(id: string): boolean;
12
+ /** @param id */
13
+ export declare function isFoucScopedId(id: string): boolean;
14
+ /** @param id */
15
+ export declare function foucRelFromId(id: string): string | null;
16
+ /**
17
+ * Collect side-effect import specs that pull island CSS into the client graph without JS.
18
+ * @param entryAbs absolute path to the island entry `.svelte`
19
+ * @param opts
20
+ */
21
+ export declare function buildFoucCssModuleSource(entryAbs: string, opts: CssReachOptions): Promise<string>;
22
+ /**
23
+ * The transitive CSS-reachability walk under `buildFoucCssModuleSource`, exported on its own for the
24
+ * server-router CSS registry (link/router-css.ts): from a component entry, in DISCOVERY ORDER (the
25
+ * cascade order the aggregator has always imported in), every `.svelte` with a `<style>` block
26
+ * (`kind: 'scoped'`) and every plain style-file import (`kind: 'css'`) reachable through the
27
+ * component tree. Abs paths. Same resolution rules as the aggregator, so both stay in lockstep.
28
+ */
29
+ export interface CssReachOptions {
30
+ root: string;
31
+ libDir: string;
32
+ /** The app's files (the compiler's: `CompileCtx.read_file`). */
33
+ readFile: (p: string) => string | null;
34
+ /** app aliases to follow (`$lib_x/…`, `@scope/pkg/…` → source dirs) — the fallback resolver's */
35
+ alias?: readonly AppAlias[];
36
+ /**
37
+ * The bundler's own resolver (Vite's `this.resolve`): a package specifier through its `exports`
38
+ * (a TypeScript entry included), a workspace link, an alias — whatever the build resolves. Without
39
+ * it (a unit test, a host with no bundler) `$lib`, relative paths and `alias` only.
40
+ */
41
+ resolve?: (spec: string, importer: string) => Promise<string | null>;
42
+ /**
43
+ * The export index of `resolve` (one per bundler resolver, for the app's life), so every walk of a
44
+ * build goes through one parse and one resolution of each barrel. Without it, a fresh one.
45
+ */
46
+ exports?: ExportIndex<WalkResolve>;
47
+ }
48
+ /** The CSS walk's resolver: the caller its export index resolves with. */
49
+ export type WalkResolve = (spec: string, importer: string) => Promise<string | null>;
50
+ /** An export index's resolve for the CSS walk: the walk hands its resolver in as the caller. */
51
+ export declare const through_caller: (spec: string, importer: string, walk_resolve: WalkResolve) => Promise<string | null>;
52
+ /**
53
+ * THE CSS A COMPONENT TREE REACHES — every `.svelte` with a `<style>` block (`kind: 'scoped'`) and
54
+ * every plain style-file import (`kind: 'css'`), in DISCOVERY ORDER (the cascade order the aggregator
55
+ * has always imported in). Abs paths.
56
+ *
57
+ * A subtree no client chunk carries (a server-only hole, a router page, a lake) gets its CSS from
58
+ * here, so this walk must reach what the bundler reaches — a component imported through a workspace
59
+ * package's TypeScript barrel came back unstyled: its specifier was not resolved, and a `.ts` module
60
+ * was a dead end. So:
61
+ * - specifiers resolve through the bundler's resolver (`opts.resolve`) when the build has one;
62
+ * - a `.svelte` file is a component: all of it renders, so every import of it is followed;
63
+ * - a script module is followed by the NAMES taken from it: through a barrel (the export index:
64
+ * nested barrels, `export *`), each name to its leaf, so a barrel of twenty components brings the
65
+ * CSS of the two imported; a module with code of its own, every import it makes (its code may
66
+ * render them). A dependency's own JavaScript (`node_modules`, not a barrel) is not walked: a
67
+ * package ships compiled code, its components as `.svelte` files a barrel names.
68
+ */
69
+ export declare function collectFoucCssReachable(entryAbs: string, opts: CssReachOptions): Promise<Array<{
70
+ kind: "scoped" | "css";
71
+ abs: string;
72
+ }>>;
73
+ /** How the app compiles a component, as its CSS needs it. */
74
+ export interface ComponentCss {
75
+ /** `<style lang="scss|sass">` to CSS, TypeScript stripped from its script
76
+ * (vite/style-preprocess.ts). */
77
+ preprocess(source: string, abs: string): Promise<string>;
78
+ /** The Svelte options the component's own compile uses (vite/svelte-options.ts), so the scope
79
+ * class matches its markup (test/region-css-svelte-options.test.ts). */
80
+ options(abs: string, source: string): Promise<CompileOptions>;
81
+ }
82
+ /**
83
+ * A component's scoped CSS, one rule for every leg (dev router CSS, the build's tree CSS, the fouc
84
+ * module): preprocessed, then compiled with its script and the app's Svelte options
85
+ * (test/router-css-dev-preprocess.test.ts). With no `css` (a host with no bundler), the source as
86
+ * it is.
87
+ */
88
+ export declare function scoped_component_css(abs: string, source: string, css: ComponentCss | undefined): Promise<string>;
89
+ /**
90
+ * Compile scoped CSS for a `.svelte` file (filename must match SSR for hash stability).
91
+ * @param abs
92
+ * @param source
93
+ */
94
+ export declare function compileFoucScopedCss(abs: string, source: string, opts?: {
95
+ /** Keep the `<script>` (already free of TS/dialects): a template reading `$store` from an
96
+ * imported store, or any script-declared name, only compiles WITH its script. Stripping it
97
+ * throws on such a template and falls back to UNSCOPED style bodies — which match nothing
98
+ * the SSR'd markup carries. Without it (a source that may still carry TypeScript), the
99
+ * source is tried whole first (Svelte reads `lang="ts"` itself), then script-stripped. */
100
+ keepScript?: boolean;
101
+ /** The app's Svelte options (`ComponentCss.options`); this compile sets only what makes it
102
+ * a CSS compile. */
103
+ options?: CompileOptions;
104
+ }): string;
105
+ /** @param source */
106
+ export declare function svelteHasStyle(source: string): boolean;
107
+ /** A component's static imports: each specifier with the names it takes (`*` for a namespace;
108
+ * none for a bare `import 'x'`). Type-only imports are left out: they bring nothing at runtime. */
109
+ export declare function listStaticImports(source: string, filename: string): Array<{
110
+ source: string;
111
+ names: Set<string>;
112
+ }>;
@@ -0,0 +1,314 @@
1
+ import { blank_styles } from "./blank-styles.js";
2
+ import { component_blocks } from "./parse/scan.js";
3
+ import { EVERY_BARREL, ExportIndex, Shapes } from "./exports/index.js";
4
+ import { warn } from "./messages.js";
5
+ import { region_family } from "./ids.js";
6
+ import { resolve_app_spec } from "./app-spec.js";
7
+ import path from "node:path";
8
+ import { unscoped_marker } from "@ogygia/core/contract";
9
+ import { compile, parse } from "svelte/compiler";
10
+ import { walk } from "estree-walker";
11
+ // src/fouc-css.ts
12
+ const FOUC_CSS_PREFIX = region_family("fouc_css");
13
+ const FOUC_SCOPED_PREFIX = region_family("fouc_scoped");
14
+ const PATH_SEP = /[/\\]/;
15
+ const STYLE_OPEN = /<style\b/i;
16
+ const STYLE_EXT = /\.(css|scss|sass|less|styl|stylus|pcss)(?:\?|$)/i;
17
+ const SVELTE_EXT = /\.svelte(?:\?|$)/i;
18
+ const IMPORT_SPEC = /import\s+(?:[\s\S]*?\s+from\s+)?["']([^"']+\.(?:svelte|css|scss|sass|less|styl|pcss)(?:\?[^"']*)?)["']/g;
19
+ const WIN_DRIVE_RE = /^[a-zA-Z]:/;
20
+ const PARENT_TRAVERSAL_RE = /(^|[\\/])\.\.([\\/]|$)/;
21
+ /** @param relPosix */
22
+ function foucCssVirtualId(relPosix) {
23
+ return `${FOUC_CSS_PREFIX + encodeURIComponent(relPosix.split(PATH_SEP).join("/"))}.js`;
24
+ }
25
+ /** @param relPosix */
26
+ function foucScopedVirtualId(relPosix) {
27
+ return `${FOUC_SCOPED_PREFIX + encodeURIComponent(relPosix.split(PATH_SEP).join("/"))}.css`;
28
+ }
29
+ /** @param id */
30
+ function isFoucCssId(id) {
31
+ const bare = id.startsWith("\0") ? id.slice(1) : id;
32
+ return bare.startsWith(FOUC_CSS_PREFIX) && bare.endsWith(".js");
33
+ }
34
+ /** @param id */
35
+ function isFoucScopedId(id) {
36
+ const bare = id.startsWith("\0") ? id.slice(1) : id;
37
+ return bare.startsWith(FOUC_SCOPED_PREFIX) && bare.endsWith(".css");
38
+ }
39
+ /** @param id */
40
+ function foucRelFromId(id) {
41
+ const bare = id.startsWith("\0") ? id.slice(1) : id;
42
+ let encoded = null;
43
+ if (bare.startsWith(FOUC_CSS_PREFIX) && bare.endsWith(".js")) encoded = bare.slice(FOUC_CSS_PREFIX.length, -3);
44
+ else if (bare.startsWith(FOUC_SCOPED_PREFIX) && bare.endsWith(".css")) encoded = bare.slice(FOUC_SCOPED_PREFIX.length, -4);
45
+ if (encoded == null) return null;
46
+ let rel;
47
+ try {
48
+ rel = decodeURIComponent(encoded);
49
+ } catch {
50
+ rel = encoded;
51
+ }
52
+ if (rel.startsWith("/") || rel.startsWith("\\") || WIN_DRIVE_RE.test(rel) || PARENT_TRAVERSAL_RE.test(rel)) return null;
53
+ return rel;
54
+ }
55
+ /**
56
+ * Collect side-effect import specs that pull island CSS into the client graph without JS.
57
+ * @param entryAbs absolute path to the island entry `.svelte`
58
+ * @param opts
59
+ */
60
+ async function buildFoucCssModuleSource(entryAbs, opts) {
61
+ const entries = await collectFoucCssReachable(entryAbs, opts);
62
+ const posix_rel = (abs) => path.relative(opts.root, abs).split(PATH_SEP).join("/");
63
+ const imports = [];
64
+ for (const e of entries) if (e.kind !== "scoped") imports.push(e.abs);
65
+ else {
66
+ const rel = posix_rel(e.abs);
67
+ if (!rel.startsWith("../") && !path.isAbsolute(rel)) imports.push(foucScopedVirtualId(rel));
68
+ }
69
+ if (imports.length === 0) return "export {}";
70
+ return `${imports.map((s) => `import ${JSON.stringify(s)};`).join("\n")}\n`;
71
+ }
72
+ /** An export index's resolve for the CSS walk: the walk hands its resolver in as the caller. */
73
+ const through_caller = (spec, importer, walk_resolve) => walk_resolve(spec, importer);
74
+ const SCRIPT_MODULE_EXT = /\.(?:[cm]?[jt]sx?|svelte\.[jt]s)$/;
75
+ const RESOLVE_SUFFIXES = [
76
+ "",
77
+ ".ts",
78
+ ".js",
79
+ "/index.ts",
80
+ "/index.js"
81
+ ];
82
+ const NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
83
+ const ALL = "*";
84
+ /**
85
+ * THE CSS A COMPONENT TREE REACHES — every `.svelte` with a `<style>` block (`kind: 'scoped'`) and
86
+ * every plain style-file import (`kind: 'css'`), in DISCOVERY ORDER (the cascade order the aggregator
87
+ * has always imported in). Abs paths.
88
+ *
89
+ * A subtree no client chunk carries (a server-only hole, a router page, a lake) gets its CSS from
90
+ * here, so this walk must reach what the bundler reaches — a component imported through a workspace
91
+ * package's TypeScript barrel came back unstyled: its specifier was not resolved, and a `.ts` module
92
+ * was a dead end. So:
93
+ * - specifiers resolve through the bundler's resolver (`opts.resolve`) when the build has one;
94
+ * - a `.svelte` file is a component: all of it renders, so every import of it is followed;
95
+ * - a script module is followed by the NAMES taken from it: through a barrel (the export index:
96
+ * nested barrels, `export *`), each name to its leaf, so a barrel of twenty components brings the
97
+ * CSS of the two imported; a module with code of its own, every import it makes (its code may
98
+ * render them). A dependency's own JavaScript (`node_modules`, not a barrel) is not walked: a
99
+ * package ships compiled code, its components as `.svelte` files a barrel names.
100
+ */
101
+ async function collectFoucCssReachable(entryAbs, opts) {
102
+ const read = opts.readFile;
103
+ const resolve = async (spec, importer) => {
104
+ if (opts.resolve) {
105
+ const id = await opts.resolve(spec, importer);
106
+ return id ? path.normalize(id.split("?")[0]) : null;
107
+ }
108
+ const base = resolve_app_spec(spec, importer, opts);
109
+ if (!base) return null;
110
+ const clean = base.split("?")[0];
111
+ if (STYLE_EXT.test(clean) || SVELTE_EXT.test(clean)) return path.normalize(clean);
112
+ for (const suffix of RESOLVE_SUFFIXES) {
113
+ const candidate = path.normalize(clean + suffix);
114
+ if (read(candidate) != null) return candidate;
115
+ }
116
+ return null;
117
+ };
118
+ const barrels = opts.exports ?? new ExportIndex(through_caller, new Shapes((id) => read(id)));
119
+ const entries = [];
120
+ const seen_css = /* @__PURE__ */ new Set();
121
+ const seen_svelte = /* @__PURE__ */ new Set();
122
+ const seen_names = /* @__PURE__ */ new Map();
123
+ const visit = async (abs, names, spec) => {
124
+ if (STYLE_EXT.test(abs)) {
125
+ if (!seen_css.has(abs)) {
126
+ seen_css.add(abs);
127
+ entries.push({
128
+ kind: "css",
129
+ abs
130
+ });
131
+ }
132
+ } else if (SVELTE_EXT.test(abs)) await visit_svelte(abs);
133
+ else if (SCRIPT_MODULE_EXT.test(abs)) await visit_script(abs, names, spec);
134
+ };
135
+ const follow = async (decls, importer) => {
136
+ for (const d of decls) {
137
+ const resolved = await resolve(d.source, importer);
138
+ if (resolved) await visit(resolved, d.names, d.source);
139
+ }
140
+ };
141
+ const visit_svelte = async (abs) => {
142
+ if (seen_svelte.has(abs)) return;
143
+ seen_svelte.add(abs);
144
+ const source = read(abs);
145
+ if (source == null) return;
146
+ if (svelteHasStyle(source)) entries.push({
147
+ kind: "scoped",
148
+ abs
149
+ });
150
+ await follow(listStaticImports(source, abs), abs);
151
+ };
152
+ const visit_script = async (abs, names, spec) => {
153
+ let done = seen_names.get(abs);
154
+ if (!done) seen_names.set(abs, done = /* @__PURE__ */ new Set());
155
+ if (done.has(ALL)) return;
156
+ const wanted = names.has(ALL) ? [ALL] : [...names].filter((n) => !done.has(n));
157
+ if (!wanted.length) return;
158
+ for (const n of wanted) done.add(n);
159
+ const map = await barrels.map(abs, spec, EVERY_BARREL, resolve);
160
+ if (map) {
161
+ const own = [];
162
+ for (const n of wanted) {
163
+ const entry = map.entries.get(n);
164
+ if (entry && typeof entry === "object") await visit(entry.id, /* @__PURE__ */ new Set(["namespace" in entry ? ALL : entry.name]), entry.id);
165
+ else own.push(n);
166
+ }
167
+ if (!own.length && !map.opaque) return;
168
+ }
169
+ if (NODE_MODULES_RE.test(abs)) return;
170
+ const shape = barrels.shapes.get(abs);
171
+ if (!shape) return;
172
+ await follow(shape.imports.filter((d) => !d.type_only).map((d) => ({
173
+ source: d.source,
174
+ names: new Set(d.side_effect ? [] : d.specs.filter((s) => !s.type_only).map((s) => s.kind === "namespace" ? ALL : s.imported))
175
+ })), abs);
176
+ await follow(shape.exports.flatMap((e) => {
177
+ if (e.kind === "reexport" && !e.type_only) return [{
178
+ source: e.source,
179
+ names: /* @__PURE__ */ new Set([e.imported])
180
+ }];
181
+ if (e.kind === "star" && !e.type_only || e.kind === "star_ns") return [{
182
+ source: e.source,
183
+ names: /* @__PURE__ */ new Set([ALL])
184
+ }];
185
+ return [];
186
+ }), abs);
187
+ };
188
+ await visit_svelte(path.normalize(entryAbs));
189
+ return entries;
190
+ }
191
+ /**
192
+ * A component's scoped CSS, one rule for every leg (dev router CSS, the build's tree CSS, the fouc
193
+ * module): preprocessed, then compiled with its script and the app's Svelte options
194
+ * (test/router-css-dev-preprocess.test.ts). With no `css` (a host with no bundler), the source as
195
+ * it is.
196
+ */
197
+ async function scoped_component_css(abs, source, css) {
198
+ if (!css) return compileFoucScopedCss(abs, source);
199
+ const preprocessed = await css.preprocess(source, abs);
200
+ return compileFoucScopedCss(abs, preprocessed, {
201
+ keepScript: true,
202
+ options: await css.options(abs, preprocessed)
203
+ });
204
+ }
205
+ /**
206
+ * Compile scoped CSS for a `.svelte` file (filename must match SSR for hash stability).
207
+ * @param abs
208
+ * @param source
209
+ */
210
+ function compileFoucScopedCss(abs, source, opts = {}) {
211
+ const inputs = opts.keepScript ? [source] : [source, without_scripts(source)];
212
+ let err;
213
+ for (const input of inputs) try {
214
+ return compile(input, {
215
+ ...opts.options,
216
+ filename: abs,
217
+ generate: "client",
218
+ css: "external",
219
+ hmr: false,
220
+ discloseVersion: false,
221
+ experimental: {
222
+ ...opts.options?.experimental,
223
+ async: true
224
+ }
225
+ }).css?.code ?? "";
226
+ } catch (e) {
227
+ err ??= e;
228
+ }
229
+ const why = err.message.split("\n")[0];
230
+ if (opts.keepScript) warn("scoped_css_failed", {
231
+ file: abs,
232
+ reason: why
233
+ });
234
+ const raw = extractRawStyleBodies(source);
235
+ return raw ? unscoped_marker(abs, why) + raw : raw;
236
+ }
237
+ /** @param source */
238
+ function svelteHasStyle(source) {
239
+ return STYLE_OPEN.test(source);
240
+ }
241
+ const GLOBAL_OPEN = ":global(";
242
+ function unwrap_global(css) {
243
+ let out = "";
244
+ let i = 0;
245
+ while (i < css.length) {
246
+ const at = css.indexOf(GLOBAL_OPEN, i);
247
+ if (at === -1) {
248
+ out += css.slice(i);
249
+ break;
250
+ }
251
+ out += css.slice(i, at);
252
+ const inner = at + 8;
253
+ let depth = 1;
254
+ let j = inner;
255
+ for (; j < css.length && depth > 0; j++) if (css[j] === "(") depth++;
256
+ else if (css[j] === ")") depth--;
257
+ out += css.slice(inner, j - 1);
258
+ i = j;
259
+ }
260
+ return out;
261
+ }
262
+ function extractRawStyleBodies(source) {
263
+ return unwrap_global(component_blocks(source).filter((b) => b.kind === "style").map((b) => source.slice(b.start, b.end)).join("\n"));
264
+ }
265
+ function without_scripts(source) {
266
+ let out = "";
267
+ let at = 0;
268
+ for (const b of component_blocks(source)) {
269
+ if (b.kind !== "script") continue;
270
+ out += source.slice(at, b.open);
271
+ at = b.close;
272
+ }
273
+ return out + source.slice(at);
274
+ }
275
+ /** A component's static imports: each specifier with the names it takes (`*` for a namespace;
276
+ * none for a bare `import 'x'`). Type-only imports are left out: they bring nothing at runtime. */
277
+ function listStaticImports(source, filename) {
278
+ const out = [];
279
+ try {
280
+ const ast = parse(blank_styles(source), {
281
+ filename,
282
+ modern: true
283
+ });
284
+ const scripts = [ast.instance, ast.module].filter(Boolean);
285
+ for (const block of scripts) {
286
+ const content = block?.content;
287
+ if (!content || content.type !== "Program") continue;
288
+ walk(content, { enter(node) {
289
+ if (node.type !== "ImportDeclaration") return;
290
+ const decl = node;
291
+ const src = decl.source?.value;
292
+ if (typeof src !== "string" || decl.importKind === "type") return;
293
+ const names = /* @__PURE__ */ new Set();
294
+ for (const s of decl.specifiers ?? []) {
295
+ if (s.importKind === "type") continue;
296
+ if (s.type === "ImportDefaultSpecifier") names.add("default");
297
+ else if (s.type === "ImportNamespaceSpecifier") names.add(ALL);
298
+ else names.add(s.imported?.name ?? s.imported?.value ?? ALL);
299
+ }
300
+ out.push({
301
+ source: src,
302
+ names
303
+ });
304
+ } });
305
+ }
306
+ } catch {
307
+ for (const m of source.matchAll(IMPORT_SPEC)) out.push({
308
+ source: m[1],
309
+ names: /* @__PURE__ */ new Set([ALL])
310
+ });
311
+ }
312
+ return out;
313
+ }
314
+ export { FOUC_CSS_PREFIX, FOUC_SCOPED_PREFIX, buildFoucCssModuleSource, collectFoucCssReachable, compileFoucScopedCss, foucCssVirtualId, foucRelFromId, foucScopedVirtualId, isFoucCssId, isFoucScopedId, listStaticImports, scoped_component_css, svelteHasStyle, through_caller };