@skathi-native/cli 0.1.0-beta.4 → 0.2.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 (46) hide show
  1. package/aot-inputs.ts +21 -2
  2. package/build.ts +241 -60
  3. package/check/bundle.ts +265 -0
  4. package/check/graph.ts +3 -1
  5. package/check/index.ts +10 -1
  6. package/check/program.ts +26 -6
  7. package/cli/create.ts +29 -7
  8. package/devtools/commands.ts +25 -0
  9. package/effects/compile.ts +160 -31
  10. package/effects/sk.slang +353 -29
  11. package/package.json +7 -4
  12. package/prod.ts +40 -7
  13. package/svelte.ts +76 -0
  14. package/templates/icon.png +0 -0
  15. package/templates/showcase/assets/textures/golden.png +0 -0
  16. package/templates/showcase/assets/textures/hammered.png +0 -0
  17. package/templates/showcase/assets/textures/noir.png +0 -0
  18. package/templates/showcase/assets/textures/reeded.png +0 -0
  19. package/templates/showcase/assets/textures/teal-orange.png +0 -0
  20. package/templates/showcase/shaders/dissolve.slang +40 -0
  21. package/templates/showcase/shaders/fireflies.slang +58 -0
  22. package/templates/showcase/shaders/glass.slang +31 -0
  23. package/templates/showcase/shaders/grade.slang +34 -0
  24. package/templates/showcase/shaders/halftone.slang +42 -0
  25. package/templates/showcase/shaders/lens.slang +51 -0
  26. package/templates/showcase/shaders/nebula.slang +57 -0
  27. package/templates/showcase/shaders/orbit.slang +52 -0
  28. package/templates/showcase/shaders/pond.slang +76 -0
  29. package/templates/showcase/shaders/ripples.slang +71 -0
  30. package/templates/showcase/shaders/shatter.slang +116 -0
  31. package/templates/showcase/shaders/snow.slang +57 -0
  32. package/templates/showcase/shaders/spotlight.slang +52 -0
  33. package/templates/showcase/src/App.vue +11 -16
  34. package/templates/showcase/src/components/FullWindow.vue +77 -0
  35. package/templates/showcase/src/components/Page.vue +2 -0
  36. package/templates/showcase/src/fullwindow.ts +36 -0
  37. package/templates/showcase/src/icons.ts +2 -0
  38. package/templates/showcase/src/pages/GraphicsPage.vue +122 -0
  39. package/templates/showcase/src/pages/MotionPage.vue +71 -1
  40. package/templates/showcase/src/pages/ShadersPage.vue +443 -0
  41. package/templates/showcase/src/router.ts +32 -1
  42. package/templates/svelte/.vscode/settings.json +3 -0
  43. package/templates/svelte/assets/hello.txt +1 -0
  44. package/templates/svelte/src/App.svelte +142 -0
  45. package/templates/svelte/src/main.ts +4 -0
  46. package/vitecompat.ts +2 -0
package/aot-inputs.ts CHANGED
@@ -6,7 +6,8 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
6
  import type ts from "typescript";
7
7
 
8
8
  type TypeScript = typeof ts;
9
- type InputKind = "source" | "vue" | "vue-module" | "vue-script" | "transformed-module" | "config";
9
+ type InputKind =
10
+ "source" | "vue" | "vue-module" | "vue-script" | "svelte" | "svelte-module" | "transformed-module" | "config";
10
11
  interface Input {
11
12
  path: string;
12
13
  kind: InputKind;
@@ -116,6 +117,21 @@ export class AotInputs {
116
117
  }
117
118
  }
118
119
 
