@ogygia/compiler 0.0.0-stage → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -2
  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 +349 -0
  21. package/dist/driver.js +1401 -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 +102 -0
  27. package/dist/fouc-css.js +304 -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 +198 -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 +672 -0
  83. package/dist/messages.js +938 -0
  84. package/dist/ownership-stamps.d.ts +9 -0
  85. package/dist/ownership-stamps.js +101 -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 +56 -0
  119. package/dist/virtual/resolver.js +249 -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 +118 -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 +874 -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 +11 -0
  137. package/dist/vite/late-island.js +19 -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 +14 -0
  145. package/dist/vite/paths.js +37 -0
  146. package/dist/vite/plugin-api.d.ts +316 -0
  147. package/dist/vite/plugin-api.js +328 -0
  148. package/dist/vite/session.d.ts +28 -0
  149. package/dist/vite/session.js +43 -0
  150. package/dist/vite/sourcemaps.d.ts +19 -0
  151. package/dist/vite/sourcemaps.js +75 -0
  152. package/dist/vite/style-preprocess.d.ts +2 -0
  153. package/dist/vite/style-preprocess.js +84 -0
  154. package/dist/vite/svelte-entries.d.ts +4 -0
  155. package/dist/vite/svelte-entries.js +10 -0
  156. package/package.json +85 -3
