@slim-lang/core 1.2.15 → 1.2.17

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slim-lang/core",
3
- "version": "1.2.15",
3
+ "version": "1.2.17",
4
4
  "description": "Slim extends JavaScript with runtime types, structs, operators, and components, compiling to plain Javascript",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -1,6 +1,7 @@
1
1
  use http from "http"
2
2
  use * as fs from "fs"
3
3
  use * as nodePath from "path"
4
+ use { fileURLToPath } from "url"
4
5
  import process from 'node:process';
5
6
 
6
7
  export type ServerInstance = typeof Server;
@@ -30,6 +31,10 @@ class Server {
30
31
  this.clients = [];
31
32
  this.staticDirs = [];
32
33
  this.dev = false;
34
+ this.clientPrefix = "/@slim";
35
+ this.distDir = null;
36
+ this.httpServer = null;
37
+ this.shutdownInstalled = false;
33
38
 
34
39
  this.#loadConfig();
35
40
  }
@@ -37,10 +42,13 @@ class Server {
37
42
  #loadConfig() {
38
43
  let configDir = process.cwd();
39
44
  let raw: object = {};
45
+ let distName = "slim-dist";
40
46
 
41
47
  try {
42
48
  const slimConf = JSON.parse(fs.readFileSync(nodePath.join(process.cwd(), "slimconfig.json"), "utf8"));
43
49
  if (slimConf.main) configDir = nodePath.dirname(nodePath.resolve(slimConf.main));
50
+ if (slimConf.names && slimConf.names.dist) distName = slimConf.names.dist;
51
+ else if (slimConf.dist) distName = slimConf.dist;
44
52
  } catch (e) {}
45
53
 
46
54
  try {
@@ -60,6 +68,77 @@ class Server {
60
68
  });
61
69
 
62
70
  this.static(statics);
71
+
72
+ this.#mountClient(distName);
73
+ }
74
+
75
+ #mountClient(distName: string) {
76
+ const distDir = nodePath.resolve(process.cwd(), distName);
77
+
78
+ this.distDir = distDir;
79
+
80
+ if (fs.existsSync(distDir)) {
81
+ this.staticDirs.push({ prefix: this.clientPrefix, dir: distDir });
82
+ }
83
+ }
84
+
85
+ #resolveHydrate(entry: string) {
86
+ if (entry.startsWith("/") || entry.startsWith("http")) return entry;
87
+
88
+ const modulePath = entry.endsWith(".js") ? entry : `${entry}.js`;
89
+ return `${this.clientPrefix}/${modulePath}`;
90
+ }
91
+
92
+ #hydrateBootstrap(hydrate) {
93
+ // Component reference → derive its module + export name automatically.
94
+ // Every compiled component carries `__module__` (its own import.meta.url).
95
+ if (typeof hydrate === "function") {
96
+ const name = hydrate.name;
97
+ const moduleUrl = this.#clientUrlFor(hydrate.__module__);
98
+
99
+ if (empty name || empty moduleUrl) {
100
+ throw new Error("hydrate: component must be a named export compiled by Slim");
101
+ }
102
+
103
+ return this.#inlineBootstrap(moduleUrl, name);
104
+ }
105
+
106
+ // Absolute/external entry → load it as a module (custom bootstrap escape hatch).
107
+ if (hydrate.startsWith("/") || hydrate.startsWith("http")) {
108
+ return `<script type="module" src="${hydrate}"></script>`;
109
+ }
110
+
111
+ // "module/path:Export" → generate the client bootstrap inline. The component is
112
+ // already compiled (the server imports it), so no client entry file is needed.
113
+ if (hydrate.includes(":")) {
114
+ const parts = hydrate.split(":");
115
+ return this.#inlineBootstrap(`${this.clientPrefix}/${parts[0]}.js`, parts[1]);
116
+ }
117
+
118
+ // Bare module path → a hand-written client entry compiled to <path>.js.
119
+ return `<script type="module" src="${this.#resolveHydrate(hydrate)}"></script>`;
120
+ }
121
+
122
+ // Map a compiled module's import.meta.url to its served /@slim/... URL.
123
+ #clientUrlFor(moduleUrl: string) {
124
+ if (empty moduleUrl || empty this.distDir) return null;
125
+
126
+ const filePath = moduleUrl.startsWith("file:") ? fileURLToPath(moduleUrl) : moduleUrl;
127
+ const rel = nodePath.relative(this.distDir, filePath).split(nodePath.sep).join("/");
128
+
129
+ if (empty rel || rel.startsWith("..")) return null;
130
+
131
+ return `${this.clientPrefix}/${rel}`;
132
+ }
133
+
134
+ #inlineBootstrap(moduleUrl: string, name: string) {
135
+ const coreUrl = `${this.clientPrefix}/external/core.js`;
136
+
137
+ return `<script type="module">` +
138
+ `import "${coreUrl}";` +
139
+ `import { ${name} } from "${moduleUrl}";` +
140
+ `hydrate(() => ${name}(), document.getElementById("slim-root"));` +
141
+ `</script>`;
63
142
  }
