@stacksjs/stx 0.2.189 → 0.2.191

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.
@@ -206,7 +206,7 @@ function compileTemplateToRender(template) {
206
206
  function compileScriptScope(source, file, outputDir) {
207
207
  const block = [...source.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((script) => !/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(script[1]));
208
208
  if (!block)
209
- return { imports: [], body: "", propNames: [], defaults: {} };
209
+ return { imports: [], body: "", propNames: [], defaults: {}, declared: {} };
210
210
  let code = block[2];
211
211
  const imports = [], propNames = [], defaults = {}, declared = {};
212
212
  code = code.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm, (statement) => {
@@ -22,17 +22,31 @@
22
22
  *
23
23
  * @module composable-loader
24
24
  */
25
+ /** One composable file and the names it exports. */
26
+ export interface ComposableModule {
27
+ /** Absolute path to the `.ts` file. */
28
+ file: string;
29
+ /** Exported binding names, excluding `default`. */
30
+ names: string[];
31
+ }
25
32
  /**
26
- * Discover composable files and bundle them into a single script that
27
- * populates `window.__composables`.
33
+ * Every composable file in the resolved directory, with its exported names.
28
34
  *
29
- * Every file is concatenated into ONE IIFE, so composables can call each other
30
- * directly without importing — their declarations share a scope once the
31
- * import statements are stripped.
35
+ * Shared by the two consumers that need the names without the bundle: the
36
+ * typechecker, which has to declare them or an app's own composables read as
37
+ * undefined (#1934), and the per-page pruning that decides which of them a page
38
+ * actually references (#1936).
32
39
  *
33
- * Returns `null` when there is nothing to load, so callers can skip injection.
40
+ * Returns an empty array when there is no composables directory, which is the
41
+ * common case and not an error.
34
42
  */
35
- export declare function getComposableScript(composablesDir?: string): Promise<string | null>;
43
+ export declare function listComposableModules(composablesDir?: string): Promise<ComposableModule[]>;
44
+ /**
45
+ * @param pageSource - the rendered page, used to drop composables it cannot
46
+ * reach. Omit to emit every composable, which is what a caller with no page in
47
+ * hand needs.
48
+ */
49
+ export declare function getComposableScript(composablesDir?: string, pageSource?: string): Promise<string | null>;
36
50
  /**
37
51
  * Clear the cached composable script (for dev mode hot reload).
38
52
  */
@@ -37,7 +37,61 @@ async function probeDefaultDirs() {
37
37
  }
38
38
  return null;
39
39
  }
40
- export async function getComposableScript(composablesDir) {
40
+ export async function listComposableModules(composablesDir) {
41
+ const resolvedDir = await resolveComposablesDir(composablesDir);
42
+ if (!resolvedDir)
43
+ return [];
44
+ const files = [];
45
+ try {
46
+ const glob = new Bun.Glob("**/*.ts");
47
+ for await (const file of glob.scan({ cwd: resolvedDir, absolute: !0 }))
48
+ if (!isSkippedFile(file))
49
+ files.push(file);
50
+ } catch {
51
+ return [];
52
+ }
53
+ files.sort();
54
+ const transpiler = getSharedTranspiler({ loader: "ts", target: "browser", define: getPublicEnvDefine() }), modules = [];
55
+ for (const file of files)
56
+ try {
57
+ const code = await Bun.file(file).text(), names = transpiler.scan(code).exports.filter((name) => name !== "default");
58
+ if (names.length > 0)
59
+ modules.push({ file, names });
60
+ } catch {}
61
+ return modules;
62
+ }
63
+ function mentions(text, name) {
64
+ return new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(text);
65
+ }
66
+ function selectReachable(modules, codeByFile, pageSource) {
67
+ const fileForName = new Map;
68
+ for (const { file, names } of modules)
69
+ for (const name of names)
70
+ if (!fileForName.has(name))
71
+ fileForName.set(name, file);
72
+ const filesMentionedIn = (text) => {
73
+ const found = [];
74
+ for (const [name, file] of fileForName)
75
+ if (mentions(text, name))
76
+ found.push(file);
77
+ return found;
78
+ }, selected = new Set;
79
+ let frontier = filesMentionedIn(pageSource);
80
+ while (frontier.length > 0) {
81
+ const next = [];
82
+ for (const file of frontier) {
83
+ if (selected.has(file))
84
+ continue;
85
+ selected.add(file);
86
+ for (const dependency of filesMentionedIn(codeByFile.get(file) ?? ""))
87
+ if (!selected.has(dependency))
88
+ next.push(dependency);
89
+ }
90
+ frontier = next;
91
+ }
92
+ return selected;
93
+ }
94
+ export async function getComposableScript(composablesDir, pageSource) {
41
95
  const resolvedDir = await resolveComposablesDir(composablesDir);
42
96
  if (!resolvedDir)
43
97
  return null;
@@ -53,18 +107,33 @@ export async function getComposableScript(composablesDir) {
53
107
  writeSigned(_cachedComposableScripts, resolvedDir, "", "");
54
108
  return null;
55
109
  }
56
- const signature = sourceSignature(composableFiles), cached = readSigned(_cachedComposableScripts, resolvedDir, signature);
57
- if (cached !== void 0)
58
- return cached || null;
110
+ const signature = sourceSignature(composableFiles);
59
111
  if (composableFiles.length === 0) {
60
112
  writeSigned(_cachedComposableScripts, resolvedDir, signature, "");
61
113
  return null;
62
114
  }
63
115
  composableFiles.sort();
64
- const transpiler = getSharedTranspiler({ loader: "ts", target: "browser", define: getPublicEnvDefine() }), chunks = [], exportedNames = new Set, declaredNames = new Set;
116
+ const transpiler = getSharedTranspiler({ loader: "ts", target: "browser", define: getPublicEnvDefine() }), codeByFile = new Map, modules = [];
65
117
  for (const file of composableFiles)
66
118
  try {
67
- let code = await Bun.file(file).text();
119
+ const code = await Bun.file(file).text();
120
+ codeByFile.set(file, code);
121
+ const names = transpiler.scan(code).exports.filter((name) => name !== "default");
122
+ if (names.length > 0)
123
+ modules.push({ file, names });
124
+ } catch {
125
+ codeByFile.set(file, "");
126
+ }
127
+ const selected = pageSource === void 0 ? new Set(composableFiles) : selectReachable(modules, codeByFile, pageSource);
128
+ if (selected.size === 0)
129
+ return null;
130
+ const includedFiles = composableFiles.filter((file) => selected.has(file)), cacheKey = `${resolvedDir}\x00${includedFiles.join("\x00")}`, cached = readSigned(_cachedComposableScripts, cacheKey, signature);
131
+ if (cached !== void 0)
132
+ return cached || null;
133
+ const chunks = [], exportedNames = new Set, declaredNames = new Set;
134
+ for (const file of includedFiles)
135
+ try {
136
+ let code = codeByFile.get(file) ?? await Bun.file(file).text();
68
137
  const composableName = path.basename(file, ".ts");
69
138
  for (const match of code.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))
70
139
  if (match[1])
@@ -84,7 +153,7 @@ ${code.trim()}`);
84
153
  console.warn(`[stx] Failed to load composable ${file}:`, e);
85
154
  }
86
155
  if (chunks.length === 0 || exportedNames.size === 0) {
87
- writeSigned(_cachedComposableScripts, resolvedDir, signature, "");
156
+ writeSigned(_cachedComposableScripts, cacheKey, signature, "");
88
157
  return null;
89
158
  }
90
159
  const assignments = [...exportedNames].map((name) => ` try { __c[${JSON.stringify(name)}] = ${name}; } catch (e) {}`).join(`
@@ -112,7 +181,7 @@ ${assignments}
112
181
  window[__n] = __c[__n];
113
182
  }
114
183
  })();`;
115
- writeSigned(_cachedComposableScripts, resolvedDir, signature, code);
184
+ writeSigned(_cachedComposableScripts, cacheKey, signature, code);
116
185
  return code;
117
186
  }
118
187
  export function clearComposableCache() {
@@ -18,9 +18,14 @@ export declare function removeCookie(name: string, options?: Pick<CookieOptions,
18
18
  /**
19
19
  * Create a reactive Signal bound to a cookie. Mirrors `useLocalStorage`'s
20
20
  * shape: read with `c()`, write with `c.set(v)`. Setting to `''` deletes the
21
- * cookie. The signal is one-way (writes propagate to document.cookie via an
22
- * `effect`); cookies don't fire a 'storage' event, so cross-tab updates
23
- * aren't auto-reflected.
21
+ * cookie. The signal is one-way (writes propagate to document.cookie on `set`);
22
+ * cookies don't fire a 'storage' event, so cross-tab updates aren't
23
+ * auto-reflected.
24
+ *
25
+ * Construction is a pure read: declaring a cookie writes nothing, so a caller
26
+ * that only wants the value cannot disturb the attributes its owner set. A
27
+ * `defaultValue` therefore does not reach `document.cookie` until something
28
+ * writes (#1933).
24
29
  *
25
30
  * @example
26
31
  * ```ts