120
+ /**
121
+ * A Svelte component, or a `.svelte.ts`/`.svelte.js` rune module, and the JS the compiler made of it. The
122
+ * compiler keeps no types, so a rune module's typed source stays the program's view of it.
123
+ */
124
+ svelte(path: string, original: string, compiled: string): void {
125
+ this.add(path, compiled, "svelte-module", "js");
126
+ if (/\.svelte$/i.test(path)) {
127
+ this.add(path, original, "svelte");
128
+ this.addVirtual(`${resolve(path)}.js`, compiled);
129
+ return;
130
+ }
131
+ this.add(path, original, "source");
132
+ this.modules.set(this.key(path), { path: resolve(path), text: original });
133
+ }
134
+
119
135
  private collectTypes(): { version: string; config: string | null; diagnostics: { code: number; message: string }[] } {
120
136
  const { typescript, appRoot, entry, aliases, declarations = [] } = this.options;
121
137
  const read = (path: string): string | undefined => {
@@ -178,6 +194,9 @@ export class AotInputs {
178
194
  (specifier.endsWith(".vue")
179
195
  ? typescript.resolveModuleName(`${specifier}.ts`, importer, options, host).resolvedModule
180
196
  : undefined) ??
197
+ (specifier.endsWith(".svelte")
198
+ ? typescript.resolveModuleName(`${specifier}.js`, importer, options, host).resolvedModule
199
+ : undefined) ??
181
200
  (alias ? typescript.resolveModuleName(specifier, alias, options, host).resolvedModule : undefined) ??
182
201
  (alias
183
202
  ? {
@@ -282,7 +301,7 @@ export class AotInputs {
282
301
  limitations: [
283
302
  "Source archive, not a native AOT image; no host ABI or builtin-effect descriptors are inferred from declarations.",
284
303
  "Original paths are app-root-relative or use a named source-root anchor; blob names are content hashes. An AOT frontend needs a resolver that maps these paths to blobs.",
285
- "Vue modules and TS/JS source rewrites are retained before Bun transpilation. Bun-generated asset/query/HTML modules, CSS installation and module linking still require a frontend adapter.",
304
+ "Vue and Svelte modules and TS/JS source rewrites are retained before Bun transpilation. Bun-generated asset/query/HTML modules, CSS installation and module linking still require a frontend adapter.",
286
305
  "TypeScript file-module resolution is recorded in addition to Bun's runtime graph; unresolvedImports also includes ambient module names that have no file mapping. A frontend adapter must handle them. This archive does not assert type-checking or AOT compatibility.",
287
306
  ],
288
307
  };
package/build.ts CHANGED
@@ -8,7 +8,8 @@
8
8
  //
9
9
  // Module ids are workspace-relative POSIX paths. Change kind: script or <style> scoped/module/lang
10
10
  // shape changed -> "reload"; template -> "rerender" (state survives); <style> text only ->
11
- // "css-only"; non-.vue source -> "reload".
11
+ // "css-only"; non-.vue source -> "reload"; an npm module already loaded that now belongs to a
12
+ // rebuilt package group -> "restart".
12
13
  // hoistStatic and inlineTemplate are forced off: the host has no insertStaticContent, and an inline
13
14
  // render inside setup() could not be swapped without losing state.
14
15
  // npm dependencies are one shared module per package entry (inlining per importer breaks
@@ -53,6 +54,7 @@ import {
53
54
  viteShapesPlugin,
54
55
  } from "./vitecompat";
55
56
  import { colorEnabled, paint } from "./cli/term";
57
+ import { SVELTE_SOURCE, compileSvelte } from "./svelte";
56
58
 
57
59
  const C = paint(colorEnabled(process.stdout));
58
60
  const styled = (rest: (text: string) => string) => (text: string) => {
@@ -75,7 +77,7 @@ const APP_SRC_DIR = dirname(ENTRY_ABS);
75
77
  const DIST = resolve(positional[1] ?? join(PKG_DIR, "dist"));
76
78
  const MODULES_DIR = join(DIST, "modules");
77
79
 
78
- const SOURCE_EXT = /\.(vue|js|ts|mjs)$/;
80
+ const SOURCE_EXT = /\.(vue|svelte|js|ts|mjs)$/;
79
81
 
80
82
  // The window block of sk.config.json is copied verbatim into the manifest: the host reads it
81
83
  // before the window opens, the only time creation-time options can be set without a flash.
@@ -322,7 +324,8 @@ const DEFINES: Record<string, string> = {
322
324
  // by Bun while parsing.
323
325
  "import.meta.env.SK": "true",
324
326
  "import.meta.env": JSON.stringify(VITE_ENV_DEV),
325
- // Library code guards on it; undefined means "not a dev server" (our HMR rides __VUE_HMR_RUNTIME__).
327
+ // Undefined in the vendor bundle and npm modules (library code guards on it); an app module gets its own
328
+ // (`MODULE_DEFINES`).
326
329
  "import.meta.hot": "undefined",
327
330
  "import.meta.url": '"sk://module"',
328
331
  // Leftover import.meta.glob calls are defined to a findable name so buildModule can fail clearly.
@@ -331,6 +334,9 @@ const DEFINES: Record<string, string> = {
331
334
  ...APP_DEFINES.defines,
332
335
  };
333
336
 
337
+ // An app module's `import.meta.hot` is the loader's per-module HMR context.
338
+ const MODULE_DEFINES: Record<string, string> = { ...DEFINES, "import.meta.hot": "module.hot" };
339
+
334
340
  function writeAtomic(path: string, text: string) {
335
341
  const tmp = path + ".tmp";
336
342
  writeFileSync(tmp, text);
@@ -342,10 +348,6 @@ function ensureDirs() {
342
348
  }
343
349
 
344
350
  async function buildVendor() {
345
- for (const [name, dep] of FRAMEWORK) {
346
- if (dep.warning) devAdvise(dep.warning);
347
- say(`${stamp()} ${name} ${dep.version ?? "unknown"}: the ${dep.from === "app" ? "app's" : "runtime's"} copy`);
348
- }
349
351
  const result = await Bun.build({
350
352
  entrypoints: [LOADER_ENTRY],
351
353
  format: "iife",
@@ -353,15 +355,10 @@ async function buildVendor() {
353
355
  define: DEFINES,
354
356
  plugins: [
355
357
  {
356
- // vue-router and others import from "vue": that must be our runtime. Exact-match filter only:
357
- // bun 1.4 crashes on catch-all onResolve filters.
358
+ // "vue" is our runtime. Exact-match filter only: bun 1.4 crashes on catch-all onResolve filters.
358
359
  name: "vendor-vue-alias",
359
360
  setup(b: Bun.PluginBuilder) {
360
361
  b.onResolve({ filter: /^vue$/ }, () => ({ path: RUNTIME_ENTRY }));
361
- // The app owns these packages in dev and prod; mixing majors breaks store/router identity.
362
- b.onResolve({ filter: /^(vue-router|pinia)$/ }, (args: Bun.OnResolveArgs) => ({
363
- path: FRAMEWORK.get(args.path)!.path,
364
- }));
365
362
  },
366
363
  },
367
364
  ],
@@ -543,6 +540,16 @@ const appModulePlugin = {
543
540
  const code = transformSource(out.contents, args.path, DEV_SHAPES);
544
541
  return code === null ? out : { ...out, contents: code };
545
542
  });
543
+ build.onLoad({ filter: SVELTE_SOURCE }, async (args: Bun.OnLoadArgs) => {
544
+ const id = toId(args.path);
545
+ const out = await compileSvelte(APP_ROOT, args.path, await Bun.file(args.path).text(), {
546
+ dev: true,
547
+ filename: id,
548
+ });
549
+ for (const w of out.warnings) devAdvise(w);
550
+ capturedCss = out.css ? pruneVendorPrefixes(await viteCss(out.css, args.path, `${id} <style>`)) : null;
551
+ return { contents: transformSource(out.js, args.path, DEV_SHAPES) ?? out.js, loader: "js" as const };
552
+ });
546
553
  },
547
554
  };
548
555
 
@@ -552,7 +559,20 @@ const appModulePlugin = {
552
559
 
553
560
  const REQUIRE_RE = /\brequire\(\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*\)/g;
554
561
 
555
- const CANDIDATE_EXTS = ["", ".js", ".ts", ".mjs", ".vue", "/index.js", "/index.ts", "/index.vue"];
562
+ const CANDIDATE_EXTS = [
563
+ "",
564
+ ".js",
565
+ ".ts",
566
+ ".mjs",
567
+ ".vue",
568
+ ".svelte",
569
+ ".svelte.ts",
570
+ ".svelte.js",
571
+ "/index.js",
572
+ "/index.ts",
573
+ "/index.vue",
574
+ "/index.svelte",
575
+ ];
556
576
 
557
577
  function normalizeId(path: string): string {
558
578
  const out: string[] = [];
@@ -588,7 +608,10 @@ function depsOf(id: string, body: string, ids: Set<string>, skip: Set<string>):
588
608
  if (spec === null || spec.charCodeAt(0) !== 46 /* . */) continue; // bare -> vendor
589
609
  if (skip.has(spec)) continue; // a stylesheet: its own synthetic module
590
610
  const base = normalizeId((dir ? dir + "/" : "") + spec);
591
- const hit = CANDIDATE_EXTS.map((ext) => base + ext).find((cand) => ids.has(cand));
611
+ // TypeScript's ESM spelling: `./x.js` names `x.ts`.
612
+ const hit = CANDIDATE_EXTS.map((ext) => base + ext)
613
+ .concat(base.endsWith(".js") ? [base.slice(0, -3) + ".ts"] : [])
614
+ .find((cand) => ids.has(cand));
592
615
  if (!hit) {
593
616
  warn(`${stamp()} ${id}: import ${J(spec)} resolves to no built module — ` + `require() will throw at runtime`);
594
617
  continue;
@@ -606,7 +629,7 @@ function bareOf(body: string, skip: Set<string>): string[] {
606
629
  if (spec === null) continue;
607
630
  const c = spec.charCodeAt(0);
608
631
  if (c === 46 /* . */ || c === 47 /* / */) continue; // relative/absolute -> graph
609
- if (isPreseeded(spec) || found.includes(spec) || skip.has(spec)) continue;
632
+ if ((isPreseeded(spec) && !FRAMEWORK.has(spec)) || found.includes(spec) || skip.has(spec)) continue;
610
633
  found.push(spec);
611
634
  }
612
635
  return found;
@@ -733,7 +756,7 @@ async function buildModule(absPath: string, ids: Set<string>) {
733
756
  target: "node",
734
757
  external: ["*"],
735
758
  plugins: [devShapesPlugin, devImports, appModulePlugin],
736
- define: DEFINES,
759
+ define: MODULE_DEFINES,
737
760
  });
738
761
  } finally {
739
762
  inlinedNow = null;
@@ -780,11 +803,18 @@ async function buildModule(absPath: string, ids: Set<string>) {
780
803
  // npm modules: one per package ENTRY, keyed on the resolved directory (not the name), so every
781
804
  // importer of a directory shares it and a nested copy at another version stays separate. The id
782
805
  // is the specifier when the app resolves it to that directory, else `<spec>~<hash of the directory>`.
806
+ // Two or more entries of one package (`svelte`, `svelte/internal/client`) share module state through
807
+ // relative imports: they are bundled together into one group module, and each entry's module reads
808
+ // its namespace from it.
783
809
 
784
810
  const npmBuilt = new Map<string, number>();
785
811
  const npmFailed = new Set<string>();
786
- const npmEntries = new Map<string, { spec: string; from: string }>();
812
+ const npmEntries = new Map<string, { spec: string; from: string; root: string | null }>();
787
813
  const npmBare = new Map<string, string[]>();
814
+ /** Package root -> its group module's id and members. */
815
+ const npmGroups = new Map<string, { id: string; members: string[] }>();
816
+ /** npm id -> the group module it was last built as a member of, "" when built alone. */
817
+ const npmShape = new Map<string, string>();
788
818
 
789
819
  function splitSpec(spec: string): [string, string] {
790
820
  const parts = spec.split("/");
@@ -832,20 +862,34 @@ function npmIdOf(spec: string, abs: string, from: string): string {
832
862
  appKeys.set(spec, appKey);
833
863
  }
834
864
  const id = key === appKey ? spec : `${spec}~${Bun.hash(key).toString(16).slice(0, 8)}`;
835
- if (!npmEntries.has(id)) npmEntries.set(id, { spec, from: id === spec ? APP_ROOT : from });
865
+ if (!npmEntries.has(id)) {
866
+ npmEntries.set(id, { spec, from: id === spec ? APP_ROOT : from, root: packageRootOf(abs, splitSpec(spec)[0]) });
867
+ }
836
868
  return id;
837
869
  }
838
870
 
839
- function npmSharePlugin(selfKey: string, found: Set<string>) {
871
+ /** A file of the package at `root` itself, not of one installed beneath it. */
872
+ function inPackage(abs: string, root: string): boolean {
873
+ const rel = relative(root, abs);
874
+ return !!rel && !rel.startsWith("..") && !isAbsolute(rel) && !rel.split(sep).includes("node_modules");
875
+ }
876
+
877
+ function npmSharePlugin(selfKey: string, selfRoot: string | null, found: Set<string>) {
840
878
  return {
841
879
  name: "sk-dev-npm-share",
842
880
  setup(build: Bun.PluginBuilder) {
843
881
  build.onResolve({ filter: /^(?!node:)[^./\\]/ }, (args: Bun.OnResolveArgs) => {
844
- if (args.kind === "entry-point-build" || isAbsolute(args.path) || isPreseeded(args.path)) return undefined;
882
+ if (args.kind === "entry-point-build" || isAbsolute(args.path)) return undefined;
883
+ // Every importer lands on the one copy: the vendor bundle's, or the framework module built on demand.
884
+ if (isPreseeded(args.path)) {
885
+ if (FRAMEWORK.has(args.path)) found.add(args.path);
886
+ return { path: args.path, external: true };
887
+ }
845
888
  const from = importerDir(args, APP_ROOT);
846
889
  const abs = resolveImport(args.path, from);
847
890
  if (abs === null || !isAbsolute(abs) || /\.css$/i.test(abs) || LEAF_IMPORT.test(abs)) return undefined;
848
- if (npmKey(args.path, abs) === selfKey) return undefined;
891
+ // The package's own `#imports` and self-references are part of it, as its relative imports are.
892
+ if (npmKey(args.path, abs) === selfKey || (selfRoot && inPackage(abs, selfRoot))) return undefined;
849
893
  const id = npmIdOf(args.path, abs, from);
850
894
  found.add(id);
851
895
  return { path: id, external: true };
@@ -854,25 +898,60 @@ function npmSharePlugin(selfKey: string, found: Set<string>) {
854
898
  };
855
899
  }
856
900
 
901
+ function noteUnresolved(id: string, spec: string, from: string): void {
902
+ if (npmFailed.has(id)) return;
903
+ npmFailed.add(id);
904
+ const alias = !/^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(?:\/|$)/i.test(spec);
905
+ warn(
906
+ `${stamp()} cannot resolve ${J(spec)} from ${toId(from)} — ` +
907
+ `require(${J(id)}) will throw at runtime ` +
908
+ (alias
909
+ ? "(an import alias resolves through tsconfig.json compilerOptions.paths, as in sk build; " +
910
+ "a vite.config resolve.alias is not read)"
911
+ : "(is it installed?)"),
912
+ );
913
+ }
914
+
915
+ const npmHash = new Map<string, string>();
916
+
917
+ /** Writes an npm module script; true when its body differs from the last one written under this id. */
918
+ function writeNpmModule(id: string, what: string, body: string): boolean {
919
+ moduleDeps.set(id, []);
920
+ // Constant unless the package changes, so a rebuild never invalidates module-scope singletons.
921
+ const hash = Bun.hash(body).toString(16);
922
+ writeAtomic(
923
+ join(MODULES_DIR, encId(id)),
924
+ [
925
+ `// Skathi module: ${id} (${what})`,
926
+ `__SK__.setDeps && __SK__.setDeps(${J(id)}, []);`,
927
+ `__SK__.define(${J(id)}, function (require, module, exports) {`,
928
+ body,
929
+ `}, ${J(hash)});`,
930
+ ].join("\n"),
931
+ );
932
+ npmBuilt.set(id, body.length);
933
+ const changed = npmHash.get(id) !== hash;
934
+ npmHash.set(id, hash);
935
+ return changed;
936
+ }
937
+
857
938
  async function buildNpmModule(id: string): Promise<boolean> {
858
939
  const { spec, from } = npmEntries.get(id) ?? { spec: id, from: APP_ROOT };
859
- const candidates = await entryCandidates(spec, from);
940
+ // vue-router and pinia: the copy the app declares (else the runtime's), like the production bundle.
941
+ const framework = FRAMEWORK.get(id);
942
+ if (framework) {
943
+ if (framework.warning) devAdvise(framework.warning);
944
+ say(
945
+ `${stamp()} ${id} ${framework.version ?? "unknown"}: the ${framework.from === "app" ? "app's" : "runtime's"} copy`,
946
+ );
947
+ }
948
+ const candidates = framework ? [framework.path] : await entryCandidates(spec, from);
860
949
  if (!candidates.length) {
861
- if (!npmFailed.has(id)) {
862
- npmFailed.add(id);
863
- const alias = !/^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(?:\/|$)/i.test(spec);
864
- warn(
865
- `${stamp()} cannot resolve ${J(spec)} from ${toId(from)} — ` +
866
- `require(${J(id)}) will throw at runtime ` +
867
- (alias
868
- ? "(an import alias resolves through tsconfig.json compilerOptions.paths, as in sk build; " +
869
- "a vite.config resolve.alias is not read)"
870
- : "(is it installed?)"),
871
- );
872
- }
950
+ noteUnresolved(id, spec, from);
873
951
  return false;
874
952
  }
875
953
  const selfKey = npmKey(spec, candidates[0]!);
954
+ const selfRoot = packageRootOf(candidates[0]!, splitSpec(spec)[0]);
876
955
  const requires = new Set<string>();
877
956
  let result: Awaited<ReturnType<typeof Bun.build>> | null = null;
878
957
  let entry = candidates[0]!;
@@ -886,7 +965,7 @@ async function buildNpmModule(id: string): Promise<boolean> {
886
965
  // Pre-seeded ids plus every other package entry stay external. A dependency can ship raw .vue
887
966
  // source: without the SFC plugin Bun treats it as an asset and the import silently renders
888
967
  // nothing.
889
- plugins: [npmShapesPlugin, npmSharePlugin(selfKey, requires), vuePlugin],
968
+ plugins: [npmShapesPlugin, npmSharePlugin(selfKey, selfRoot, requires), vuePlugin],
890
969
  define: DEFINES,
891
970
  }).catch(() => null);
892
971
  if (result?.success) break;
@@ -898,24 +977,87 @@ async function buildNpmModule(id: string): Promise<boolean> {
898
977
  for (const log of result?.logs ?? []) console.error(log);
899
978
  throw new Error(`npm module build failed: ${id}`);
900
979
  }
901
- const body = tagModuleNamespaces(await result.outputs[0]!.text()).code;
902
- moduleDeps.set(id, []);
903
980
  npmBare.set(id, Array.from(requires).sort());
904
- writeAtomic(
905
- join(MODULES_DIR, encId(id)),
906
- [
907
- `// Skathi module: ${id} (npm dependency, bundled from ${toId(entry)})`,
908
- `__SK__.setDeps && __SK__.setDeps(${J(id)}, []);`,
909
- `__SK__.define(${J(id)}, function (require, module, exports) {`,
910
- body,
911
- // Constant unless the package changes, so a rebuild never invalidates module-scope singletons.
912
- `}, ${J(Bun.hash(body).toString(16))});`,
913
- ].join("\n"),
981
+ npmShape.set(id, "");
982
+ writeNpmModule(
983
+ id,
984
+ `npm dependency, bundled from ${toId(entry)}`,
985
+ tagModuleNamespaces(await result.outputs[0]!.text()).code,
914
986
  );
915
- npmBuilt.set(id, body.length);
916
987
  return true;
917
988
  }
918
989
 
990
+ const GROUP_ENTRY = "__sk_npm_group__.js";
991
+
992
+ /** Bundles the entries `members` of the package at `root` into one module: the members it built, and whether that module changed. */
993
+ async function buildNpmGroup(root: string, members: string[]): Promise<{ built: string[]; changed: boolean }> {
994
+ const lists: string[][] = [];
995
+ const built: string[] = [];
996
+ for (const id of members) {
997
+ const { spec, from } = npmEntries.get(id)!;
998
+ const candidates = await entryCandidates(spec, from);
999
+ if (!candidates.length) {
1000
+ noteUnresolved(id, spec, from);
1001
+ continue;
1002
+ }
1003
+ lists.push(candidates);
1004
+ built.push(id);
1005
+ }
1006
+ if (!built.length) return { built, changed: false };
1007
+ const gid = `${pkgNameAt.get(root) ?? toId(root)}~pkg~${Bun.hash(toId(root)).toString(16).slice(0, 8)}`;
1008
+ const probe = join(root, GROUP_ENTRY); // never written: the plugin answers for it
1009
+ const requires = new Set<string>();
1010
+ let result: Awaited<ReturnType<typeof Bun.build>> | null = null;
1011
+ const attempts = Math.max(...lists.map((l) => l.length));
1012
+ for (let i = 0; i < attempts; i++) {
1013
+ const source = lists.map((l, k) => `export * as e${k} from ${J(l[Math.min(i, l.length - 1)])};`).join("\n");
1014
+ requires.clear();
1015
+ result = await Bun.build({
1016
+ entrypoints: [probe],
1017
+ format: "cjs",
1018
+ target: "browser",
1019
+ plugins: [
1020
+ {
1021
+ name: "sk-npm-group-entry",
1022
+ setup(b: Bun.PluginBuilder) {
1023
+ b.onResolve({ filter: /__sk_npm_group__\.js$/ }, () => ({ path: probe }));
1024
+ b.onLoad({ filter: /__sk_npm_group__\.js$/ }, () => ({ contents: source, loader: "js" }));
1025
+ },
1026
+ },
1027
+ npmShapesPlugin,
1028
+ npmSharePlugin("", root, requires),
1029
+ vuePlugin,
1030
+ ],
1031
+ define: DEFINES,
1032
+ }).catch(() => null);
1033
+ if (result?.success) break;
1034
+ }
1035
+ if (!result?.success) {
1036
+ for (const log of result?.logs ?? []) console.error(log);
1037
+ throw new Error(`npm module build failed: ${built.join(", ")} (bundled together as ${gid})`);
1038
+ }
1039
+ npmBare.set(gid, Array.from(requires).sort());
1040
+ const changed = writeNpmModule(
1041
+ gid,
1042
+ `npm dependency, the entries ${built.join(", ")} of ${toId(root)}`,
1043
+ tagModuleNamespaces(await result.outputs[0]!.text()).code,
1044
+ );
1045
+ for (const [k, id] of built.entries()) {
1046
+ // An ES module's namespace is the module; a CommonJS entry's is its `module.exports`, as when built alone.
1047
+ writeNpmModule(
1048
+ id,
1049
+ `npm dependency, entry of ${gid}`,
1050
+ `var ns = require(${J(gid)}).e${k};\n` +
1051
+ 'module.exports = ns && ns[Symbol.toStringTag] === "Module" ? ' +
1052
+ 'Object.defineProperty(ns, "__esModule", { value: true }) : ns && ns.default;',
1053
+ );
1054
+ npmBare.set(id, [gid]);
1055
+ npmShape.set(id, gid);
1056
+ }
1057
+ npmGroups.set(root, { id: gid, members: built });
1058
+ return { built, changed };
1059
+ }
1060
+
919
1061
  const npmIds = () => Array.from(npmBuilt.keys()).sort();
920
1062
 
921
1063
  function wantedNpm(): Set<string> {
@@ -930,16 +1072,50 @@ function wantedNpm(): Set<string> {
930
1072
  return wanted;
931
1073
  }
932
1074
 
933
- async function syncNpmModules(): Promise<string[]> {
1075
+ /** `added`: npm modules new to the build; `regrouped`: ones already built that now belong to a new group module (a running app holds the old copy). */
1076
+ async function syncNpmModules(): Promise<{ added: string[]; regrouped: string[] }> {
934
1077
  const added: string[] = [];
1078
+ const regrouped: string[] = [];
935
1079
  const tried = new Set<string>();
936
- for (;;) {
937
- const todo = Array.from(wantedNpm())
938
- .filter((id) => !npmBuilt.has(id) && !tried.has(id))
1080
+ for (let progress = true; progress;) {
1081
+ progress = false;
1082
+ const wanted = wantedNpm();
1083
+ const groupIds = new Set(Array.from(npmGroups.values(), (g) => g.id));
1084
+ const byRoot = new Map<string, string[]>();
1085
+ for (const id of wanted) {
1086
+ const root = groupIds.has(id) ? null : npmEntries.get(id)?.root;
1087
+ if (root) byRoot.set(root, [...(byRoot.get(root) ?? []), id]);
1088
+ }
1089
+ for (const [root, ids] of byRoot) {
1090
+ const known = npmGroups.get(root)?.members ?? [];
1091
+ // A member that went away leaves the group as it is; a new one rebuilds it.
1092
+ if (ids.length < 2 && !known.length) continue;
1093
+ if (ids.every((id) => known.includes(id) && npmBuilt.has(id))) continue;
1094
+ const members = Array.from(new Set([...known, ...ids])).sort();
1095
+ const key = members.join("\n");
1096
+ if (tried.has(key)) continue;
1097
+ tried.add(key);
1098
+ progress = true;
1099
+ const before = new Set(members.filter((id) => npmBuilt.has(id)));
1100
+ const shapeBefore = new Map(members.map((id) => [id, npmShape.get(id)]));
1101
+ const t0 = Date.now();
1102
+ const { built, changed } = await buildNpmGroup(root, members);
1103
+ for (const id of built) {
1104
+ if (!before.has(id)) added.push(id);
1105
+ else if (changed || shapeBefore.get(id) !== npmShape.get(id)) regrouped.push(id);
1106
+ }
1107
+ if (built.length) say(`${stamp()} npm ${built.join(", ")}: bundled together in ${Date.now() - t0} ms`);
1108
+ }
1109
+ const grouped = (id: string) => {
1110
+ const root = npmEntries.get(id)?.root;
1111
+ return !!root && npmGroups.has(root);
1112
+ };
1113
+ const todo = Array.from(wanted)
1114
+ .filter((id) => !npmBuilt.has(id) && !tried.has(id) && !groupIds.has(id) && !grouped(id))
939
1115
  .sort();
940
- if (!todo.length) break;
941
1116
  for (const id of todo) {
942
1117
  tried.add(id);
1118
+ progress = true;
943
1119
  const t0 = Date.now();
944
1120
  if (!(await buildNpmModule(id))) continue;
945
1121
  added.push(id);
@@ -952,12 +1128,14 @@ async function syncNpmModules(): Promise<string[]> {
952
1128
  if (wanted.has(id)) continue;
953
1129
  npmBuilt.delete(id);
954
1130
  npmBare.delete(id);
1131
+ npmShape.delete(id);
955
1132
  moduleDeps.delete(id);
956
1133
  try {
957
1134
  rmSync(join(MODULES_DIR, encId(id)));
958
1135
  } catch {}
959
1136
  }
960
- return added.filter((id) => npmBuilt.has(id));
1137
+ for (const [root, group] of npmGroups) if (!npmBuilt.has(group.id)) npmGroups.delete(root);
1138
+ return { added: added.filter((id) => npmBuilt.has(id)), regrouped: regrouped.filter((id) => npmBuilt.has(id)) };
961
1139
  }
962
1140
 
963
1141
  const TW_CONFIG = findConfig(appRootArg ? APP_ROOT : APP_SRC_DIR, ID_ROOT);
@@ -987,7 +1165,7 @@ async function buildTailwind(): Promise<boolean> {
987
1165
  }
988
1166
 
989
1167
  type Blocks = { src: string; script: string; template: string; styleShape: string; styleText: string };
990
- type Kind = "reload" | "rerender" | "css-only";
1168
+ type Kind = "reload" | "rerender" | "css-only" | "restart";
991
1169
 
992
1170
  const prevBlocks = new Map<string, Blocks>(); // abs path -> blocks
993
1171
 
@@ -1094,6 +1272,9 @@ async function fullBuild(reason: string) {
1094
1272
  npmBuilt.clear(); // force a rewrite: the module files may not exist yet
1095
1273
  npmBare.clear();
1096
1274
  npmEntries.clear();
1275
+ npmGroups.clear();
1276
+ npmShape.clear();
1277
+ npmHash.clear();
1097
1278
  appKeys.clear();
1098
1279
  pkgNameAt.clear();
1099
1280
  cssModules.clear();
@@ -1162,10 +1343,10 @@ async function incrementalBuild() {
1162
1343
  structural = true;
1163
1344
  }
1164
1345
 
1165
- for (const spec of await syncNpmModules()) {
1166
- changed.push({ id: spec, kind: "reload" });
1167
- structural = true;
1168
- }
1346
+ const npm = await syncNpmModules();
1347
+ for (const id of npm.added) changed.push({ id, kind: "reload" });
1348
+ for (const id of npm.regrouped) changed.push({ id, kind: "restart" });
1349
+ if (npm.added.length || npm.regrouped.length) structural = true;
1169
1350
 
1170
1351
  // Always re-run Tailwind: any content file can add a utility, and a stylesheet that went
1171
1352
  // through Tailwind is re-emitted on the same signal.