64
143
 
65
144
  page(path: string, render: function, options?: object) {
@@ -146,9 +225,10 @@ class Server {
146
225
  const props = { dev: isDev, params, url: req.url }
147
226
  const rendered = await renderToStringAsync(() => render(props))
148
227
  const data = JSON.stringify(props).replace(/</g, "\\u003c")
228
+ const bootstrap = this.#hydrateBootstrap(options.hydrate)
149
229
  html = `<div id="slim-root">${rendered.html}</div>` + rendered.script +
150
230
  `<script>window.__slimProps = ${data}</script>` +
151
- `<script type="module" src="${options.hydrate}"></script>`
231
+ bootstrap
152
232
  } else {
153
233
  html = render({ dev: isDev, params, url: req.url })
154
234
  }
@@ -338,7 +418,7 @@ class Server {
338
418
  });
339
419
  });
340
420
 
341
- http.createServer((req, res) => {
421
+ this.httpServer = http.createServer((req, res) => {
342
422
  const url = req.url.split("?")[0];
343
423
 
344
424
  if (this.dev && url != "/__slim_reload__") {
@@ -425,9 +505,53 @@ class Server {
425
505
 
426
506
  res.writeHead(404);
427
507
  res.end("404");
428
- }).listen(this.port);
508
+ });
509
+
510
+ this.httpServer.on("error", (err) => {
511
+ if (err && err.code == "EADDRINUSE") {
512
+ error(`Port ${this.port} is already in use — another server (or a previous run) is still holding it.`);
513
+ process.exit(1);
514
+ }
515
+ throw err;
516
+ });
517
+
518
+ this.httpServer.listen(this.port, () => {
519
+ log(`http://localhost:${this.port}`);
520
+ });
521
+
522
+ this.#installShutdown();
523
+ }
524
+
525
+ // Close the HTTP server and release its port. Safe to call more than once.
526
+ stop() {
527
+ for (const res of this.clients) {
528
+ try { res.end(); } catch (e) {}
529
+ }
530
+ this.clients = [];
531
+
532
+ if (this.httpServer) {
533
+ // Drop keep-alive connections (e.g. the dev reload stream) so the
534
+ // socket is freed immediately instead of lingering.
535
+ if (typeof this.httpServer.closeAllConnections == "function") {
536
+ this.httpServer.closeAllConnections();
537
+ }
538
+ this.httpServer.close();
539
+ this.httpServer = null;
540
+ }
541
+ }
542
+
543
+ // Stop cleanly on Ctrl+C / termination signals so the port is freed on exit.
544
+ #installShutdown() {
545
+ if (this.shutdownInstalled) return;
546
+ this.shutdownInstalled = true;
547
+
548
+ const shutdown = () => {
549
+ this.stop();
550
+ process.exit(0);
551
+ };
429
552
 
430
- log(`http://localhost:${this.port}`);
553
+ process.on("SIGINT", shutdown);
554
+ process.on("SIGTERM", shutdown);
431
555
  }
432
556
  }
433
557
 
