@ternkit/tern 1.4.0 → 1.5.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.
package/dist/index.d.ts CHANGED
@@ -29,4 +29,4 @@ export type { MessageKey } from './runtime/i18n.svelte.js';
29
29
  export interface Messages {
30
30
  }
31
31
  /** The version of the Tern client runtime. */
32
- export declare const VERSION = "1.4.0";
32
+ export declare const VERSION = "1.5.0";
package/dist/index.js CHANGED
@@ -17,4 +17,4 @@ export { stream, socket, EventStreamState, SocketState } from './runtime/realtim
17
17
  export { default as Image } from './image/Image.svelte';
18
18
  export { t, i18n, setLocale } from './runtime/i18n.svelte.js';
19
19
  /** The version of the Tern client runtime. */
20
- export const VERSION = '1.4.0';
20
+ export const VERSION = '1.5.0';
@@ -17,7 +17,11 @@ export declare class DeferredScope {
17
17
  /** Rejects every value still pending, e.g. when the stream ends early. */
18
18
  close(reason: string): void;
19
19
  }
20
- /** Replaces deferred placeholders in data with promises from scope. */
20
+ /**
21
+ * Replaces deferred placeholders in data with promises from scope. The data
22
+ * must be fresh from JSON.parse: it is changed in place, which saves
23
+ * copying every page's data on every render.
24
+ */
21
25
  export declare function revive<T>(value: T, promise: (id: number) => Promise<unknown>): T;
22
26
  /**
23
27
  * Reads a response that holds one JSON payload line, optionally followed
@@ -32,21 +32,37 @@ export class DeferredScope {
32
32
  this.#pending.clear();
33
33
  }
34
34
  }
35
- /** Replaces deferred placeholders in data with promises from scope. */
35
+ /**
36
+ * Replaces deferred placeholders in data with promises from scope. The data
37
+ * must be fresh from JSON.parse: it is changed in place, which saves
38
+ * copying every page's data on every render.
39
+ */
36
40
  export function revive(value, promise) {
41
+ if (value === null || typeof value !== 'object')
42
+ return value;
37
43
  if (Array.isArray(value)) {
38
- return value.map((v) => revive(v, promise));
44
+ for (let i = 0; i < value.length; i++) {
45
+ const v = value[i];
46
+ if (v !== null && typeof v === 'object') {
47
+ const r = revive(v, promise);
48
+ if (r !== v)
49
+ value[i] = r;
50
+ }
51
+ }
52
+ return value;
53
+ }
54
+ const obj = value;
55
+ if (typeof obj.__tern_deferred === 'number' && Object.keys(obj).length === 1) {
56
+ return promise(obj.__tern_deferred);
39
57
  }
40
- if (value && typeof value === 'object') {
41
- const obj = value;
42
- const keys = Object.keys(obj);
43
- if (keys.length === 1 && keys[0] === '__tern_deferred' && typeof obj.__tern_deferred === 'number') {
44
- return promise(obj.__tern_deferred);
58
+ for (const k in obj) {
59
+ const v = obj[k];
60
+ if (v !== null && typeof v === 'object') {
61
+ const r = revive(v, promise);
62
+ // defineProperty, so a key named __proto__ stays a plain property.
63
+ if (r !== v)
64
+ Object.defineProperty(obj, k, { value: r, writable: true, enumerable: true, configurable: true });
45
65
  }
46
- const out = {};
47
- for (const k of keys)
48
- out[k] = revive(obj[k], promise);
49
- return out;
50
66
  }
51
67
  return value;
52
68
  }
@@ -2,6 +2,7 @@ import { svelte } from '@sveltejs/vite-plugin-svelte';
2
2
  import fs from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import path from 'node:path';
5
+ import { nativePlugin } from './native.js';
5
6
  import { goScriptPlugin, goScriptPreprocessor } from './goscript.js';
6
7
  import { imagePlugin } from './image.js';
7
8
  /** Packages whose browser build works in the server renderer and whose default build needs Node. */
@@ -218,7 +219,7 @@ export function tern(options = {}) {
218
219
  return user;
219
220
  }
220
221
  };
221
- return [browserBuildsPlugin, imagePlugin(), goScriptPlugin(() => root), ...svelte(svelteOptions), plugin];
222
+ return [browserBuildsPlugin, imagePlugin(), goScriptPlugin(() => root), ...svelte(svelteOptions), plugin, nativePlugin(() => root, SERVER_ENTRY)];
222
223
  }
223
224
  /** The $service-worker module: what this build produced, for caching. */