@@ -0,0 +1,1565 @@
1
+ import { foucCssVirtualId } from "../fouc-css.js";
2
+ import { collectCaptureInfo, collect_pattern_names } from "../free-vars.js";
3
+ import { parse_module } from "../parse/oxc.js";
4
+ import { regionId, regionIdentity, strategyKey } from "./identity.js";
5
+ import { OGYGIA_SCHEME } from "../virtual/specifier.js";
6
+ import { resolve_app_spec } from "../app-spec.js";
7
+ import { regionBindingVirtualId, region_family, wrapperVirtualId } from "../ids.js";
8
+ import "../virtual/table.js";
9
+ import { island_entry_source, lake_wrapper_source, make_region_binding, make_wake_island, server_wrapper_source } from "./emit.js";
10
+ import { check_marked_uses, marked_import_bindings, refuse_as_region } from "./marked-imports.js";
11
+ import { blank_styles } from "../blank-styles.js";
12
+ import { OgygiaError, warn } from "../messages.js";
13
+ import _taggedTemplateLiteral from "../_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js";
14
+ import path from "node:path";
15
+ import { SCHEDULE, WAKE, dedent, parse_trigger } from "@ogygia/core/contract";
16
+ import { parse } from "svelte/compiler";
17
+ import MagicString from "magic-string";
18
+ import { createHash } from "node:crypto";
19
+ import { say } from "@ogygia/machine";
20
+ // src/region/transform.ts
21
+ var _templateObject;
22
+ const unparsed = say();
23
+ function warn_unparsed(id, err) {
24
+ unparsed.once(id, () => say_unparsed(id, err));
25
+ }
26
+ function say_unparsed(id, err) {
27
+ const e = err;
28
+ warn("region_host_skipped", {
29
+ file: id,
30
+ reason: e.code ?? (e.message ?? "parse error").split("\n")[0].slice(0, 80),
31
+ at: e.start?.line ? `${e.start.line}:${(e.start.column ?? 0) + 1}` : ""
32
+ });
33
+ }
34
+ const REGEXP_META = /[.*+?^${}()|[\]\\]/g;
35
+ const PATH_SEP = /[/\\]/;
36
+ const DURATION = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h)?$/i;
37
+ const MS_PER_UNIT = /* @__PURE__ */ new Map([
38
+ ["ms", 1],
39
+ ["s", 1e3],
40
+ ["m", 6e4],
41
+ ["h", 36e5]
42
+ ]);
43
+ const SECONDS_PER_UNIT = /* @__PURE__ */ new Map([
44
+ ["s", 1],
45
+ ["m", 60],
46
+ ["h", 3600]
47
+ ]);
48
+ const JS_EXT = /\.js$/;
49
+ const VIRTUAL_HOST_RE = /^\0?(?:virtual|ogygia):/;
50
+ const ISLAND_DIR = ".ogygia";
51
+ const ENTRY_PREFIX = region_family("entry");
52
+ const WRAPPER_PREFIX = region_family("wrapper");
53
+ const BINDING_PREFIX = region_family("binding");
54
+ const LAZY_PREFIX = region_family("lazy");
55
+ /** True for a GENERATED island glue id (virtual island entry / wrapper / region binding, or the legacy
56
+ * on-disk `.ogygia/` shape) — the ids that are ogygia's own emit, not authored app/component source. */
57
+ function is_island_path(id) {
58
+ const bare = id.split("?")[0];
59
+ return bare.startsWith(ENTRY_PREFIX) && (bare.endsWith(".js") || bare.endsWith(".svelte")) || bare.startsWith(WRAPPER_PREFIX) && bare.endsWith(".svelte") || bare.startsWith(BINDING_PREFIX) && bare.endsWith(".js") || bare.startsWith(LAZY_PREFIX) && bare.endsWith(".js") || bare.includes(`/.ogygia/`) && bare.endsWith(".svelte");
60
+ }
61
+ /**
62
+ * Default import-attribute keys — the two-dial grammar. Internal role names stay `hydrate`/`defer`
63
+ * (the wire format + runtime keep those anchors); the user-facing ATTRIBUTE names are the values.
64
+ * Override via `ogygia({ importKeys })`.
65
+ * - `render` attribute → the MODE: `static` (inline HTML) | `deferred` (a hole, fetched) | `live`
66
+ * (a hole that revalidates). Defaults to `static`.
67
+ * - `fetch` attribute → a `deferred` hole's TIMING, when its HTML arrives (default `load`):
68
+ * `with { render: 'deferred', fetch: 'visible' }`.
69
+ * - `wake` attribute → when an island's JS runs (`none`: a lake). Never a hole's timing.
70
+ */
71
+ const DEFAULT_IMPORT_KEYS = {
72
+ wake: "wake",
73
+ fetch: "fetch",
74
+ render: "render",
75
+ preset: "preset",
76
+ region: "region"
77
+ };
78
+ /** The keys a region preset takes, by their standard names: a preset is config, so `importKeys`
79
+ * never renames them. */
80
+ const PRESET_KEYS = /* @__PURE__ */ new Set([
81
+ "render",
82
+ "wake",
83
+ "fetch",
84
+ "margin",
85
+ "maxAge",
86
+ "onExpire",
87
+ "revalidate",
88
+ "keep",
89
+ "stitch",
90
+ "prefetch"
91
+ ]);
92
+ const RENDER_MODES = /* @__PURE__ */ new Set([
93
+ "static",
94
+ "deferred",
95
+ "live"
96
+ ]);
97
+ const JS_IDENT = /^[A-Za-z_$][\w$]*$/;
98
+ const STORE_CTORS = /* @__PURE__ */ new Set([
99
+ "writable",
100
+ "readable",
101
+ "derived",
102
+ "toStore",
103
+ "fromStore"
104
+ ]);
105
+ const STORE_SUB_RE = /\$([A-Za-z_][\w$]*)/g;
106
+ const RUNE_NAMES = /* @__PURE__ */ new Set([
107
+ "state",
108
+ "derived",
109
+ "effect",
110
+ "props",
111
+ "bindable",
112
+ "inspect",
113
+ "host"
114
+ ]);
115
+ function line_col(src, offset) {
116
+ let line = 1;
117
+ let last = -1;
118
+ for (let i = 0; i < offset; i++) if (src.charCodeAt(i) === 10) {
119
+ line++;
120
+ last = i;
121
+ }
122
+ return `${line}:${offset - last}`;
123
+ }
124
+ const store_warned = say();
125
+ function warn_once(key, speak) {
126
+ store_warned.once(key, speak);
127
+ }
128
+ const CHILD_KEYS = [
129
+ "consequent",
130
+ "alternate",
131
+ "body",
132
+ "fallback",
133
+ "pending",
134
+ "then",
135
+ "catch",
136
+ "fragment"
137
+ ];
138
+ const NORMALIZED_CACHE = /* @__PURE__ */ new WeakMap();
139
+ let DEFAULT_NORMALIZED = null;
140
+ /**
141
+ * Merge partial `importKeys` with {@link DEFAULT_IMPORT_KEYS}.
142
+ * Rejects empty strings, non-identifiers, and colliding role names.
143
+ *
144
+ * @param overrides - Optional overrides for one or more roles.
145
+ * @returns Fully resolved key map used by the transform.
146
+ * @throws If a value is not a JS identifier or two roles share the same name.
147
+ */
148
+ function normalize_import_keys(overrides) {
149
+ if (overrides == null) return DEFAULT_NORMALIZED ??= normalize_import_keys_uncached(null);
150
+ const hit = NORMALIZED_CACHE.get(overrides);
151
+ if (hit) return hit;
152
+ const result = normalize_import_keys_uncached(overrides);
153
+ NORMALIZED_CACHE.set(overrides, result);
154
+ return result;
155
+ }
156
+ function normalize_import_keys_uncached(overrides) {
157
+ const wake = (overrides?.wake ?? DEFAULT_IMPORT_KEYS.wake).trim();
158
+ const fetch = (overrides?.fetch ?? DEFAULT_IMPORT_KEYS.fetch).trim();
159
+ const render = (overrides?.render ?? DEFAULT_IMPORT_KEYS.render).trim();
160
+ const preset = (overrides?.preset ?? DEFAULT_IMPORT_KEYS.preset).trim();
161
+ const region = (overrides?.region ?? DEFAULT_IMPORT_KEYS.region).trim();
162
+ for (const [role, name] of [
163
+ ["wake", wake],
164
+ ["fetch", fetch],
165
+ ["render", render],
166
+ ["preset", preset],
167
+ ["region", region]
168
+ ]) if (!name || !JS_IDENT.test(name)) throw new OgygiaError("import_key_invalid", {
169
+ role,
170
+ got: String(JSON.stringify(overrides?.[role]))
171
+ });
172
+ if ((/* @__PURE__ */ new Set([
173
+ wake,
174
+ fetch,
175
+ render,
176
+ preset,
177
+ region
178
+ ])).size !== 5) throw new OgygiaError("import_keys_not_distinct");
179
+ return {
180
+ wake,
181
+ fetch,
182
+ render,
183
+ preset,
184
+ region
185
+ };
186
+ }
187
+ const COMPONENT_ATTRS_RE = /\.svelte['"]\s*(?:with|assert)\s*\{([^}]*)\}/g;
188
+ const COMPONENT_SPEC_RE = /\.svelte$/;
189
+ const ATTR_KEY_RE = /(?:^|,)\s*(?:(['"])(.*?)\1|([\w$-]+))\s*:/g;
190
+ function foreign_attribute(key, import_keys) {
191
+ if (key === "type") return true;
192
+ return DEFAULT_IMPORT_KEYS[key] !== void 0 && import_keys[key] !== key;
193
+ }
194
+ function component_attribute_keys(import_keys) {
195
+ return [
196
+ import_keys.wake,
197
+ import_keys.fetch,
198
+ import_keys.render,
199
+ import_keys.preset,
200
+ import_keys.region,
201
+ "keep",
202
+ "stitch",
203
+ "prefetch"
204
+ ];
205
+ }
206
+ function has_unknown_component_attribute(source, import_keys) {
207
+ if (!source.includes(".svelte")) return false;
208
+ const known = component_attribute_keys(import_keys);
209
+ for (const m of source.matchAll(COMPONENT_ATTRS_RE)) for (const k of m[1].matchAll(ATTR_KEY_RE)) {
210
+ const key = k[2] ?? k[3];
211
+ if (!known.includes(key) && !foreign_attribute(key, import_keys)) return true;
212
+ }
213
+ return false;
214
+ }
215
+ function refuse_unknown_attributes(spec, keys, import_keys, host, names) {
216
+ if (!COMPONENT_SPEC_RE.test(spec)) return;
217
+ const known = component_attribute_keys(import_keys);
218
+ for (const key of keys) if (!known.includes(key) && !foreign_attribute(key, import_keys)) throw new OgygiaError("region_attribute_unknown", {
219
+ host,
220
+ names,
221
+ key,
222
+ known: known.map((k) => `\`${k}\``).join(", ")
223
+ });
224
+ }
225
+ const HINT_CACHE = /* @__PURE__ */ new WeakMap();
226
+ /**
227
+ * Cheap source-scan regex matching any of the configured import-attribute key names.
228
+ * Used to skip AST work on hosts that cannot contain region imports.
229
+ *
230
+ * @param import_keys - Resolved key map from {@link normalize_import_keys}.
231
+ */
232
+ function import_keys_hint(import_keys) {
233
+ let re = HINT_CACHE.get(import_keys);
234
+ if (re) return re;
235
+ const esc = (s) => s.replace(REGEXP_META, "\\$&");
236
+ re = new RegExp(`${esc(import_keys.wake)}|${esc(import_keys.fetch)}|${esc(import_keys.render)}|${esc(import_keys.preset)}|${esc(import_keys.region)}`);
237
+ HINT_CACHE.set(import_keys, re);
238
+ return re;
239
+ }
240
+ /** Deterministic short id for a region (stable across dev + build).
241
+ * When `salt` is set (production `OGYGIA_SECRET`), ids are not offline-computable (P1-ID).
242
+ * Paths are always posix so SSR/client builds agree across OS path separators. */
243
+ function islandId(relHostPath, index, salt = "") {
244
+ const rel = String(relHostPath).split(PATH_SEP).join("/");
245
+ const msg = salt ? `${salt}\0${rel}::${index}` : `${rel}::${index}`;
246
+ return createHash("md5").update(msg).digest("hex").slice(0, 12);
247
+ }
248
+ /**
249
+ * The directory, under the app dir, of the STABLE names (an island's identity, the runtime's): not
250
+ * `immutable/`. A host serves `immutable/` for a year by name (every adapter, every CDN rule written
251
+ * for it), and a stable name keeps its name while its content follows each build: a year-old copy
252
+ * would load another build's code. Here a host's ordinary rule revalidates them. The content-hashed
253
+ * files they point at stay in `immutable/`.
254
+ */
255
+ const STABLE_NAME_DIR = "ogygia";
256
+ /**
257
+ * Deterministic client path of a hydrate island's stable name (mirrors the runtime's). SSR bakes it
258
+ * into `<ogygia-region entry>` as the island's identity — a name, not a file: the content-hashed
259
+ * entry is found through the handoff (the server) and the location maps (the browser,
260
+ * link/location-map.ts), since Kit builds server before client.
261
+ */
262
+ function islandChunkFileName(iid, appDir = "_app") {
263
+ return `${appDir}/${STABLE_NAME_DIR}/og-region.${iid}.js`;
264
+ }
265
+ /** App-internal URL for {@link islandChunkFileName}: `/<appDir>/ogygia/…` (leading slash, appDir,
266
+ * NO base). It is what SSR bakes onto `<ogygia-region entry>`; `Region.svelte` runs it through Kit's
267
+ * `asset()` at render time, which is the sole authority on `base` / the assets CDN / relative paths —
268
+ * so a base is never baked here (that would double-apply it). NOT the on-disk output filename. */
269
+ function islandPublicUrl(iid, appDir = "_app") {
270
+ return `/${islandChunkFileName(iid, appDir)}`;
271
+ }
272
+ /**
273
+ * csr=false CLIENT host binding target. Kit still emits those page nodes; pointing marked
274
+ * imports here (instead of wrappers) keeps N island wrappers/entries out of the page graph so
275
+ * `emitFile` owns hydrate modules and Rolldown does not thin-facade them. Hydration uses
276
+ * `import(entry)` only — this stub is never loaded for island JS.
277
+ *
278
+ * Beside the stub the transform emits `import 'ogygia:region/fouc-css/<entry>'` so Kit still
279
+ * links stylesheets (FOUC) via CSS-only side effects. Importing the full `.svelte` JS module
280
+ * dual-owns it with the emitFile island entry and Rolldown thin-facades `og-region.*`.
281
+ * Omitting CSS entirely orphans rules (scoped class hashes, no stylesheet).
282
+ */
283
+ const CLIENT_BINDING_STUB = region_family("client_binding_stub");
284
+ /**
285
+ * The `with { region: … }` marker has ONE value — `'raw'` (an adjective: "a raw/held region"). It
286
+ * carries NO schedule: the wake timing is set at the `region()` call (`region(C, props, { wake })`)
287
+ * or, in a block tree, per node. This is the only surviving import-attribute marker for a component
288
+ * a registry hands to `region()` where the transform can't see the call site.
289
+ *
290
+ * @param raw the marker value
291
+ * @param where host label for error messages
292
+ * @param regionKey configured `region` attribute name (for the message)
293
+ */
294
+ function normalize_region_value(raw, where, regionKey = "region") {
295
+ if ((raw ?? "").trim() === "raw") return;
296
+ throw new OgygiaError("region_value_not_raw", {
297
+ host: where,
298
+ key: regionKey
299
+ });
300
+ }
301
+ /**
302
+ * Validate a `wake:` schedule value on a held import (a `.ts` registry / remote). Accepts the wake
303
+ * strategies (`load` / `idle` / `visible` / `interaction`) or a media query — the same vocabulary as
304
+ * a placed island's `wake:`. Returns the value unchanged (it becomes the baked `__hydrate`).
305
+ */
306
+ function normalize_hydrate_value(raw, where, wakeKey = "wake") {
307
+ const v = (raw ?? "").trim();
308
+ if (parse_trigger(v, WAKE)) return v;
309
+ throw new OgygiaError("wake_strategy_unknown", {
310
+ host: where,
311
+ key: wakeKey,
312
+ value: v
313
+ });
314
+ }
315
+ function clean_import_text(source, node) {
316
+ return `${source.slice(node.start, node.source.end)};`;
317
+ }
318
+ function region_keys_on_dynamic_import(node, import_keys) {
319
+ const opts = node.options;
320
+ if (!opts || opts.type !== "ObjectExpression") return [];
321
+ const claimed = /* @__PURE__ */ new Set([
322
+ import_keys.wake,
323
+ import_keys.fetch,
324
+ import_keys.render,
325
+ import_keys.preset,
326
+ import_keys.region
327
+ ]);
328
+ const found = [];
329
+ for (const prop of opts.properties) {
330
+ if (prop.type !== "Property" || prop.computed) continue;
331
+ let bag_key = null;
332
+ if (prop.key.type === "Identifier") bag_key = prop.key.name;
333
+ else if (prop.key.type === "Literal") bag_key = String(prop.key.value);
334
+ if (bag_key !== "with" && bag_key !== "assert") continue;
335
+ if (prop.value.type !== "ObjectExpression") continue;
336
+ for (const atr of prop.value.properties) {
337
+ if (atr.type !== "Property" || atr.computed) continue;
338
+ let ak = null;
339
+ if (atr.key.type === "Identifier") ak = atr.key.name;
340
+ else if (atr.key.type === "Literal") ak = String(atr.key.value);
341
+ if (ak && claimed.has(ak) && !found.includes(ak)) found.push(ak);
342
+ }
343
+ }
344
+ return found;
345
+ }
346
+ function reject_dynamic_region_imports(body, import_keys, host) {
347
+ const walk = (node) => {
348
+ if (!node || typeof node !== "object") return;
349
+ if (node.type === "ImportExpression") {
350
+ const keys = region_keys_on_dynamic_import(node, import_keys);
351
+ if (keys.length) throw new OgygiaError("dynamic_region_import", {
352
+ host,
353
+ keys: keys.join(", "),
354
+ wake_key: import_keys.wake,
355
+ render_key: import_keys.render,
356
+ preset_key: import_keys.preset
357
+ });
358
+ }
359
+ for (const k of Object.keys(node)) {
360
+ if (k === "start" || k === "end" || k === "loc") continue;
361
+ const v = node[k];
362
+ if (Array.isArray(v)) for (const c of v) walk(c);
363
+ else if (v && typeof v === "object" && typeof v.type === "string") walk(v);
364
+ }
365
+ };
366
+ for (const n of body ?? []) walk(n);
367
+ }
368
+ function script_lang_attr(scriptNode) {
369
+ if (!scriptNode) return "";
370
+ for (const attr of scriptNode.attributes ?? []) if (attr.name === "lang" && Array.isArray(attr.value) && attr.value[0]?.data) return ` lang="${attr.value[0].data}"`;
371
+ return "";
372
+ }
373
+ const REMOUNT_ON_EXPIRE = /* @__PURE__ */ new Set(["empty", "fetch"]);
374
+ function parse_max_age(raw, err, names) {
375
+ if (raw == null) return void 0;
376
+ if (typeof raw === "number") {
377
+ if (!Number.isFinite(raw) || raw < 0) throw err(names, `\`remount.maxAge\` must be a non-negative number (ms), got ${raw}.`);
378
+ return Math.floor(raw);
379
+ }
380
+ if (typeof raw === "string") {
381
+ const m = raw.trim().match(DURATION);
382
+ if (!m) throw err(names, `unknown remount.maxAge '${raw}'. Use a number (ms) or a duration like '30s' | '5m' | '1h'.`);
383
+ const n = Number(m[1]);
384
+ const unit = (m[2] || "ms").toLowerCase();
385
+ return Math.floor(n * MS_PER_UNIT.get(unit));
386
+ }
387
+ throw err(names, `\`remount.maxAge\` must be a number (ms) or duration string.`);
388
+ }
389
+ function parse_cache_ttl_sec(raw, err, names) {
390
+ if (raw == null) return void 0;
391
+ if (typeof raw === "number") {
392
+ if (!Number.isFinite(raw) || raw < 0) throw err(names, `\`maxAge\` must be a non-negative number of seconds, got ${raw}.`);
393
+ return Math.floor(raw);
394
+ }
395
+ if (typeof raw === "string") {
396
+ const m = raw.trim().match(DURATION);
397
+ if (!m) throw err(names, `unknown \`maxAge\` '${raw}'. Use seconds (a number) or a duration like '30s' | '5m' | '1h'.`);
398
+ const n = Number(m[1]);
399
+ const unit = (m[2] || "s").toLowerCase();
400
+ if (unit === "ms") return Math.floor(n / 1e3);
401
+ return Math.floor(n * SECONDS_PER_UNIT.get(unit));
402
+ }
403
+ throw err(names, `\`maxAge\` must be a number of seconds or a duration string.`);
404
+ }
405
+ function parse_remount(ro, err, names) {
406
+ const out = { policy: "cache" };
407
+ if (ro.revalidate === true) throw err(names, `\`remount.revalidate: true\` is invalid — use 'load' (or 'idle' | 'visible' | a media query).`);
408
+ if (ro.revalidate !== false && ro.revalidate != null) {
409
+ const rev = String(ro.revalidate);
410
+ if (!parse_trigger(rev, SCHEDULE)) throw err(names, `unknown remount.revalidate '${rev}'. Use false | 'load' | 'idle' | 'visible' | a media query.`);
411
+ out.policy = "swr";
412
+ out.when = rev;
413
+ }
414
+ if (ro.onExpire != null) {
415
+ const oe = String(ro.onExpire);
416
+ if (!REMOUNT_ON_EXPIRE.has(oe)) throw err(names, `unknown remount.onExpire '${oe}'. Use 'empty' | 'fetch'.`);
417
+ if (out.policy === "cache" && oe === "fetch") throw err(names, `\`onExpire: 'fetch'\` requires \`revalidate\` (a schedule). Pure cache expires to empty — use { revalidate: 'load', maxAge, onExpire: 'fetch' } for SWR past maxAge.`);
418
+ out.onExpire = oe;
419
+ }
420
+ if (ro.maxAge != null) out.maxAgeMs = parse_max_age(ro.maxAge, err, names);
421
+ return out;
422
+ }
423
+ const SWR_EVENT_ATTR = /* @__PURE__ */ new Set([
424
+ "onclick",
425
+ "ondblclick",
426
+ "oncontextmenu",
427
+ "onauxclick",
428
+ "onpointerdown",
429
+ "onpointerup",
430
+ "onpointermove",
431
+ "onpointerenter",
432
+ "onpointerleave",
433
+ "onpointercancel",
434
+ "onpointerover",
435
+ "onpointerout",
436
+ "onmousedown",
437
+ "onmouseup",
438
+ "onmousemove",
439
+ "onmouseenter",
440
+ "onmouseleave",
441
+ "onmouseover",
442
+ "onmouseout",
443
+ "onkeydown",
444
+ "onkeyup",
445
+ "onkeypress",
446
+ "onfocus",
447
+ "onblur",
448
+ "onfocusin",
449
+ "onfocusout",
450
+ "oninput",
451
+ "onbeforeinput",
452
+ "onchange",
453
+ "onsubmit",
454
+ "onreset",
455
+ "onscroll",
456
+ "onwheel",
457
+ "ontouchstart",
458
+ "ontouchend",
459
+ "ontouchmove",
460
+ "ontouchcancel",
461
+ "ondrag",
462
+ "ondragstart",
463
+ "ondragend",
464
+ "ondragenter",
465
+ "ondragleave",
466
+ "ondragover",
467
+ "ondrop",
468
+ "oncopy",
469
+ "oncut",
470
+ "onpaste",
471
+ "onanimationstart",
472
+ "onanimationend",
473
+ "onanimationiteration",
474
+ "ontransitionend",
475
+ "ontransitionrun",
476
+ "ontransitionstart",
477
+ "ontransitioncancel",
478
+ "onload",
479
+ "onerror",
480
+ "ontoggle",
481
+ "onselect",
482
+ "oninvalid",
483
+ "onformdata"
484
+ ]);
485
+ function is_component_node(n) {
486
+ return n.type === "Component";
487
+ }
488
+ function assert_swr_lake_crossable(node, err) {
489
+ if ((node.fragment?.nodes ?? []).filter((n) => !(n.type === "Text" && !String(n.data ?? "").trim())).length) throw err(node.name, `\`render: 'live'\` region <${node.name}> cannot have children — the revalidate endpoint re-renders it from serialized props only, so snippets cannot cross. Move the content inside the component, or make it a static lake with \`wake: 'none'\`.`);
490
+ for (const attr of node.attributes ?? []) {
491
+ if (attr.type === "SpreadAttribute") continue;
492
+ if (attr.type !== "Attribute") throw err(node.name, `\`render: 'live'\` region <${node.name}> cannot use \`${attr.type === "BindDirective" ? `bind:${attr.name}` : attr.name || attr.type}\` — only plain attributes and spreads can be serialized for the revalidate endpoint.`);
493
+ const name = attr.name;
494
+ if (typeof name === "string" && SWR_EVENT_ATTR.has(name)) throw err(node.name, `\`render: 'live'\` region <${node.name}> cannot use \`${name}\` — event/callback attributes cannot be serialized for the revalidate endpoint. Pass serializable data props instead.`);
495
+ const val = attr.value;
496
+ let chunk_list = val;
497
+ if (!Array.isArray(val)) chunk_list = val != null && val !== true ? [val] : [];
498
+ for (const chunk of chunk_list) {
499
+ const t = chunk?.expression?.type;
500
+ if (t === "ArrowFunctionExpression" || t === "FunctionExpression") throw err(node.name, `\`render: 'live'\` region <${node.name}> cannot use a function value for \`${name}\` — functions cannot be serialized for the revalidate endpoint.`);
501
+ }
502
+ }
503
+ }
504
+ function resolve_component_path(spec, host_id, ctx) {
505
+ if (typeof spec !== "string" || !spec.trim()) return null;
506
+ if (spec.startsWith(".") && VIRTUAL_HOST_RE.test(host_id)) throw new OgygiaError("generated_module_relative_import", {
507
+ host: host_id,
508
+ specifier: spec
509
+ });
510
+ return resolve_app_spec(spec, host_id, ctx) ?? spec;
511
+ }
512
+ function is_wake_island(mark) {
513
+ return mark.strategy !== "server" && mark.strategy !== "held" && mark.strategy !== "lake";
514
+ }
515
+ function transformHost(source, id, ctx) {
516
+ return new FileCompilation(source, id, ctx).run();
517
+ }
518
+ var FileCompilation = class {
519
+ #source;
520
+ #id;
521
+ #ctx;
522
+ #ast;
523
+ #instance_body;
524
+ #module_body;
525
+ #lang;
526
+ #rel_host;
527
+ #import_keys;
528
+ #imports;
529
+ #marked_components;
530
+ #imports_to_strip;
531
+ #export_names;
532
+ #has_island_children;
533
+ #static_placed;
534
+ #has_island_hint;
535
+ #to_kit = [];
536
+ #kit_owns(mark) {
537
+ return this.#ctx.routeCsr === true && is_wake_island(mark);
538
+ }
539
+ #kit_only() {
540
+ const s = new MagicString(this.#source);
541
+ for (const edit of this.#to_kit) s.overwrite(edit.start, edit.end, edit.text);
542
+ return {
543
+ code: s.toString(),
544
+ map: s.generateMap({
545
+ hires: true,
546
+ source: this.#id,
547
+ includeContent: true
548
+ }),
549
+ islands: []
550
+ };
551
+ }
552
+ constructor(source, id, ctx) {
553
+ this.#source = source;
554
+ this.#id = id;
555
+ this.#ctx = ctx;
556
+ this.#import_keys = normalize_import_keys(ctx.importKeys);
557
+ }
558
+ run() {
559
+ const early = this.#analyze();
560
+ if (early) return early.done;
561
+ return this.#lower();
562
+ }
563
+ #referenced_names(skip) {
564
+ const names = /* @__PURE__ */ new Set();
565
+ const walk = (node) => {
566
+ if (!node || typeof node !== "object") return;
567
+ if (node.type === "Identifier") names.add(node.name);
568
+ else if (node.type === "Component") {
569
+ const n = node.name || "";
570
+ names.add(n);
571
+ for (let i = n.indexOf("."); i !== -1; i = n.indexOf(".", i + 1)) names.add(n.slice(0, i));
572
+ }
573
+ for (const k of Object.keys(node)) {
574
+ if (k === "start" || k === "end" || k === "loc") continue;
575
+ const v = node[k];
576
+ if (Array.isArray(v)) for (const c of v) walk(c);
577
+ else if (v && typeof v === "object" && typeof v.type === "string") walk(v);
578
+ }
579
+ };
580
+ for (const n of this.#instance_body) if (n.type !== "ImportDeclaration" && !skip?.has(n)) walk(n);
581
+ for (const n of this.#module_body) if (n.type !== "ImportDeclaration") walk(n);
582
+ for (const n of this.#ast.fragment?.nodes ?? []) walk(n);
583
+ return names;
584
+ }
585
+ #used_names;
586
+ #marked_import_referenced(local) {
587
+ return (this.#used_names ??= this.#referenced_names()).has(local);
588
+ }
589
+ #resolve_region_mark(inline, fail) {
590
+ const import_keys = this.#import_keys;
591
+ const ctx = this.#ctx;
592
+ const rel_host = this.#rel_host;
593
+ const REGION_KEYS = [
594
+ import_keys.wake,
595
+ import_keys.fetch,
596
+ import_keys.render,
597
+ import_keys.preset,
598
+ import_keys.region
599
+ ];
600
+ const err_shim = (_names, msg) => fail(msg);
601
+ if (!REGION_KEYS.some((k) => inline.has(k))) return null;
602
+ if (inline.has(import_keys.region)) {
603
+ if (inline.size > 1) throw fail(`\`${import_keys.region}\` must be the only import attribute — it only marks a held region ('raw'); set the wake schedule at the \`region()\` call.`);
604
+ normalize_region_value(inline.get(import_keys.region), rel_host, import_keys.region);
605
+ return {
606
+ strategy: "held",
607
+ options: {}
608
+ };
609
+ }
610
+ const attrs = /* @__PURE__ */ new Map();
611
+ let remount_opt;
612
+ let from_preset = null;
613
+ let render_mode;
614
+ let wake_val;
615
+ let fetch_val;
616
+ const live_opts = {};
617
+ if (inline.has(import_keys.preset)) {
618
+ if (inline.size > 1) throw fail(`\`${import_keys.preset}\` must be the only import attribute — put its options (margin, maxAge, …) in the preset definition (ogygia({ presets })).`);
619
+ from_preset = inline.get(import_keys.preset);
620
+ const preset = ctx.presets && ctx.presets[from_preset];
621
+ if (!preset) {
622
+ const avail = Object.keys(ctx.presets || {});
623
+ throw fail(`unknown ${import_keys.preset} '${from_preset}'. Available: ${avail.length ? avail.join(", ") : "(none)"}.`);
624
+ }
625
+ for (const [k, v] of Object.entries(preset)) {
626
+ if (v == null) continue;
627
+ if (k === "render") render_mode = String(v);
628
+ else if (k === "wake") wake_val = String(v);
629
+ else if (k === "fetch") fetch_val = String(v);
630
+ else if (k === "maxAge" || k === "onExpire" || k === "revalidate") live_opts[k] = v;
631
+ else if (k === "margin" || k === "keep" || k === "prefetch") attrs.set(k, String(v));
632
+ else if (k === "stitch") {
633
+ if (v !== true && v !== "serve" && v !== "edge") throw fail(`preset '${from_preset}': \`stitch\` takes \`true\` / 'serve' (the hole fills at ORIGIN on every serve) or 'edge' (an ESI include the CDN fills — the shell stays edge-cached).`);
634
+ attrs.set("stitch", v === "edge" ? "edge" : "serve");
635
+ } else throw fail(`unknown key \`${k}\` in preset '${from_preset}'. Use ${[...PRESET_KEYS].map((key) => `\`${key}\``).join(", ")}.`);
636
+ }
637
+ } else {
638
+ for (const k of inline.keys()) if (k !== import_keys.wake && k !== import_keys.fetch && k !== import_keys.render && k !== "keep" && k !== "stitch" && k !== "prefetch") throw fail(`\`${k}\` is not allowed inline. Use \`${import_keys.wake}\`, \`${import_keys.fetch}\`, \`${import_keys.render}\`, \`keep\`, \`stitch\`, \`prefetch\`, or a named \`${import_keys.preset}\` — options like \`margin\` / \`maxAge\` belong in plugin config (ogygia({ presets })).`);
639
+ if (inline.has(import_keys.render)) render_mode = inline.get(import_keys.render);
640
+ if (inline.has(import_keys.wake)) wake_val = inline.get(import_keys.wake);
641
+ if (inline.has(import_keys.fetch)) fetch_val = inline.get(import_keys.fetch);
642
+ if (inline.has("keep")) attrs.set("keep", inline.get("keep"));
643
+ if (inline.has("prefetch")) attrs.set("prefetch", inline.get("prefetch"));
644
+ if (inline.has("stitch")) {
645
+ const mode = inline.get("stitch");
646
+ if (mode !== "serve" && mode !== "edge") throw fail(`\`stitch: '${mode}'\` — the inline values are \`stitch: 'serve'\` (the hole fills at ORIGIN on every serve) or \`stitch: 'edge'\` (an ESI include the CDN fills — the shell stays edge-cached).`);
647
+ attrs.set("stitch", mode);
648
+ }
649
+ }
650
+ if (render_mode != null && !RENDER_MODES.has(render_mode)) throw fail(`unknown ${import_keys.render} '${render_mode}'. Use 'static' (inline HTML) | 'deferred' (a hole, fetched) | 'live' (a hole that revalidates).`);
651
+ const said = from_preset ? `preset '${from_preset}'` : "this import";
652
+ if (render_mode === "deferred" && wake_val != null) throw new OgygiaError("hole_wake_removed", {
653
+ host: rel_host,
654
+ said,
655
+ render_key: import_keys.render,
656
+ wake_key: import_keys.wake,
657
+ fetch_key: import_keys.fetch,
658
+ wake: wake_val,
659
+ fetch: fetch_val ?? wake_val
660
+ });
661
+ if (fetch_val != null && render_mode !== "deferred") throw fail(`${said} sets \`${import_keys.fetch}: '${fetch_val}'\` without \`${import_keys.render}: 'deferred'\` — \`${import_keys.fetch}\` is a hole's timing. Write \`${import_keys.render}: 'deferred', ${import_keys.fetch}: '${fetch_val}'\` for a hole${render_mode == null ? `, or \`${import_keys.wake}: '${fetch_val}'\` for an island.` : "."}`);
662
+ if (render_mode === "deferred") attrs.set("defer", fetch_val ?? "load");
663
+ else if (render_mode === "live") {
664
+ attrs.set("hydrate", "none");
665
+ remount_opt = parse_remount({
666
+ revalidate: wake_val ?? live_opts.revalidate ?? "load",
667
+ ...live_opts.maxAge != null ? { maxAge: live_opts.maxAge } : {},
668
+ ...live_opts.onExpire != null ? { onExpire: live_opts.onExpire } : {}
669
+ }, err_shim, "");
670
+ } else if (wake_val != null) attrs.set("hydrate", wake_val);
671
+ if (render_mode === "static" && wake_val == null) throw fail(`${said} sets \`${import_keys.render}: 'static'\` alone, which marks nothing: 'static' is how a region renders when nothing else is said. Drop it for a plain import, or add \`${import_keys.wake}\` for an island.`);
672
+ if (attrs.has("keep") && (!attrs.has("hydrate") || attrs.get("hydrate") === "none")) throw fail(`\`keep\` keeps a waking island alive across navigations, and ${said} makes no waking island (a hole, a lake or a live region has none to keep). Drop \`keep\`, or mark it with \`${import_keys.wake}: 'load'\` (or another wake).`);
673
+ if (attrs.has("stitch") && !attrs.has("defer")) throw fail(`\`stitch\` is only valid with \`${import_keys.render}: 'deferred'\` — it says WHERE a hole fills on artifact serves; there is no hole without 'deferred'.`);
674
+ if (attrs.has("prefetch") && !attrs.has("defer")) throw fail(`\`prefetch\` is only valid with \`${import_keys.render}: 'deferred'\` — it warms a hole's HTML ahead of its \`${import_keys.fetch}\` timing; an island's JS is preloaded by the runtime when it wakes, not by \`prefetch\`.`);
675
+ if (from_preset && !attrs.has("hydrate") && !attrs.has("defer")) throw fail(`${import_keys.preset} '${from_preset}' must set \`render\` or \`wake\` — a margin-only (or empty) preset is a no-op.`);
676
+ if (attrs.has("defer")) {
677
+ const dval = attrs.get("defer");
678
+ let when;
679
+ if (parse_trigger(dval, WAKE)) when = dval;
680
+ else throw fail(`\`${import_keys.render}: 'deferred'\` fetches on its \`${import_keys.fetch}\` timing, but '${dval}' is not one. Use \`${import_keys.fetch}: 'load' | 'idle' | 'visible' | 'interaction'\` or a media query (not 'none' — a hole must fetch).`);
681
+ const options = { when };
682
+ if (attrs.has("prefetch")) {
683
+ const p = attrs.get("prefetch");
684
+ if (!parse_trigger(p, SCHEDULE)) throw fail(`\`prefetch: '${p}'\` — a hole prefetches its HTML on 'load' | 'idle' | 'visible' | a media query. Never 'interaction': that is the SWAP, \`${import_keys.fetch}\`'s job; prefetch only warms the bytes ahead of it.`);
685
+ if (p === when) throw fail(`\`prefetch: '${p}'\` is this hole's own \`${import_keys.fetch}\` schedule — it adds nothing. Prefetch EARLIER than the swap ('load' | 'idle' | 'visible' for an 'interaction' hole), or drop it.`);
686
+ options.prefetch = p;
687
+ }
688
+ if (when === "visible" || options.prefetch === "visible") options.margin = attrs.get("margin") ?? ctx.visibleMargin ?? void 0;
689
+ if (live_opts.maxAge != null) {
690
+ const ttl = parse_cache_ttl_sec(live_opts.maxAge, err_shim, "");
691
+ if (ttl != null && ttl > 0) options.cacheTtlSec = ttl;
692
+ }
693
+ if (attrs.has("stitch")) options.stitch = attrs.get("stitch");
694
+ return {
695
+ strategy: "server",
696
+ options
697
+ };
698
+ }
699
+ if (attrs.has("hydrate")) {
700
+ const val = attrs.get("hydrate");
701
+ if (val === "none") {
702
+ const lake_opts = {};
703
+ if (remount_opt) {
704
+ lake_opts.remount = remount_opt.policy;
705
+ if (remount_opt.when) lake_opts.when = remount_opt.when;
706
+ if (remount_opt.maxAgeMs != null) lake_opts.maxAgeMs = remount_opt.maxAgeMs;
707
+ if (remount_opt.onExpire) lake_opts.onExpire = remount_opt.onExpire;
708
+ if (remount_opt.policy === "swr" && remount_opt.when === "visible") lake_opts.margin = attrs.get("margin") ?? ctx.visibleMargin ?? void 0;
709
+ }
710
+ return {
711
+ strategy: "lake",
712
+ options: lake_opts
713
+ };
714
+ }
715
+ if (val === "false") throw fail(`\`${import_keys.wake}: 'false'\` is not valid — use \`${import_keys.wake}: 'none'\` for a lake (a frozen region inside a hydrated island). See DESIGN.md.`);
716
+ let strategy;
717
+ if (parse_trigger(val, WAKE)) strategy = val;
718
+ else throw fail(`unknown ${import_keys.wake} strategy '${val}'. Use 'load' | 'idle' | 'visible' | 'interaction' | a media query.`);
719
+ const options = {};
720
+ if (strategy === "visible") options.margin = attrs.get("margin") ?? ctx.visibleMargin ?? void 0;
721
+ if (attrs.has("keep")) {
722
+ const p = String(attrs.get("keep")).trim();
723
+ if (!p) throw fail(`\`keep\` needs a non-empty name (e.g. keep: 'player').`);
724
+ options.keep = p;
725
+ }
726
+ return {
727
+ strategy,
728
+ options
729
+ };
730
+ }
731
+ return null;
732
+ }
733
+ #assert_portable_children(node, local, is_server) {
734
+ const kids = (node.fragment?.nodes ?? []).filter((n) => !(n.type === "Text" && !String(n.data ?? "").trim()));
735
+ if (kids.length === 0) return;
736
+ if (is_server && kids.length === 1 && kids[0].type === "SnippetBlock" && kids[0].expression?.name === "ogygiaFallback") return;
737
+ throw new OgygiaError("region_children_not_portable", {
738
+ host: this.#rel_host,
739
+ tag: local,
740
+ server: is_server
741
+ });
742
+ }
743
+ #visit_usages(nodes) {
744
+ for (const node of nodes ?? []) {
745
+ if (node.type === "Component") {
746
+ const name = node.name || "";
747
+ if (name.includes(".")) {
748
+ const root = name.split(".")[0];
749
+ if (this.#marked_components.has(root) && this.#marked_components.get(root).strategy !== "lake") throw new OgygiaError("region_dotted_tag", {
750
+ host: this.#rel_host,
751
+ tag: name,
752
+ import: root
753
+ });
754
+ } else if (this.#marked_components.has(name)) {
755
+ this.#static_placed.add(name);
756
+ const mark = this.#marked_components.get(name);
757
+ if (mark.strategy === "lake") {
758
+ if (mark.options?.remount === "swr") assert_swr_lake_crossable(node, (specifiers, msg) => this.#err(specifiers, msg));
759
+ } else if (mark.strategy === "server" || mark.strategy === "held") this.#assert_portable_children(node, name, mark.strategy === "server");
760
+ else if ((node.fragment?.nodes ?? []).filter((n) => !(n.type === "Text" && !String(n.data ?? "").trim())).length) this.#has_island_children = true;
761
+ }
762
+ }
763
+ for (const k of CHILD_KEYS) if (node[k]?.nodes) this.#visit_usages(node[k].nodes);
764
+ }
765
+ }
766
+ #posix_rel(abs) {
767
+ return path.relative(this.#ctx.root, abs).split(PATH_SEP).join("/");
768
+ }
769
+ #component_identity(p) {
770
+ if (!path.isAbsolute(p)) return p;
771
+ return (typeof this.#ctx.pkg_identity === "function" ? this.#ctx.pkg_identity(p) : null) ?? this.#posix_rel(p);
772
+ }
773
+ #err(specifiers, msg) {
774
+ return new OgygiaError("region_import_invalid", {
775
+ host: this.#rel_host,
776
+ names: specifiers,
777
+ problem: msg
778
+ });
779
+ }
780
+ #analyze() {
781
+ const source = this.#source;
782
+ const id = this.#id;
783
+ const ctx = this.#ctx;
784
+ const import_keys = this.#import_keys;
785
+ const has_island_hint = import_keys_hint(import_keys).test(source);
786
+ if (!has_island_hint && !source.includes("{#snippet") && !source.includes("asRegion") && !has_unknown_component_attribute(source, import_keys)) return { done: null };
787
+ let ast;
788
+ try {
789
+ ast = parse(blank_styles(source), {
790
+ modern: true,
791
+ filename: id
792
+ });
793
+ } catch (err) {
794
+ warn_unparsed(id, err);
795
+ return { done: null };
796
+ }
797
+ const instance_body = ast.instance?.content?.body ?? [];
798
+ const module_body = ast.module?.content?.body ?? [];
799
+ const lang = script_lang_attr(ast.instance) || script_lang_attr(ast.module);
800
+ const rel_host = this.#rel_host = path.relative(ctx.root, id).split(PATH_SEP).join("/");
801
+ reject_dynamic_region_imports(instance_body, import_keys, rel_host);
802
+ reject_dynamic_region_imports(module_body, import_keys, rel_host);
803
+ const imports = /* @__PURE__ */ new Map();
804
+ const marked_components = this.#marked_components = /* @__PURE__ */ new Map();
805
+ const imports_to_strip = /* @__PURE__ */ new Set();
806
+ const roots = [
807
+ ast.instance?.content,
808
+ ast.module?.content,
809
+ ast.fragment
810
+ ];
811
+ refuse_as_region(roots, source, rel_host);
812
+ const marked_imports = /* @__PURE__ */ new Map();
813
+ const export_names = /* @__PURE__ */ new Map();
814
+ const region_keys = [
815
+ import_keys.wake,
816
+ import_keys.fetch,
817
+ import_keys.render,
818
+ import_keys.preset,
819
+ import_keys.region
820
+ ];
821
+ for (const node of instance_body) {
822
+ if (node.type !== "ImportDeclaration") continue;
823
+ const cleaned = clean_import_text(source, node);
824
+ for (const spec of node.specifiers) imports.set(spec.local.name, {
825
+ node,
826
+ cleaned
827
+ });
828
+ const attr_list = (node.attributes ?? []).filter((a) => a.type === "ImportAttribute");
829
+ if (attr_list.length === 0) continue;
830
+ const inline = /* @__PURE__ */ new Map();
831
+ for (const a of attr_list) inline.set(a.key.name ?? a.key.value, String(a.value.value));
832
+ if (!inline.has(import_keys.preset)) refuse_unknown_attributes(String(node.source.value), inline.keys(), import_keys, rel_host, node.specifiers.map((sp) => sp.local.name).join(", "));
833
+ if (!region_keys.some((k) => inline.has(k))) continue;
834
+ const bindings = marked_import_bindings(node, source, rel_host);
835
+ const names = bindings.map((b) => b.local).join(", ");
836
+ const mark = this.#resolve_region_mark(inline, (m) => this.#err(names, m));
837
+ if (!mark) continue;
838
+ for (const b of bindings) marked_imports.set(b.local, {
839
+ node,
840
+ exportName: b.exportName
841
+ });
842
+ if (this.#kit_owns(mark)) {
843
+ this.#to_kit.push({
844
+ start: node.start,
845
+ end: node.end,
846
+ text: cleaned
847
+ });
848
+ continue;
849
+ }
850
+ for (const b of bindings) {
851
+ marked_components.set(b.local, mark);
852
+ export_names.set(b.local, b.exportName);
853
+ }
854
+ }
855
+ check_marked_uses(roots, marked_imports, source, rel_host);
856
+ if (marked_components.size === 0 && !source.includes("{#snippet")) return { done: this.#to_kit.length ? this.#kit_only() : null };
857
+ this.#has_island_children = false;
858
+ this.#static_placed = /* @__PURE__ */ new Set();
859
+ this.#visit_usages(ast.fragment?.nodes ?? []);
860
+ this.#ast = ast;
861
+ this.#instance_body = instance_body;
862
+ this.#module_body = module_body;
863
+ this.#lang = lang;
864
+ this.#rel_host = rel_host;
865
+ this.#import_keys = import_keys;
866
+ this.#imports = imports;
867
+ this.#imports_to_strip = imports_to_strip;
868
+ this.#export_names = export_names;
869
+ this.#has_island_hint = has_island_hint;
870
+ return null;
871
+ }
872
+ #lower() {
873
+ const source = this.#source;
874
+ const id = this.#id;
875
+ const ctx = this.#ctx;
876
+ const ast = this.#ast;
877
+ const instance_body = this.#instance_body;
878
+ const module_body = this.#module_body;
879
+ const lang = this.#lang;
880
+ const rel_host = this.#rel_host;
881
+ const imports = this.#imports;
882
+ const marked_components = this.#marked_components;
883
+ const imports_to_strip = this.#imports_to_strip;
884
+ const export_names = this.#export_names;
885
+ const has_island_children = this.#has_island_children;
886
+ const has_island_hint = this.#has_island_hint;
887
+ const s = new MagicString(source);
888
+ for (const edit of this.#to_kit) s.overwrite(edit.start, edit.end, edit.text);
889
+ const origin = typeof ctx.originOf === "function" ? ctx.originOf(id) || id : id;
890
+ const islands_by_id = /* @__PURE__ */ new Map();
891
+ const salt = ctx.idSalt || "";
892
+ const wrapperPathFor = typeof ctx.wrapperPathFor === "function" ? ctx.wrapperPathFor : (_host, iid) => wrapperVirtualId(iid);
893
+ const link_virtual = ctx.linkVirtualIsland !== false;
894
+ const binding_stub = typeof ctx.clientBindingStub === "string" && ctx.clientBindingStub ? ctx.clientBindingStub : CLIENT_BINDING_STUB;
895
+ const rewritten_import_nodes = /* @__PURE__ */ new Set();
896
+ const node_rewrites = /* @__PURE__ */ new Map();
897
+ const rewrite_binding = (node, text) => {
898
+ const lines = node_rewrites.get(node);
899
+ if (lines) lines.push(text);
900
+ else node_rewrites.set(node, [text]);
901
+ };
902
+ const fouc_css_specs = /* @__PURE__ */ new Set();
903
+ const binding_rewrite = (local, bindingPath, componentPathAbs, always_link_css = false) => {
904
+ const text = `import ${local} from ${JSON.stringify(bindingPath)};`;
905
+ if (!ctx.ssr && (always_link_css || !link_virtual && ctx.dev) && typeof componentPathAbs === "string" && componentPathAbs && path.isAbsolute(componentPathAbs) && !fouc_css_specs.has(componentPathAbs)) {
906
+ fouc_css_specs.add(componentPathAbs);
907
+ const rel = this.#posix_rel(componentPathAbs);
908
+ return `${text}\nimport ${JSON.stringify(foucCssVirtualId(rel))};`;
909
+ }
910
+ return text;
911
+ };
912
+ const host_declared = /* @__PURE__ */ new Set();
913
+ const declare = (node) => {
914
+ if (node?.type === "VariableDeclaration") for (const d of node.declarations) collect_pattern_names(d.id, host_declared);
915
+ else if (node?.type === "FunctionDeclaration" || node?.type === "ClassDeclaration") {
916
+ if (node.id?.name) host_declared.add(node.id.name);
917
+ } else if (node?.type === "ExportNamedDeclaration") declare(node.declaration);
918
+ else if (node?.type === "LabeledStatement" && node.label?.name === "$") {
919
+ const e = node.body?.type === "ExpressionStatement" ? node.body.expression : null;
920
+ if (e?.type === "AssignmentExpression") collect_pattern_names(e.left, host_declared);
921
+ }
922
+ };
923
+ for (const node of instance_body) declare(node);
924
+ for (const node of module_body) declare(node);
925
+ const module_imports = /* @__PURE__ */ new Map();
926
+ for (const node of module_body) {
927
+ if (node.type !== "ImportDeclaration") continue;
928
+ const cleaned = clean_import_text(source, node);
929
+ for (const spec of node.specifiers) module_imports.set(spec.local.name, cleaned);
930
+ }
931
+ const store_like = /* @__PURE__ */ new Set();
932
+ for (const node of instance_body) {
933
+ if (node.type !== "VariableDeclaration") continue;
934
+ for (const d of node.declarations) {
935
+ const callee = d.init?.type === "CallExpression" ? d.init.callee : null;
936
+ const cname = callee?.type === "Identifier" ? callee.name : null;
937
+ if (cname && STORE_CTORS.has(cname) && d.id?.type === "Identifier") store_like.add(d.id.name);
938
+ }
939
+ }
940
+ STORE_SUB_RE.lastIndex = 0;
941
+ for (let m; m = STORE_SUB_RE.exec(source);) {
942
+ if (source.charCodeAt(m.index - 1) === 36) continue;
943
+ if (!RUNE_NAMES.has(m[1])) store_like.add(m[1]);
944
+ }
945
+ for (const [local, mark] of marked_components) {
946
+ const info = imports.get(local);
947
+ if (!info) continue;
948
+ if (!this.#marked_import_referenced(local)) {
949
+ if (!rewritten_import_nodes.has(info.node)) imports_to_strip.add(info.node);
950
+ continue;
951
+ }
952
+ const entry_spec = info.node.source?.value;
953
+ const componentPath = resolve_component_path(entry_spec, origin, ctx);
954
+ if (!componentPath) throw new OgygiaError("region_import_no_specifier", {
955
+ host: rel_host,
956
+ name: local,
957
+ held: false
958
+ });
959
+ const named_export = export_names.get(local);
960
+ const exportName = named_export === "default" ? void 0 : named_export;
961
+ const comp_rel = this.#component_identity(componentPath);
962
+ const id_base = exportName ? `${comp_rel}#${exportName}` : comp_rel;
963
+ const identity = regionIdentity(id_base, mark);
964
+ const iid = regionId(identity, salt);
965
+ const entryPath = ctx.virtualPathFor(id, iid);
966
+ const wrapPath = wrapperPathFor(id, iid);
967
+ const bindingPath = link_virtual ? wrapPath : binding_stub;
968
+ if (mark.strategy === "lake") {
969
+ if (!islands_by_id.has(iid)) {
970
+ const swr = (mark.options?.remount || "cache") === "swr";
971
+ islands_by_id.set(iid, {
972
+ id: iid,
973
+ virtualPath: swr ? entryPath : void 0,
974
+ source: swr ? island_entry_source(componentPath, iid, exportName) : void 0,
975
+ wrapperPath: wrapPath,
976
+ wrapperSource: lake_wrapper_source(iid, componentPath, mark.options, exportName),
977
+ hostPath: origin,
978
+ componentPath,
979
+ server: swr,
980
+ kind: "lake",
981
+ lakes: ["OgygiaLakeInner"],
982
+ identity
983
+ });
984
+ }
985
+ rewrite_binding(info.node, binding_rewrite(local, bindingPath, componentPath, true));
986
+ continue;
987
+ }
988
+ if (mark.strategy === "held") {
989
+ if (!islands_by_id.has(iid)) islands_by_id.set(iid, make_region_binding({
990
+ iid,
991
+ componentPath,
992
+ entryPath,
993
+ hostPath: origin,
994
+ moduleUrl: ctx.dev ? ctx.devUrlFor(entryPath) : islandPublicUrl(iid, ctx.appDir),
995
+ exportName,
996
+ identity
997
+ }));
998
+ rewrite_binding(info.node, `import ${local} from ${JSON.stringify(regionBindingVirtualId(iid))};`);
999
+ continue;
1000
+ }
1001
+ const is_server = mark.strategy === "server";
1002
+ const deferred_hydrate = is_server && !!mark.options?.hydrate;
1003
+ const wants_attach = !is_server;
1004
+ if (!islands_by_id.has(iid)) islands_by_id.set(iid, is_server ? {
1005
+ id: iid,
1006
+ virtualPath: entryPath,
1007
+ wrapperPath: wrapPath,
1008
+ wrapperSource: server_wrapper_source(iid, componentPath, entryPath, mark.options, exportName, ctx.dev ? ctx.devUrlFor(entryPath) : islandPublicUrl(iid, ctx.appDir)),
1009
+ wrapperClientSource: server_wrapper_source(iid, componentPath, entryPath, mark.options, exportName, ctx.dev ? ctx.devUrlFor(entryPath) : islandPublicUrl(iid, ctx.appDir), false),
1010
+ source: island_entry_source(componentPath, iid, exportName),
1011
+ hostPath: origin,
1012
+ componentPath,
1013
+ server: true,
1014
+ kind: deferred_hydrate ? "hydrate" : "defer",
1015
+ lakes: [],
1016
+ identity,
1017
+ strategy: mark.strategy,
1018
+ fetchWhen: mark.options?.when,
1019
+ wakeAfter: deferred_hydrate ? mark.options?.hydrate : void 0,
1020
+ keep: mark.options?.keep
1021
+ } : make_wake_island({
1022
+ iid,
1023
+ componentPath,
1024
+ entryPath,
1025
+ wrapperPath: wrapPath,
1026
+ moduleUrl: ctx.dev ? ctx.devUrlFor(entryPath) : islandPublicUrl(iid, ctx.appDir),
1027
+ strategy: mark.strategy,
1028
+ options: mark.options,
1029
+ exportName,
1030
+ hostPath: origin,
1031
+ identity
1032
+ }));
1033
+ const rewrite_path = wants_attach && link_virtual ? regionBindingVirtualId(iid) : bindingPath;
1034
+ rewrite_binding(info.node, binding_rewrite(local, rewrite_path, componentPath));
1035
+ }
1036
+ for (const [node, lines] of node_rewrites) {
1037
+ s.overwrite(node.start, node.end, lines.join("\n"));
1038
+ rewritten_import_nodes.add(node);
1039
+ }
1040
+ for (const node of imports_to_strip) {
1041
+ if (rewritten_import_nodes.has(node)) continue;
1042
+ s.remove(node.start, node.end);
1043
+ }
1044
+ const OG_PORTABLE = "__og_portable";
1045
+ const portable_candidates = [];
1046
+ const portable_allowed = !id.includes("node_modules");
1047
+ const walk_portable = (nodes) => {
1048
+ for (const node of nodes ?? []) {
1049
+ if (is_component_node(node)) {
1050
+ const base_name = String(node.name || "").split(".")[0];
1051
+ const mark = marked_components.get(base_name);
1052
+ const island_site = !!mark && ![
1053
+ "lake",
1054
+ "server",
1055
+ "held"
1056
+ ].includes(mark.strategy);
1057
+ const from_generated = String(imports.get(base_name)?.node?.source?.value ?? "").startsWith(OGYGIA_SCHEME);
1058
+ for (const child of node.fragment?.nodes ?? []) {
1059
+ if (child.type !== "SnippetBlock" || !child.expression?.name) continue;
1060
+ const zero_arg = (child.parameters?.length ?? 0) === 0;
1061
+ if (island_site || !mark && zero_arg && !from_generated) portable_candidates.push({
1062
+ comp: node,
1063
+ snip: child
1064
+ });
1065
+ }
1066
+ }
1067
+ for (const k of CHILD_KEYS) if (node[k]?.nodes) walk_portable(node[k].nodes);
1068
+ }
1069
+ };
1070
+ if (portable_allowed) walk_portable(ast.fragment?.nodes ?? []);
1071
+ const by_start = [...portable_candidates].sort(outer_spans_first);
1072
+ const nested = /* @__PURE__ */ new Set();
1073
+ let reach = -Infinity;
1074
+ for (let i = 0; i < by_start.length; i++) {
1075
+ const c = by_start[i];
1076
+ if (c.snip.end <= reach) nested.add(c);
1077
+ if (c.snip.end > reach) reach = c.snip.end;
1078
+ }
1079
+ const outer_candidates = portable_candidates.filter((c) => !nested.has(c));
1080
+ const block_bound = /* @__PURE__ */ new Set();
1081
+ const bind_pattern = (n) => {
1082
+ if (Array.isArray(n)) for (const p of n) collect_pattern_names(p, block_bound);
1083
+ else collect_pattern_names(n, block_bound);
1084
+ };
1085
+ const walk_bound = (nodes, root) => {
1086
+ for (const node of nodes ?? []) {
1087
+ if (node.type === "EachBlock") {
1088
+ bind_pattern(node.context);
1089
+ if (node.index) block_bound.add(node.index);
1090
+ } else if (node.type === "AwaitBlock") {
1091
+ bind_pattern(node.value);
1092
+ bind_pattern(node.error);
1093
+ } else if (node.type === "ConstTag") bind_pattern(node.declaration?.declarations?.map((d) => d.id));
1094
+ else if (node.type === "SnippetBlock") {
1095
+ bind_pattern(node.parameters);
1096
+ if (!root && node.expression?.name) block_bound.add(node.expression.name);
1097
+ }
1098
+ for (const a of node.attributes ?? []) {
1099
+ if (a.type !== "LetDirective") continue;
1100
+ if (a.expression) bind_pattern(a.expression);
1101
+ else if (a.name) block_bound.add(a.name);
1102
+ }
1103
+ for (const k of CHILD_KEYS) if (node[k]?.nodes) walk_bound(node[k].nodes, false);
1104
+ }
1105
+ };
1106
+ walk_bound(ast.fragment?.nodes ?? [], true);
1107
+ const root_snippets = /* @__PURE__ */ new Map();
1108
+ for (const n of ast.fragment?.nodes ?? []) if (n.type === "SnippetBlock" && n.expression?.name) root_snippets.set(n.expression.name, n);
1109
+ let portable_emitted = false;
1110
+ const portable_imports = [];
1111
+ const portable_seen = /* @__PURE__ */ new Set();
1112
+ let native_seq = 0;
1113
+ const host_style_src = ast.css ? source.slice(ast.css.start, ast.css.end) : "";
1114
+ for (const { comp, snip } of outer_candidates) {
1115
+ const name = snip.expression.name;
1116
+ const body = snip.body?.nodes ?? [];
1117
+ if (!body.length) continue;
1118
+ const snip_params = snip.parameters ?? [];
1119
+ const params_src = snip_params.length ? source.slice(snip_params[0].start, snip_params[snip_params.length - 1].end) : "";
1120
+ const param_names = /* @__PURE__ */ new Set();
1121
+ for (const p of snip_params) collect_pattern_names(p, param_names);
1122
+ const { free, mutated, stores } = collectCaptureInfo([snip]);
1123
+ if ([...free].some((nm) => block_bound.has(nm) && !param_names.has(nm))) continue;
1124
+ if (mutated.size) continue;
1125
+ const carried = [];
1126
+ const pending = [...free].filter((nm) => root_snippets.has(nm) && !param_names.has(nm));
1127
+ const carried_names = /* @__PURE__ */ new Set();
1128
+ let carry_blocked = false;
1129
+ while (pending.length && !carry_blocked) {
1130
+ const nm = pending.pop();
1131
+ if (carried_names.has(nm)) continue;
1132
+ carried_names.add(nm);
1133
+ const node = root_snippets.get(nm);
1134
+ const info = collectCaptureInfo([node]);
1135
+ if (info.mutated.size || info.stores.size) carry_blocked = true;
1136
+ carried.push(node);
1137
+ for (const f of info.free) if (root_snippets.has(f)) pending.push(f);
1138
+ else free.add(f);
1139
+ }
1140
+ if (carry_blocked) continue;
1141
+ for (const nm of carried_names) free.delete(nm);
1142
+ const store_captures = [];
1143
+ const store_rewrites = [];
1144
+ for (const [nm, sites] of stores) {
1145
+ if (nm.startsWith("$$")) throw new OgygiaError("snippet_reads_dollar_props", {
1146
+ host: rel_host,
1147
+ snippet: name,
1148
+ name: nm
1149
+ });
1150
+ const base = nm.slice(1);
1151
+ const prop = `__og_sub_${base}`;
1152
+ store_captures.push({
1153
+ prop,
1154
+ expr: nm
1155
+ });
1156
+ for (const p of sites) store_rewrites.push({
1157
+ start: p.start,
1158
+ end: p.end,
1159
+ prop
1160
+ });
1161
+ const trace = sites.map((p) => `${rel_host}:${line_col(source, p.start)}`).join(", ");
1162
+ if (host_declared.has(base) || imports.has(base)) warn_once(`${id}\0${name}\0${nm}\0frozen`, () => warn("snippet_store_snapshot", {
1163
+ host: rel_host,
1164
+ snippet: name,
1165
+ store: nm,
1166
+ at: trace
1167
+ }));
1168
+ else warn_once(`${id}\0${name}\0${nm}\0unresolved`, () => warn("snippet_store_unverified", {
1169
+ host: rel_host,
1170
+ snippet: name,
1171
+ store: nm,
1172
+ at: trace
1173
+ }));
1174
+ }
1175
+ const cleaned_imports = [];
1176
+ const seen_imports = /* @__PURE__ */ new Set();
1177
+ const captures = [];
1178
+ for (const nm of free) {
1179
+ if (nm.startsWith("$")) continue;
1180
+ if (param_names.has(nm)) continue;
1181
+ if (imports.has(nm)) {
1182
+ const info = imports.get(nm);
1183
+ const text = marked_components.has(nm) ? source.slice(info.node.start, info.node.end).trim() : info.cleaned.trim();
1184
+ if (!seen_imports.has(text)) {
1185
+ seen_imports.add(text);
1186
+ cleaned_imports.push(text);
1187
+ }
1188
+ } else if (host_declared.has(nm)) {
1189
+ if (store_like.has(nm)) warn_once(`${id}\0${name}\0${nm}\0object`, () => warn("snippet_captures_store", {
1190
+ host: rel_host,
1191
+ snippet: name,
1192
+ store: nm
1193
+ }));
1194
+ captures.push(nm);
1195
+ } else if (module_imports.has(nm)) {
1196
+ const text = module_imports.get(nm).trim();
1197
+ if (!seen_imports.has(text)) {
1198
+ seen_imports.add(text);
1199
+ cleaned_imports.push(text);
1200
+ }
1201
+ }
1202
+ }
1203
+ const body_start = body[0].start;
1204
+ const body_end = body[body.length - 1].end;
1205
+ let markup;
1206
+ if (store_rewrites.length) {
1207
+ store_rewrites.sort((a, b) => a.start - b.start);
1208
+ let out = "";
1209
+ let cursor = body_start;
1210
+ for (const r of store_rewrites) {
1211
+ out += source.slice(cursor, r.start) + r.prop;
1212
+ cursor = r.end;
1213
+ }
1214
+ markup = out + source.slice(cursor, body_end);
1215
+ } else markup = source.slice(body_start, body_end);
1216
+ const carried_src = carried.map((n) => source.slice(n.start, n.end)).join("\n");
1217
+ const hash = createHash("md5").update(`${markup}\0${captures.join(",")}\0${cleaned_imports.join("\n")}\0${params_src}\0${carried_src}`).digest("hex").slice(0, 12);
1218
+ const identity = regionIdentity(`${this.#component_identity(this.#id)}\0psnip:${hash}`, { strategy: "hydrate" });
1219
+ const iid = regionId(identity, salt);
1220
+ const entryPath = ctx.virtualPathFor(id, iid).replace(JS_EXT, ".svelte");
1221
+ if (!islands_by_id.has(iid)) {
1222
+ const store_props = store_captures.map((c) => c.prop);
1223
+ const prop_names = snip_params.length ? [
1224
+ "__ogArgs = []",
1225
+ ...captures,
1226
+ ...store_props
1227
+ ] : [...captures, ...store_props];
1228
+ const wrapped = body.some((n) => n.type === "ConstTag");
1229
+ const template = (carried_src ? `${carried_src}\n` : "") + (wrapped ? dedent`
1230
+ {#snippet __og_body()}
1231
+ ${markup}
1232
+ {/snippet}
1233
+ {@render __og_body()}
1234
+ ` : markup);
1235
+ const synth = `<script${lang}>
1236
+ import 'ogygia:region/transportables-eager';
1237
+ ${cleaned_imports.map((imp) => `\t${imp}\n`).join("")}${prop_names.length ? `\t// svelte-ignore state_referenced_locally\n\tlet { ${prop_names.join(", ")} } = $props();\n` : ""}${snip_params.length ? `\t// svelte-ignore state_referenced_locally\n\tconst [${params_src}] = __ogArgs;\n` : ""}<\/script>
1238
+ ${template}
1239
+ ${host_style_src ? `${host_style_src}\n` : ""}`;
1240
+ islands_by_id.set(iid, {
1241
+ id: iid,
1242
+ virtualPath: entryPath,
1243
+ wrapperPath: wrapperPathFor(id, iid),
1244
+ wrapperSource: "",
1245
+ source: synth,
1246
+ hostPath: origin,
1247
+ componentPath: entryPath,
1248
+ server: false,
1249
+ kind: "hydrate",
1250
+ lakes: [],
1251
+ identity,
1252
+ strategy: "hydrate",
1253
+ portable: true
1254
+ });
1255
+ }
1256
+ const url = ctx.dev ? ctx.devUrlFor(entryPath) : islandPublicUrl(iid, ctx.appDir);
1257
+ const cap_entries = [...captures, ...store_captures.map((c) => `${c.prop}: ${c.expr}`)];
1258
+ const cap_obj = cap_entries.length ? `{ ${cap_entries.join(", ")} }` : "{}";
1259
+ const entry_ref = ctx.ssr ? `__OgPS_${iid}` : "null";
1260
+ if (!portable_seen.has(iid)) {
1261
+ portable_seen.add(iid);
1262
+ if (ctx.ssr) portable_imports.push(`import __OgPS_${iid} from ${JSON.stringify(entryPath)};`);
1263
+ }
1264
+ const native_name = `__og_native_${name}_${native_seq++}`;
1265
+ s.move(snip.start, snip.end, source.length);
1266
+ s.overwrite(snip.expression.start, snip.expression.end, native_name);
1267
+ const insert_at = comp.start + 1 + String(comp.name).length;
1268
+ s.appendLeft(insert_at, ` ${name}={${OG_PORTABLE}(${native_name}, ${entry_ref}, ${cap_obj}, ${JSON.stringify(url)})}`);
1269
+ portable_emitted = true;
1270
+ }
1271
+ if (portable_emitted) {
1272
+ const head = `${[`import { og_portable as ${OG_PORTABLE} } from 'ogygia/internal';`, ...portable_imports].join("\n")}\n`;
1273
+ if (ast.instance) s.appendLeft(ast.instance.content.start, `\n${head}`);
1274
+ else s.prepend(`${dedent(_templateObject || (_templateObject = _taggedTemplateLiteral([
1275
+ "\n <script",
1276
+ ">\n ",
1277
+ "<\/script>\n "
1278
+ ])), lang, head)}\n`);
1279
+ }
1280
+ if (!has_island_hint && !portable_emitted && islands_by_id.size === 0 && this.#to_kit.length === 0) return null;
1281
+ const has_dynamic_island_use = [...marked_components].some(([name, m]) => is_wake_island(m) && !this.#static_placed.has(name));
1282
+ return {
1283
+ code: s.toString(),
1284
+ map: s.generateMap({
1285
+ hires: true,
1286
+ source: id,
1287
+ includeContent: true
1288
+ }),
1289
+ islands: [...islands_by_id.values()],
1290
+ hasWireCrossing: has_island_children || has_dynamic_island_use || portable_emitted
1291
+ };
1292
+ }
1293
+ };
1294
+ function outer_spans_first(a, b) {
1295
+ return a.snip.start - b.snip.start;
1296
+ }
1297
+ function import_attrs_of(node) {
1298
+ const attrs = /* @__PURE__ */ new Map();
1299
+ for (const a of node.attributes ?? []) {
1300
+ const key = a.key?.type === "Identifier" ? a.key.name : a.key?.value;
1301
+ if (typeof key === "string" && typeof a.value?.value === "string") attrs.set(key, a.value.value);
1302
+ }
1303
+ return attrs;
1304
+ }
1305
+ /**
1306
+ * Rewrite held-region imports in a `.ts` / `.js` module (a load or remote function, where held
1307
+ * regions are minted and handed to `region()`). Svelte's `parse()` can't read these files, so this
1308
+ * reads the module's oxc AST; only the default-import form is a region import. A `.ts` module has no template,
1309
+ * so every marked import here is HELD → a descriptor. Two markers:
1310
+ * - `region: 'raw'` → bakes no schedule (set at the `region()` call).
1311
+ * - `wake: 'x'` → bakes that schedule (the `region()` call can still override).
1312
+ * Each registers a server-manifest entry + client chunk and is rewritten to import the leg-split
1313
+ * descriptor module. Returns the same `{code, map, islands}` shape, or `null` when nothing matched.
1314
+ *
1315
+ * @param source
1316
+ * @param id absolute module path
1317
+ * @param ctx same context fields as {@link transformHost} (root, libDir, dev, devUrlFor,
1318
+ * virtualPathFor, importKeys, idSalt)
1319
+ * @returns
1320
+ */
1321
+ function transformTsRegions(source, id, ctx) {
1322
+ return new TsRegionCompilation(source, id, ctx).run();
1323
+ }
1324
+ var TsRegionCompilation = class {
1325
+ #source;
1326
+ #id;
1327
+ #ctx;
1328
+ #import_keys;
1329
+ #regionKey;
1330
+ #wakeKey;
1331
+ #root;
1332
+ #salt;
1333
+ #rel_host;
1334
+ constructor(source, id, ctx) {
1335
+ this.#source = source;
1336
+ this.#id = id;
1337
+ this.#ctx = ctx;
1338
+ this.#import_keys = normalize_import_keys(ctx.importKeys);
1339
+ this.#regionKey = this.#import_keys.region;
1340
+ this.#wakeKey = this.#import_keys.wake;
1341
+ this.#root = ctx.root;
1342
+ this.#salt = ctx.idSalt || "";
1343
+ this.#rel_host = path.relative(this.#root, id).split(PATH_SEP).join("/");
1344
+ }
1345
+ #posix_rel(abs) {
1346
+ return path.relative(this.#root, abs).split(PATH_SEP).join("/");
1347
+ }
1348
+ #resolve_spec(spec) {
1349
+ if (typeof spec !== "string" || !spec.trim()) return null;
1350
+ return resolve_app_spec(spec, this.#id, this.#ctx) ?? spec;
1351
+ }
1352
+ #component_identity(p) {
1353
+ if (!path.isAbsolute(p)) return p;
1354
+ const ctx = this.#ctx;
1355
+ return (typeof ctx.pkg_identity === "function" ? ctx.pkg_identity(p) : null) ?? this.#posix_rel(p);
1356
+ }
1357
+ #wrapper_path_for(wid) {
1358
+ const ctx = this.#ctx;
1359
+ return typeof ctx.wrapperPathFor === "function" ? ctx.wrapperPathFor(this.#id, wid) : wrapperVirtualId(wid);
1360
+ }
1361
+ #emit_ts_region(componentPath, marker, exportName) {
1362
+ const comp_rel = this.#component_identity(componentPath);
1363
+ const id_base = exportName && exportName !== "default" ? `${comp_rel}#${exportName}` : comp_rel;
1364
+ const fetchKey = this.#import_keys.fetch;
1365
+ const renderKey = this.#import_keys.render;
1366
+ if (marker.fetch != null && marker.render == null) throw new OgygiaError("held_fetch_without_render", {
1367
+ host: this.#rel_host,
1368
+ fetch_key: fetchKey,
1369
+ render_key: renderKey,
1370
+ wake_key: this.#wakeKey,
1371
+ value: marker.fetch
1372
+ });
1373
+ if (marker.render != null) {
1374
+ if (marker.render !== "deferred") throw marker.render === "live" ? new OgygiaError("held_render_live", {
1375
+ host: this.#rel_host,
1376
+ render_key: renderKey
1377
+ }) : new OgygiaError("held_render_unknown", {
1378
+ host: this.#rel_host,
1379
+ render_key: renderKey,
1380
+ value: marker.render
1381
+ });
1382
+ if (marker.wake != null) throw new OgygiaError("hole_wake_removed", {
1383
+ host: this.#rel_host,
1384
+ render_key: renderKey,
1385
+ wake_key: this.#wakeKey,
1386
+ fetch_key: fetchKey,
1387
+ wake: marker.wake,
1388
+ fetch: marker.fetch ?? marker.wake
1389
+ });
1390
+ const dval = marker.fetch ?? "load";
1391
+ let when;
1392
+ if (parse_trigger(dval, WAKE)) when = dval;
1393
+ else throw new OgygiaError("held_fetch_not_timing", {
1394
+ host: this.#rel_host,
1395
+ fetch_key: fetchKey,
1396
+ value: dval
1397
+ });
1398
+ const options = { when };
1399
+ if (when === "visible" && this.#ctx.visibleMargin != null) options.margin = this.#ctx.visibleMargin;
1400
+ const identity = regionIdentity(id_base, {
1401
+ strategy: "server",
1402
+ options
1403
+ });
1404
+ const iid = regionId(identity, this.#salt);
1405
+ const entryPath = this.#ctx.virtualPathFor(this.#id, iid);
1406
+ const wrapPath = this.#wrapper_path_for(iid);
1407
+ return {
1408
+ iid,
1409
+ importFrom: wrapPath,
1410
+ record: {
1411
+ id: iid,
1412
+ virtualPath: entryPath,
1413
+ wrapperPath: wrapPath,
1414
+ wrapperSource: server_wrapper_source(iid, componentPath, entryPath, options, exportName, this.#ctx.dev ? this.#ctx.devUrlFor(entryPath) : islandPublicUrl(iid, this.#ctx.appDir)),
1415
+ wrapperClientSource: server_wrapper_source(iid, componentPath, entryPath, options, exportName, this.#ctx.dev ? this.#ctx.devUrlFor(entryPath) : islandPublicUrl(iid, this.#ctx.appDir), false),
1416
+ source: island_entry_source(componentPath, iid, exportName),
1417
+ hostPath: this.#id,
1418
+ componentPath,
1419
+ server: true,
1420
+ kind: "defer",
1421
+ lakes: [],
1422
+ identity,
1423
+ strategy: "server",
1424
+ fetchWhen: options.when
1425
+ }
1426
+ };
1427
+ }
1428
+ if (marker.region != null) {
1429
+ normalize_region_value(marker.region, this.#rel_host, this.#regionKey);
1430
+ const identity = regionIdentity(id_base, {
1431
+ strategy: "held",
1432
+ options: {}
1433
+ });
1434
+ const iid = regionId(identity, this.#salt);
1435
+ const entryPath = this.#ctx.virtualPathFor(this.#id, iid);
1436
+ return {
1437
+ iid,
1438
+ importFrom: regionBindingVirtualId(iid),
1439
+ record: make_region_binding({
1440
+ iid,
1441
+ componentPath,
1442
+ entryPath,
1443
+ hostPath: this.#id,
1444
+ moduleUrl: this.#ctx.dev ? this.#ctx.devUrlFor(entryPath) : islandPublicUrl(iid, this.#ctx.appDir),
1445
+ exportName,
1446
+ identity
1447
+ })
1448
+ };
1449
+ }
1450
+ const strategy = normalize_hydrate_value(marker.wake, this.#rel_host, this.#wakeKey);
1451
+ const hydrateMargin = strategy === "visible" && this.#ctx.visibleMargin != null ? this.#ctx.visibleMargin : void 0;
1452
+ const identity = regionIdentity(id_base, {
1453
+ strategy: "held",
1454
+ options: hydrateMargin ? {
1455
+ hydrate: strategy,
1456
+ hydrateMargin
1457
+ } : { hydrate: strategy }
1458
+ });
1459
+ const iid = regionId(identity, this.#salt);
1460
+ const entryPath = this.#ctx.virtualPathFor(this.#id, iid);
1461
+ return {
1462
+ iid,
1463
+ importFrom: regionBindingVirtualId(iid),
1464
+ record: make_wake_island({
1465
+ iid,
1466
+ componentPath,
1467
+ entryPath,
1468
+ wrapperPath: this.#wrapper_path_for(iid),
1469
+ moduleUrl: this.#ctx.dev ? this.#ctx.devUrlFor(entryPath) : islandPublicUrl(iid, this.#ctx.appDir),
1470
+ strategy,
1471
+ options: hydrateMargin ? { margin: hydrateMargin } : {},
1472
+ hostPath: this.#id,
1473
+ identity,
1474
+ held: true,
1475
+ exportName
1476
+ })
1477
+ };
1478
+ }
1479
+ run() {
1480
+ const source = this.#source;
1481
+ const id = this.#id;
1482
+ const import_keys = this.#import_keys;
1483
+ const regionKey = this.#regionKey;
1484
+ const wakeKey = this.#wakeKey;
1485
+ const renderKey = import_keys.render;
1486
+ const fetchKey = import_keys.fetch;
1487
+ if (!source.includes("asRegion") && !has_unknown_component_attribute(source, import_keys) && (!import_keys_hint(import_keys).test(source) || !source.includes("with") && !source.includes("assert"))) return null;
1488
+ const rel_host = this.#rel_host;
1489
+ const s = new MagicString(source);
1490
+ const islands_by_id = /* @__PURE__ */ new Map();
1491
+ let matched = false;
1492
+ const { program, ok } = parse_module(source, id);
1493
+ if (!ok || !program) return null;
1494
+ const body = program.body ?? [];
1495
+ reject_dynamic_region_imports(body, import_keys, rel_host);
1496
+ refuse_as_region(body, source, rel_host);
1497
+ const marked = /* @__PURE__ */ new Map();
1498
+ for (const node of body) {
1499
+ if (node.type !== "ImportDeclaration" && node.type !== "ExportNamedDeclaration" && node.type !== "ExportAllDeclaration") continue;
1500
+ const attrs = import_attrs_of(node);
1501
+ if (node.type === "ImportDeclaration" && attrs.size > 0) refuse_unknown_attributes(String(node.source?.value ?? ""), attrs.keys(), import_keys, rel_host, (node.specifiers ?? []).map((sp) => sp.local?.name).join(", "));
1502
+ const has_render = attrs.has(renderKey);
1503
+ const has_region = attrs.has(regionKey);
1504
+ const has_wake = attrs.has(wakeKey);
1505
+ const has_fetch = attrs.has(fetchKey);
1506
+ if (!has_render && !has_region && !has_wake && !has_fetch) continue;
1507
+ if (node.type !== "ImportDeclaration") throw new OgygiaError("region_import_invalid", {
1508
+ host: rel_host,
1509
+ names: (node.specifiers ?? []).map((sp) => (sp.exported ?? sp.local)?.name).filter(Boolean).join(", ") || String(node.source?.value ?? "?"),
1510
+ problem: `a re-export cannot carry a region mark. Import it with the mark, then export the binding: \`import { X } from '…' with { … }; export { X };\``
1511
+ });
1512
+ const bindings = marked_import_bindings(node, source, rel_host);
1513
+ const local = bindings.map((b) => b.local).join(", ");
1514
+ const spec = String(node.source.value);
1515
+ if (has_region && attrs.size > 1 || has_render && [...attrs.keys()].some((k) => k !== renderKey && k !== wakeKey && k !== fetchKey) || !has_render && has_wake && attrs.size > 1) throw new OgygiaError("held_marker_mixed", {
1516
+ host: rel_host,
1517
+ name: local,
1518
+ region_key: regionKey,
1519
+ wake_key: wakeKey,
1520
+ render_key: renderKey,
1521
+ fetch_key: fetchKey
1522
+ });
1523
+ const componentPath = this.#resolve_spec(spec);
1524
+ if (!componentPath) throw new OgygiaError("region_import_no_specifier", {
1525
+ host: rel_host,
1526
+ name: local,
1527
+ held: true
1528
+ });
1529
+ let marker = { wake: attrs.get(wakeKey) };
1530
+ if (has_render) marker = {
1531
+ render: attrs.get(renderKey),
1532
+ wake: attrs.get(wakeKey),
1533
+ fetch: attrs.get(fetchKey)
1534
+ };
1535
+ else if (has_region) marker = { region: attrs.get(regionKey) };
1536
+ else if (has_fetch) marker = { fetch: attrs.get(fetchKey) };
1537
+ const lines = [];
1538
+ for (const b of bindings) {
1539
+ const { iid, record, importFrom } = this.#emit_ts_region(componentPath, marker, b.exportName === "default" ? void 0 : b.exportName);
1540
+ if (!islands_by_id.has(iid)) islands_by_id.set(iid, record);
1541
+ lines.push(`import ${b.local} from ${JSON.stringify(importFrom)};`);
1542
+ marked.set(b.local, {
1543
+ node,
1544
+ exportName: b.exportName
1545
+ });
1546
+ }
1547
+ s.overwrite(node.start, node.end, lines.join("\n"));
1548
+ matched = true;
1549
+ }
1550
+ check_marked_uses(body, marked, source, rel_host);
1551
+ if (!matched) return null;
1552
+ const islands = [...islands_by_id.values()];
1553
+ return {
1554
+ code: s.toString(),
1555
+ map: s.generateMap({
1556
+ hires: true,
1557
+ source: id,
1558
+ includeContent: true
1559
+ }),
1560
+ islands,
1561
+ hasWireCrossing: islands.some((i) => typeof i.strategy === "string" && i.strategy !== "server")
1562
+ };
1563
+ }
1564
+ };
1565
+ export { CLIENT_BINDING_STUB, DEFAULT_IMPORT_KEYS, ISLAND_DIR, PRESET_KEYS, STABLE_NAME_DIR, foucCssVirtualId, import_keys_hint, is_island_path, islandChunkFileName, islandId, islandPublicUrl, normalize_hydrate_value, normalize_import_keys, normalize_region_value, regionBindingVirtualId, regionId, regionIdentity, strategyKey, transformHost, transformTsRegions, wrapperVirtualId };