package/src/compile.js CHANGED
@@ -251,6 +251,13 @@ function main() {
251
251
  const entry = data.main.endsWith(".slim") ? data.main : `${data.main}.slim`
252
252
  setOutputPath(entry, path.resolve(distDirName(), `${data.main}.js`))
253
253
  compileFile(entry)
254
+
255
+ const clients = Array.isArray(data.clients) ? data.clients : []
256
+ for (const client of clients) {
257
+ if (typeof client !== "string" || !client.trim()) continue
258
+ compileFile(client.endsWith(".slim") ? client : `${client}.slim`)
259
+ }
260
+
254
261
  cleanDist()
255
262
  saveCache()
256
263
  if (reused > 0) debug(`Up to date: ${reused} of ${compiled.size} files`)
@@ -1,7 +1,7 @@
1
1
  import { SafeHtml, VNode, htmlToVdom, slimDocument, parseAttributeList } from "./helpers.js"
2
2
  import {
3
3
  Owner, Signal, __render_effect__, __computed__, __component__, batch, runWithOwner, untrack, onCleanup, changedInPlace,
4
- setServerRendering, setRootHook, setServerData, setHydrationData
4
+ setServerRendering, setRootHook, setServerData, setHydrationData, setServerStore, setClientStore
5
5
  } from "./reactive.js"
6
6
 
7
7
  const SVG_NS = "http://www.w3.org/2000/svg"
@@ -623,24 +623,36 @@ export function renderToString(render) {
623
623
 
624
624
  export async function renderToStringAsync(render, { passes = 5 } = {}) {
625
625
  const data = { results: [], pending: [], index: 0 }
626
- for (let pass = 1; ; pass++) {
627
- data.index = 0
628
- data.pending = []
629
- setServerData(data)
630
- let html
631
- try {
632
- html = renderToString(render)
633
- } finally {
634
- setServerData(null)
635
- }
636
- if (data.pending.length === 0 || pass === passes) {
637
- const sent = data.results.map(result => result && (result.error !== undefined
638
- ? { error: String(result.error?.message ?? result.error) }
639
- : { value: result.value }))
640
- const json = JSON.stringify(sent).replace(/</g, "\\u003c")
641
- return { html, data: sent, script: `<script>window.__slimData = ${json}</script>` }
626
+ const store = {}
627
+ setServerStore(store)
628
+ try {
629
+ for (let pass = 1; ; pass++) {
630
+ data.index = 0
631
+ data.pending = []
632
+ setServerData(data)
633
+ let html
634
+ try {
635
+ html = renderToString(render)
636
+ } finally {
637
+ setServerData(null)
638
+ }
639
+ if (data.pending.length === 0 || pass === passes) {
640
+ const sent = data.results.map(result => result && (result.error !== undefined
641
+ ? { error: String(result.error?.message ?? result.error) }
642
+ : { value: result.value }))
643
+ const json = JSON.stringify(sent).replace(/</g, "\\u003c")
644
+ const storeJson = JSON.stringify(store).replace(/</g, "\\u003c")
645
+ return {
646
+ html,
647
+ data: sent,
648
+ store,
649
+ script: `<script>window.__slimData = ${json};window.__slimStore = ${storeJson}</script>`
650
+ }
651
+ }
652
+ await Promise.all(data.pending)
642
653
  }
643
- await Promise.all(data.pending)
654
+ } finally {
655
+ setServerStore(null)
644
656
  }
645
657
  }
646
658
 
@@ -648,6 +660,9 @@ export function hydrate(render, container, data = globalThis.__slimData) {
648
660
  const previous = cursor
649
661
  cursor = { nodes: [...container.childNodes], index: 0 }
650
662
  setHydrationData(Array.isArray(data) ? { values: data, index: 0 } : null)
663
+ if (globalThis.__slimStore && typeof globalThis.__slimStore === "object") {
664
+ setClientStore(globalThis.__slimStore)
665
+ }
651
666
  try {
652
667
  return render()
653
668
  } finally {
@@ -19,6 +19,8 @@ export function setServerRendering(on) {
19
19
 
20
20
  let serverData = null
21
21
  let hydrationData = null
22
+ let serverStore = null
23
+ let clientStore = null
22
24
 
23
25
  export function setServerData(data) {
24
26
  serverData = data
@@ -28,6 +30,24 @@ export function setHydrationData(data) {
28
30
  hydrationData = data
29
31
  }
30
32
 
33
+ export function setServerStore(store) {
34
+ serverStore = store
35
+ }
36
+
37
+ export function setClientStore(store) {
38
+ clientStore = store
39
+ }
40
+
41
+ export function provideData(key, compute) {
42
+ if (clientStore && key in clientStore) return clientStore[key]
43
+ if (serverStore && key in serverStore) return serverStore[key]
44
+
45
+ const value = typeof compute === "function" ? compute() : compute
46
+
47
+ if (serverStore) serverStore[key] = value
48
+ return value
49
+ }
50
+
31
51
  export function setRootHook(fn) {
32
52
  rootHook = fn
33
53
  }
@@ -596,6 +616,6 @@ export function __defaults__(props, defaults) {
596
616
  }
597
617
 
598
618
  export const REACTIVE_GLOBALS = {
599
- effect, watch, untrack, batch, onCleanup, resource, createContext, provide, inject, catchError,
619
+ effect, watch, untrack, batch, onCleanup, resource, provideData, createContext, provide, inject, catchError,
600
620
  __signal__, __computed__, __mut__, __mut_deep__, __is__, __render_effect__, __component__, __defaults__, __live__
601
621
  }
package/src/suggest.js CHANGED
@@ -42,7 +42,7 @@ export const KNOWN_GLOBALS = new Set([
42
42
  "log", "warn", "error", "info", "debug", "type", "Component", "Type", "Struct", "onError",
43
43
  "test", "describe", "assert", "assertEqual", "PI", "raw", "escapeHtml", "htmlToVdom",
44
44
  "StructError", "StructPassedError", "StructExpectError", "ArgumentDeclarationTypeError",
45
- "onMount", "onConnect", "onUnmount", "effect", "watch", "untrack", "batch", "onCleanup", "resource", "renderToString", "renderToStringAsync", "hydrate", "createContext", "provide", "inject", "catchError", "createForm", "Router", "Link", "Portal", "navigate", "route", "matchRoute",
45
+ "onMount", "onConnect", "onUnmount", "effect", "watch", "untrack", "batch", "onCleanup", "resource", "provideData", "renderToString", "renderToStringAsync", "hydrate", "createContext", "provide", "inject", "catchError", "createForm", "Router", "Link", "Portal", "navigate", "route", "matchRoute",
46
46
  "window", "document", "navigator", "location", "history", "screen", "localStorage", "sessionStorage",
47
47
  "indexedDB", "alert", "confirm", "prompt", "event", "self", "top", "parent", "frames", "customElements",
48
48
  "requestAnimationFrame", "cancelAnimationFrame", "requestIdleCallback", "cancelIdleCallback",
@@ -567,6 +567,7 @@ function buildComponent(node, lowering) {
567
567
  return new Function(${JSON.stringify(bindingCode)}, ${JSON.stringify(bodyCode)})(__props__);
568
568
  };
569
569
  ${name}.__component__ = true;
570
+ ${name}.__module__ = import.meta.url;
570
571
  return ${name};
571
572
  })()`)
572
573
  return fill(statement, { __SLIM_GUARD__: guard }).expression
@@ -579,6 +580,7 @@ function buildComponent(node, lowering) {
579
580
  const [statement] = parseTemplate(`(() => {
580
581
  const ${name} = (__props__ = {}) => ${name}.__render__(__props__);
581
582
  ${name}.__component__ = true;
583
+ ${name}.__module__ = import.meta.url;
582
584
  ${name}.tag = ${tag};
583
585
  ${name}.__render__ = (__SLIM_PARAM__ = {}, __host__ = null) => __component__(() => {
584
586
  const s = {};
@@ -617,6 +619,7 @@ function buildComponent(node, lowering) {
617
619
  return __el__;
618
620
  });
619
621
  ${name}.__component__ = true;
622
+ ${name}.__module__ = import.meta.url;
620
623
  return ${name};
621
624
  })()`)
622
625