224
225
  function serviceWorkerModule(root, base) {
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'vite';
2
+ export declare const NATIVE_IR = ".tern/native/ir.json";
3
+ export declare function nativePlugin(getRoot: () => string, entry: string): Plugin;
@@ -0,0 +1,122 @@
1
+ import { parse } from 'acorn';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ export const NATIVE_IR = '.tern/native/ir.json';
5
+ function svelteVersion(root) {
6
+ try {
7
+ const pkg = path.join(path.dirname(require_resolve('svelte/package.json', root)));
8
+ return JSON.parse(fs.readFileSync(path.join(pkg, 'package.json'), 'utf8')).version;
9
+ }
10
+ catch {
11
+ return '';
12
+ }
13
+ }
14
+ function require_resolve(spec, root) {
15
+ // Find svelte's package.json from the app's node_modules, as Vite does.
16
+ let dir = root;
17
+ for (;;) {
18
+ const candidate = path.join(dir, 'node_modules', spec);
19
+ if (fs.existsSync(candidate))
20
+ return candidate;
21
+ const up = path.dirname(dir);
22
+ if (up === dir)
23
+ throw new Error(`cannot find ${spec}`);
24
+ dir = up;
25
+ }
26
+ }
27
+ export function nativePlugin(getRoot, entry) {
28
+ const modules = new Map();
29
+ let active = false;
30
+ let env = {};
31
+ let base = '/';
32
+ // Asset URLs are placeholders in a module (import.meta.ROLLDOWN_FILE_URL_…)
33
+ // until the bundle is written: their final URLs go in the IR.
34
+ const fileRefs = new Set();
35
+ const fileUrls = {};
36
+ const bundled = {};
37
+ const rel = (file) => path.relative(getRoot(), file).split(path.sep).join('/');
38
+ // Every module is recorded, Svelte's own runtime included: compiling its
39
+ // code, rather than rewriting it, keeps the output exactly Svelte's.
40
+ const native = (_file) => false;
41
+ return {
42
+ name: 'tern:native-ir',
43
+ enforce: 'post',
44
+ configResolved(config) {
45
+ active = !!config.build.ssr && process.env.TERN_NATIVE === '1';
46
+ env = JSON.parse(JSON.stringify({ ...config.env, SSR: true }));
47
+ base = config.base || '/';
48
+ },
49
+ async transform(code, id) {
50
+ if (!active || id.startsWith('\0'))
51
+ return null;
52
+ // Modules with a query, such as an asset's ?url, are recorded under
53
+ // their whole id; what isn't JavaScript fails to parse and is left out.
54
+ const file = id;
55
+ const query = id.includes('?');
56
+ if ((!query && !/\.(svelte|[cm]?[jt]s|[jt]sx|json)$/.test(file)) || native(file))
57
+ return null;
58
+ try {
59
+ const ast = parse(code, { ecmaVersion: 'latest', sourceType: 'module' });
60
+ const imports = {};
61
+ for (const node of ast.body) {
62
+ const source = node.type === 'ImportDeclaration' || node.type === 'ExportAllDeclaration' || (node.type === 'ExportNamedDeclaration' && node.source)
63
+ ? node.source.value
64
+ : null;
65
+ if (source === null || source in imports)
66
+ continue;
67
+ const resolved = await this.resolve(source, id, { ssr: true });
68
+ const target = resolved && !resolved.external && !resolved.id.startsWith('\0') ? resolved.id : null;
69
+ imports[source] = target && !native(target) ? rel(target) : null;
70
+ }
71
+ modules.set(file, { id: rel(file), imports, ast, code });
72
+ for (const m of code.matchAll(/import\.meta\.((?:ROLLDOWN|ROLLUP|VITE)_FILE_URL_([\w$]+))/g))
73
+ fileRefs.add(m[1]);
74
+ }
75
+ catch {
76
+ // Not JavaScript we can read: the module stays unrecorded, so
77
+ // whatever imports it renders with the JavaScript engine.
78
+ }
79
+ return null;
80
+ },
81
+ generateBundle(_opts, bundle) {
82
+ if (!active)
83
+ return;
84
+ // What the bundler kept code of: modules it tree-shook away aren't
85
+ // compiled.
86
+ for (const out of Object.values(bundle)) {
87
+ if (out.type !== 'chunk')
88
+ continue;
89
+ for (const [id, m] of Object.entries(out.modules))
90
+ if (m.renderedLength > 0)
91
+ bundled[rel(id)] = true;
92
+ }
93
+ for (const ref of fileRefs) {
94
+ try {
95
+ fileUrls[ref] = path.posix.join(base, this.getFileName(ref.replace(/^(?:ROLLDOWN|ROLLUP|VITE)_FILE_URL_/, '')));
96
+ }
97
+ catch {
98
+ // Not a file of this build: the module falls back.
99
+ }
100
+ }
101
+ },
102
+ closeBundle() {
103
+ if (!active)
104
+ return;
105
+ const root = getRoot();
106
+ const out = path.join(root, NATIVE_IR);
107
+ fs.mkdirSync(path.dirname(out), { recursive: true });
108
+ const ir = { version: 1, svelte: svelteVersion(root), entry, env, fileUrls, bundled, modules: [...modules.values()] };
109
+ try {
110
+ // BigInt literals keep their digits in the node's bigint field;
111
+ // their value, which JSON can't hold, is left out.
112
+ fs.writeFileSync(out, JSON.stringify(ir, (_k, v) => (typeof v === 'bigint' ? null : v)));
113
+ }
114
+ catch (err) {
115
+ // Native rendering is an optimisation: without the IR, tern build
116
+ // skips it and pages render with the JavaScript engine.
117
+ fs.rmSync(out, { force: true });
118
+ this.warn(`native rendering skipped: ${err.message}`);
119
+ }
120
+ }
121
+ };
122
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ternkit/tern",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Client runtime and Vite plugin for Tern: Svelte on the client, Go on the server",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -71,7 +71,8 @@
71
71
  "vite": "^8.0.0"
72
72
  },
73
73
  "dependencies": {
74
- "@sveltejs/vite-plugin-svelte": "^7.3.1"
74
+ "@sveltejs/vite-plugin-svelte": "^7.3.1",
75
+ "acorn": "^8.19.0"
75
76
  },
76
77
  "devDependencies": {
77
78
  "@sveltejs/package": "^3.0.2",