sepal 0.1.0-alpha.2 → 0.3.0-alpha.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 (81) hide show
  1. package/README.md +16 -9
  2. package/cli.js +127 -10
  3. package/package.json +48 -21
  4. package/src/abort.js +129 -0
  5. package/src/app.js +13 -0
  6. package/src/dom.js +173 -60
  7. package/src/fetch.js +347 -80
  8. package/src/form-data.js +141 -0
  9. package/src/host-call.js +57 -0
  10. package/src/index.js +14 -12
  11. package/src/lru.js +45 -0
  12. package/src/native.js +32 -0
  13. package/src/notifications.js +60 -0
  14. package/src/os.js +35 -0
  15. package/src/process.js +164 -0
  16. package/src/protocol.js +3 -4
  17. package/src/renderer.js +140 -10
  18. package/src/secrets.js +42 -0
  19. package/src/settings.js +52 -0
  20. package/src/shims.js +111 -11
  21. package/src/stem.js +125 -0
  22. package/src/updater.js +3 -2
  23. package/src/url.js +65 -20
  24. package/src/web.js +86 -0
  25. package/src/window.js +6 -2
  26. package/types/abort.d.ts +46 -0
  27. package/types/app.d.ts +7 -0
  28. package/types/fetch.d.ts +118 -28
  29. package/types/form-data.d.ts +19 -0
  30. package/types/host-call.d.ts +18 -0
  31. package/types/index.d.ts +5 -2
  32. package/types/lru.d.ts +18 -0
  33. package/types/native.d.ts +22 -0
  34. package/types/notifications.d.ts +53 -0
  35. package/types/os.d.ts +53 -0
  36. package/types/process.d.ts +90 -0
  37. package/types/protocol.d.ts +0 -2
  38. package/types/renderer.d.ts +16 -1
  39. package/types/secrets.d.ts +22 -0
  40. package/types/settings.d.ts +29 -0
  41. package/types/shims.d.ts +13 -0
  42. package/types/stem.d.ts +21 -0
  43. package/types/updater.d.ts +6 -4
  44. package/types/url.d.ts +1 -1
  45. package/types/vite/adapter.d.ts +22 -0
  46. package/types/vite/add.d.ts +77 -0
  47. package/types/vite/app.d.ts +52 -1
  48. package/types/vite/licenses.d.ts +11 -0
  49. package/types/vite/native.d.ts +135 -0
  50. package/types/vite/page.d.ts +20 -0
  51. package/types/vite/permissions.d.ts +56 -0
  52. package/types/vite/sveltekit.d.ts +5 -34
  53. package/types/vite/vite.d.ts +86 -53
  54. package/types/web.d.ts +17 -0
  55. package/types/window.d.ts +5 -1
  56. package/vite/adapter.js +118 -0
  57. package/vite/add.js +254 -0
  58. package/vite/app.js +195 -27
  59. package/vite/head.js +2 -2
  60. package/vite/licenses.js +115 -0
  61. package/vite/native.js +535 -0
  62. package/vite/page.js +95 -0
  63. package/vite/permissions.d.ts +56 -0
  64. package/vite/sveltekit.js +11 -224
  65. package/vite/vite.js +377 -147
  66. package/ambient.d.ts +0 -20
  67. package/types/vite/navigation.d.ts +0 -1
  68. package/types/vite/router-entry.d.ts +0 -1
  69. package/types/vite/router.d.ts +0 -21
  70. package/types/vite/routes.d.ts +0 -41
  71. package/types/vite/routing.svelte.d.ts +0 -131
  72. package/types/vite/state.d.ts +0 -1
  73. package/vite/Router.svelte +0 -32
  74. package/vite/RouterError.svelte +0 -11
  75. package/vite/navigation.js +0 -3
  76. package/vite/router-entry.js +0 -12
  77. package/vite/router.js +0 -17
  78. package/vite/routes.js +0 -219
  79. package/vite/routing.svelte.js +0 -378
  80. package/vite/state.js +0 -2
  81. package/vite/virtual.d.ts +0 -9
@@ -5,7 +5,9 @@
5
5
  * (square, 1024×1024 recommended) in the `static/` directory, named relative to
6
6
  * it; `static/icon.png` is used when `icon` is left out, and the Sepal icon
7
7
  * when there is no `static/icon.png` either. `width` and `height`
8
- * are the initial window size in logical pixels. `id` (a bundle identifier such as `com.example.counter`) and
8
+ * are the initial window size in logical pixels, and `minWidth` and `minHeight` how
9
+ * small the window can be made: the size below which the app's layout cannot
10
+ * work. The window never opens smaller. `id` (a bundle identifier such as `com.example.counter`) and
9
11
  * `version` are used when the app is bundled.
10
12
  *
11
13
  * `updater` turns on self-update: `url` is where the update feed
@@ -13,28 +15,20 @@
13
15
  * updates are signed with (`sepal signer generate`). The app then
14
16
  * updates itself through `sepal/updater`.
15
17
  *
18
+ * `background: true` keeps an app with server code running when its last
19
+ * window closes: the server code goes on, with no window, until the app
20
+ * calls `quit()` from `sepal/app`. Otherwise closing the window quits the app.
21
+ *
16
22
  * @typedef {{
17
23
  * name?: string,
18
24
  * id?: string,
19
25
  * version?: string,
20
26
  * icon?: string,
27
+ * background?: boolean,
21
28
  * updater?: { url: string, pubkey: string },
22
- * window?: { title?: string, width?: number, height?: number }
29
+ * window?: { title?: string, width?: number, height?: number, minWidth?: number, minHeight?: number }
23
30
  * }} AppManifest
24
31
  */
25
- /**
26
- * Routing. Leave it out for the default: the built-in router when the
27
- * project has a `src/routes` directory, no router when it does not.
28
- *
29
- * - `false` turns routing off even if `src/routes` exists.
30
- * - `dir` is where the route files are (default `src/routes`).
31
- * - `entry` is a router of your own: a module that becomes the app's entry.
32
- * It mounts the app itself, and can import the generated route table
33
- * (`routes`, `fallback`) from `virtual:sepal/routes`. The built-in
34
- * `$app/navigation` and `$app/state` are not set up for it.
35
- *
36
- * @typedef {false | { dir?: string, entry?: string }} RouterOptions
37
- */
38
32
  /**
39
33
  * What the app may do outside its window. Everything is off unless it is
40
34
  * listed here; a call that is not allowed rejects with a message naming the
@@ -50,16 +44,26 @@
50
44
  * - `dialog`: open, save and message dialogs.
51
45
  * - `clipboard`: reading and writing the clipboard.
52
46
  * - `open`: opening web and mail links, and allowed files, in their default app.
53
- * - `window`: changing the window: title, minimise, maximise, close, drag.
47
+ * - `window`: changing the window: minimise, maximise, decorations, close,
48
+ * drag. The title needs no permission.
49
+ * - `os`: the system's details (`sepal/os`'s `info()`). Environment
50
+ * variables only by name: `os: { env: ['EDITOR'] }`, which gives `info()`
51
+ * too. The locale needs none: it is `navigator.language`.
52
+ * - `settings`: the app's settings (`sepal/settings`), a store the page,
53
+ * the server code and the app's Rust share.
54
+ * - `process`: which programs `sepal/process` may run: names
55
+ * (`'git'`) and absolute paths. It limits which programs start, not what
56
+ * they do: `git` runs hooks and aliases, a shell runs anything. `true`
57
+ * allows any program.
58
+ * - `secrets`: the OS's keychain (`sepal/secrets`), for the app's own
59
+ * tokens and passwords.
60
+ * - `notifications`: the system's notifications (`sepal/notifications`).
54
61
  *
55
- * @typedef {{
56
- * http?: boolean | string[],
57
- * fs?: boolean | string[],
58
- * dialog?: boolean,
59
- * clipboard?: boolean,
60
- * open?: boolean,
61
- * window?: boolean
62
- * }} Permissions
62
+ * An interface (vite/permissions.d.ts, `sepal/permissions`), so that a
63
+ * plugin's package can add its key:
64
+ * `declare module 'sepal/permissions' { interface Permissions { … } }`.
65
+ *
66
+ * @typedef {import('./permissions.js').Permissions} Permissions
63
67
  */
64
68
  /**
65
69
  * The settings in `sepal.config.ts`.
@@ -72,8 +76,6 @@
72
76
  * @typedef {{
73
77
  * app?: AppManifest,
74
78
  * permissions?: Permissions,
75
- * router?: RouterOptions,
76
- * entry?: string,
77
79
  * dom?: boolean
78
80
  * }} Config
79
81
  */
@@ -94,6 +96,35 @@ export function defineConfig<T extends Config | ((env: import("vite").ConfigEnv)
94
96
  export function sepal(inline?: Config & {
95
97
  svelte?: import("@sveltejs/vite-plugin-svelte").Options;
96
98
  }): import("vite").PluginOption[];
99
+ /**
100
+ * Sepal's rewrites of what Svelte refuses for a custom renderer (`bind:` on
101
+ * elements, `<svelte:head>`), as one preprocessor. `withSepal()` adds it;
102
+ * this is for an app that sets `sveltekit()`'s options by hand, after its
103
+ * own preprocessors: `preprocess: [vitePreprocess(), sepalPreprocess()]`.
104
+ * @returns {import('svelte/compiler').PreprocessorGroup}
105
+ */
106
+ export function sepalPreprocess(): import("svelte/compiler").PreprocessorGroup;
107
+ /**
108
+ * SvelteKit's options for a Sepal app: `sveltekit(withSepal({ adapter: adapter() }))`,
109
+ * with `adapter` from `sepal/adapter`. Adds what every Sepal app needs to
110
+ * the app's own options: components compiled for the Sepal renderer, no
111
+ * version polling (apps update through `sepal/updater`), and Sepal's
112
+ * rewrites after the app's own preprocessors (`sepalPreprocess()`), once.
113
+ * Throws on options that cannot work in an app.
114
+ * @template {import('@sveltejs/kit/vite').Config} T
115
+ * @param {T} options
116
+ * @returns {T}
117
+ */
118
+ export function withSepal<T extends import("@sveltejs/kit/vite").Config>(options: T): T;
119
+ /**
120
+ * What SvelteKit's options lack for a Sepal app, as messages; empty when
121
+ * nothing does. `sepal()` checks before the build, the adapter after it.
122
+ * @param {any} config SvelteKit's options, as it validated them
123
+ * @returns {string[]}
124
+ */
125
+ export function kit_setup_problems(config: any): string[];
126
+ /** A SvelteKit app's vite.config.ts, for the messages that point to it. */
127
+ export const KIT_SETUP: "import { sveltekit } from '@sveltejs/kit/vite';\nimport adapter from 'sepal/adapter';\nimport { sepal, withSepal } from 'sepal/vite';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n\tplugins: [sveltekit(withSepal({ adapter: adapter() })), sepal()]\n});";
97
128
  /**
98
129
  * What the app tells the host about itself. Written to `dist/app.json`.
99
130
  *
@@ -101,19 +132,26 @@ export function sepal(inline?: Config & {
101
132
  * (square, 1024×1024 recommended) in the `static/` directory, named relative to
102
133
  * it; `static/icon.png` is used when `icon` is left out, and the Sepal icon
103
134
  * when there is no `static/icon.png` either. `width` and `height`
104
- * are the initial window size in logical pixels. `id` (a bundle identifier such as `com.example.counter`) and
135
+ * are the initial window size in logical pixels, and `minWidth` and `minHeight` how
136
+ * small the window can be made: the size below which the app's layout cannot
137
+ * work. The window never opens smaller. `id` (a bundle identifier such as `com.example.counter`) and
105
138
  * `version` are used when the app is bundled.
106
139
  *
107
140
  * `updater` turns on self-update: `url` is where the update feed
108
141
  * (`latest.json`) is published, `pubkey` is the public half of the key the
109
142
  * updates are signed with (`sepal signer generate`). The app then
110
143
  * updates itself through `sepal/updater`.
144
+ *
145
+ * `background: true` keeps an app with server code running when its last
146
+ * window closes: the server code goes on, with no window, until the app
147
+ * calls `quit()` from `sepal/app`. Otherwise closing the window quits the app.
111
148
  */
112
149
  export type AppManifest = {
113
150
  name?: string;
114
151
  id?: string;
115
152
  version?: string;
116
153
  icon?: string;
154
+ background?: boolean;
117
155
  updater?: {
118
156
  url: string;
119
157
  pubkey: string;
@@ -122,23 +160,10 @@ export type AppManifest = {
122
160
  title?: string;
123
161
  width?: number;
124
162
  height?: number;
163
+ minWidth?: number;
164
+ minHeight?: number;
125
165
  };
126
166
  };
127
- /**
128
- * Routing. Leave it out for the default: the built-in router when the
129
- * project has a `src/routes` directory, no router when it does not.
130
- *
131
- * - `false` turns routing off even if `src/routes` exists.
132
- * - `dir` is where the route files are (default `src/routes`).
133
- * - `entry` is a router of your own: a module that becomes the app's entry.
134
- * It mounts the app itself, and can import the generated route table
135
- * (`routes`, `fallback`) from `virtual:sepal/routes`. The built-in
136
- * `$app/navigation` and `$app/state` are not set up for it.
137
- */
138
- export type RouterOptions = false | {
139
- dir?: string;
140
- entry?: string;
141
- };
142
167
  /**
143
168
  * What the app may do outside its window. Everything is off unless it is
144
169
  * listed here; a call that is not allowed rejects with a message naming the
@@ -154,16 +179,26 @@ export type RouterOptions = false | {
154
179
  * - `dialog`: open, save and message dialogs.
155
180
  * - `clipboard`: reading and writing the clipboard.
156
181
  * - `open`: opening web and mail links, and allowed files, in their default app.
157
- * - `window`: changing the window: title, minimise, maximise, close, drag.
182
+ * - `window`: changing the window: minimise, maximise, decorations, close,
183
+ * drag. The title needs no permission.
184
+ * - `os`: the system's details (`sepal/os`'s `info()`). Environment
185
+ * variables only by name: `os: { env: ['EDITOR'] }`, which gives `info()`
186
+ * too. The locale needs none: it is `navigator.language`.
187
+ * - `settings`: the app's settings (`sepal/settings`), a store the page,
188
+ * the server code and the app's Rust share.
189
+ * - `process`: which programs `sepal/process` may run: names
190
+ * (`'git'`) and absolute paths. It limits which programs start, not what
191
+ * they do: `git` runs hooks and aliases, a shell runs anything. `true`
192
+ * allows any program.
193
+ * - `secrets`: the OS's keychain (`sepal/secrets`), for the app's own
194
+ * tokens and passwords.
195
+ * - `notifications`: the system's notifications (`sepal/notifications`).
196
+ *
197
+ * An interface (vite/permissions.d.ts, `sepal/permissions`), so that a
198
+ * plugin's package can add its key:
199
+ * `declare module 'sepal/permissions' { interface Permissions { … } }`.
158
200
  */
159
- export type Permissions = {
160
- http?: boolean | string[];
161
- fs?: boolean | string[];
162
- dialog?: boolean;
163
- clipboard?: boolean;
164
- open?: boolean;
165
- window?: boolean;
166
- };
201
+ export type Permissions = import("./permissions.js").Permissions;
167
202
  /**
168
203
  * The settings in `sepal.config.ts`.
169
204
  *
@@ -175,7 +210,5 @@ export type Permissions = {
175
210
  export type Config = {
176
211
  app?: AppManifest;
177
212
  permissions?: Permissions;
178
- router?: RouterOptions;
179
- entry?: string;
180
213
  dom?: boolean;
181
214
  };
package/types/web.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { URL } from './url.js';
2
+ import { URLSearchParams } from './url.js';
3
+ import { TextEncoder } from './text.js';
4
+ import { TextDecoder } from './text.js';
5
+ import { AbortController } from './abort.js';
6
+ import { AbortSignal } from './abort.js';
7
+ import { fetch } from './fetch.js';
8
+ import { Headers } from './fetch.js';
9
+ import { Request } from './fetch.js';
10
+ import { Response } from './fetch.js';
11
+ import { ReadableStream } from 'web-streams-polyfill';
12
+ import { WritableStream } from 'web-streams-polyfill';
13
+ import { TransformStream } from 'web-streams-polyfill';
14
+ import { Blob } from 'formdata-node';
15
+ import { File } from 'formdata-node';
16
+ import { FormData } from 'formdata-node';
17
+ export { URL, URLSearchParams, TextEncoder, TextDecoder, AbortController, AbortSignal, fetch, Headers, Request, Response, ReadableStream, WritableStream, TransformStream, Blob, File, FormData };
package/types/window.d.ts CHANGED
@@ -1,4 +1,8 @@
1
- /** @param {string} title @returns {Promise<void>} */
1
+ /**
2
+ * Set the window's title. Needs no permission: the title is the app's own,
3
+ * as a page's is on the web (`document.title` does the same).
4
+ * @param {string} title @returns {Promise<void>}
5
+ */
2
6
  export function setTitle(title: string): Promise<void>;
3
7
  /** @returns {Promise<void>} */
4
8
  export function minimize(): Promise<void>;
@@ -0,0 +1,118 @@
1
+ // `sepal/adapter`: the SvelteKit adapter for Sepal apps.
2
+ //
3
+ // // vite.config.ts
4
+ // import { sveltekit } from '@sveltejs/kit/vite';
5
+ // import adapter from 'sepal/adapter';
6
+ // import { sepal, withSepal } from 'sepal/vite';
7
+ //
8
+ // export default defineConfig({
9
+ // plugins: [sveltekit(withSepal({ adapter: adapter() })), sepal()]
10
+ // });
11
+ //
12
+ // It writes SvelteKit's output as SvelteKit writes it, a single-page app:
13
+ // index.html as the shell every address starts from, the client chunks,
14
+ // stylesheets, fonts, static files and `_app/version.json`. Then `app.json`,
15
+ // for the host. Before that it checks what it was given, and stops the
16
+ // build saying what to add.
17
+ //
18
+ // Runs in Node.
19
+
20
+ import { cpSync, existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
21
+ import { join, relative, resolve } from 'node:path';
22
+ import { compile_bytecode, kit, manifest } from './app.js';
23
+ import { check_css, check_page } from './page.js';
24
+ import { kit_setup_problems } from './vite.js';
25
+
26
+ /** Every file under a directory, as paths relative to it, with `/`. @param {string} directory @returns {string[]} */
27
+ function files_in(directory) {
28
+ return readdirSync(directory, { recursive: true, withFileTypes: true })
29
+ .filter((entry) => entry.isFile())
30
+ .map((entry) => relative(directory, join(entry.parentPath, entry.name)).replaceAll('\\', '/'));
31
+ }
32
+
33
+ /**
34
+ * The files under `src` that SvelteKit would run on a server. An app has a
35
+ * thread for server code (the stem), but how an app's server code gets
36
+ * there is not decided (HANDOVER.md, "The stem's API: open"), so these
37
+ * would build and then never run. Relative to `src`.
38
+ * @param {string} src
39
+ */
40
+ export function server_files(src) {
41
+ if (!existsSync(src)) return [];
42
+ return files_in(src).filter((file) => /(^|\/)(\+(page|layout)\.server\.|\+server\.|hooks\.server\.)|\.remote\.[^/]+$/.test(file));
43
+ }
44
+
45
+ /**
46
+ * What is missing from the setup, as messages saying what to add.
47
+ * @param {import('@sveltejs/kit').Builder['config']} config
48
+ * @param {string} root the project
49
+ * @returns {string[]}
50
+ */
51
+ export function problems(config, root) {
52
+ const found = [];
53
+ if (kit.session === null) {
54
+ found.push('add `sepal()` from `sepal/vite` to the plugins in vite.config.ts, after `sveltekit()`: it builds the app for the Sepal renderer, and the adapter needs it.');
55
+ }
56
+ found.push(...kit_setup_problems(config));
57
+ const src = resolve(root, config.files?.src ?? 'src');
58
+ const server = server_files(src).map((file) => relative(root, join(src, file)).replaceAll('\\', '/'));
59
+ if (server.length > 0) {
60
+ found.push(
61
+ `remove ${server.join(', ')}: SvelteKit's server files are not supported yet. Use +page.ts and +layout.ts instead (\`load\` runs in the app).`
62
+ );
63
+ }
64
+ return found;
65
+ }
66
+
67
+ /**
68
+ * SvelteKit's route announcer is a 1px `overflow: hidden` box at the top
69
+ * left. Blitz hit-tests what overflows such a box, so after the first
70
+ * navigation its invisible text took clicks meant for what is drawn there.
71
+ * ponytail: goes when Blitz's hit testing clips to `overflow: hidden` (HANDOVER.md, "Blitz hit testing clipped to overflow: hidden").
72
+ */
73
+ const ANNOUNCER = '<style>#svelte-announcer { pointer-events: none }</style>';
74
+
75
+ /**
76
+ * @param {{ out?: string }} [options] `out` is where the app is written (default `dist`).
77
+ * @returns {import('@sveltejs/kit').Adapter}
78
+ */
79
+ export default function adapter({ out = 'dist' } = {}) {
80
+ return {
81
+ name: 'sepal',
82
+ async adapt(builder) {
83
+ const session = kit.session;
84
+ const root = session?.root ?? process.cwd();
85
+ const missing = problems(builder.config, root);
86
+ if (missing.length > 0) throw new Error(`sepal: ${missing.join('\nsepal: ')}`);
87
+ if (session === null) return;
88
+
89
+ const to = resolve(root, out);
90
+ rmSync(to, { force: true, recursive: true });
91
+ builder.writeClient(to);
92
+ // The shell SvelteKit serves for an address it did not prerender:
93
+ // what the app starts from, whatever its address.
94
+ const page = join(to, 'index.html');
95
+ await builder.generateFallback(page);
96
+ if (builder.prerendered.paths.length > 0) {
97
+ builder.log.warn(`sepal: prerendering is not done yet; ${builder.prerendered.paths.join(', ')} render in the app instead`);
98
+ }
99
+
100
+ const html = readFileSync(page, 'utf8');
101
+ const { errors, warnings } = check_page(html);
102
+ for (const file of files_in(to).filter((file) => file.endsWith('.css'))) errors.push(...check_css(readFileSync(join(to, file), 'utf8'), file));
103
+ if (errors.length > 0) throw new Error(`sepal: ${errors.join('\nsepal: ')}`);
104
+ for (const warning of warnings) builder.log.warn(`sepal: ${warning}`);
105
+ writeFileSync(page, html.replace('</head>', `\t${ANNOUNCER}\n\t</head>`));
106
+
107
+ const assets = resolve(root, builder.config.files?.assets ?? 'static');
108
+ const written = manifest(session.options, root, existsSync(assets) ? assets : '');
109
+ for (const warning of written?.warnings ?? []) builder.log.warn(`sepal: ${warning}`);
110
+ if (written) writeFileSync(join(to, 'app.json'), written.json);
111
+ if (written?.icon) cpSync(written.icon, join(to, 'icon.png'));
112
+ const compiled = compile_bytecode(to, (message) => builder.log.warn(message));
113
+ if (compiled) builder.log.minor(compiled);
114
+ builder.log.minor(`Wrote the app to ${relative(root, to) || '.'}`);
115
+ session.written(to);
116
+ }
117
+ };
118
+ }
package/vite/add.js ADDED
@@ -0,0 +1,254 @@
1
+ // `sepal add` and `sepal check`: adding a plugin to an app (its npm
2
+ // package, its crate in native/, its line in native/src/plugins.rs, its key
3
+ // in sepal.config.ts), handing anything else to `sv add`, and checking that
4
+ // those agree. Runs in Node.
5
+ //
6
+ // An add-on that is a plugin says so in its package.json:
7
+ //
8
+ // "sepal": { "plugin": { "crate": "sepal-watch", "init": "sepal_watch::init()",
9
+ // "permission": { "key": "watch", "default": ["documents"] } } }
10
+
11
+ import { spawnSync } from 'node:child_process';
12
+ import { existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
13
+ import { dirname, join, sep } from 'node:path';
14
+ import { tsPlugin } from '@sveltejs/acorn-typescript';
15
+ import { Parser } from 'acorn';
16
+ import MagicString from 'magic-string';
17
+ import { caret_accepts, init, native_manifest, tag_problem, VERSION } from './native.js';
18
+
19
+ /**
20
+ * Sepal's own plugins, by short name. `sepal add watch` means these and
21
+ * nothing else: never whatever `sepal-<name>` someone published, which would
22
+ * then be installed as if it were ours, crate and all.
23
+ */
24
+ export const FIRST_PARTY = /** @type {Record<string, string>} */ ({ watch: 'sepal-watch' });
25
+
26
+ /** The keys the host reads itself (`BUILT_IN` in crates/host/src/api/mod.rs). */
27
+ const BUILT_IN = ['http', 'fs', 'dialog', 'clipboard', 'open', 'window', 'os', 'settings', 'process', 'secrets', 'notifications'];
28
+
29
+ /** @typedef {{ crate: string, init: string, permission: { key: string, default?: unknown } }} PluginInfo */
30
+
31
+ /** @param {string} root */
32
+ export function package_manager(root) {
33
+ if (existsSync(join(root, 'pnpm-lock.yaml')) || process.env.npm_config_user_agent?.startsWith('pnpm')) return 'pnpm';
34
+ if (existsSync(join(root, 'yarn.lock'))) return 'yarn';
35
+ if (existsSync(join(root, 'bun.lock')) || existsSync(join(root, 'bun.lockb'))) return 'bun';
36
+ return 'npm';
37
+ }
38
+
39
+ /** @param {string} file */
40
+ const json = (file) => JSON.parse(readFileSync(file, 'utf8'));
41
+
42
+ /**
43
+ * The plugin an installed package is, or null. `sepal` is its peer range
44
+ * on sepal, which is its crate's requirement too.
45
+ * @param {string} root @param {string} name
46
+ * @returns {{ info: PluginInfo, version: string, dir: string, sepal: string | undefined } | null}
47
+ */
48
+ export function installed_plugin(root, name) {
49
+ const manifest = join(root, 'node_modules', name, 'package.json');
50
+ if (!existsSync(manifest)) return null;
51
+ const pkg = json(manifest);
52
+ return pkg.sepal?.plugin ? { info: pkg.sepal.plugin, version: pkg.version, dir: realpathSync(dirname(manifest)), sepal: pkg.peerDependencies?.sepal } : null;
53
+ }
54
+
55
+ /** The project's dependencies, by name. @param {string} root @returns {string[]} */
56
+ function dependencies(root) {
57
+ const pkg = json(join(root, 'package.json'));
58
+ return Object.keys({ ...pkg.dependencies, ...pkg.devDependencies });
59
+ }
60
+
61
+ /** Every plugin the project depends on, in name order. @param {string} root */
62
+ export function plugins(root) {
63
+ return dependencies(root)
64
+ .sort()
65
+ .map((name) => installed_plugin(root, name))
66
+ .filter((plugin) => plugin !== null);
67
+ }
68
+
69
+ /** `native/src/plugins.rs` for these plugins. @param {PluginInfo[]} infos */
70
+ export function plugins_rs(infos) {
71
+ const lines = infos.map((info) => `\n .plugin(${info.init})`).join('');
72
+ return `// Written by \`sepal add\`: it lists the app's plugins, and is written again
73
+ // when one is added or removed. Edits here are lost.
74
+ pub fn add(app: sepal::App) -> sepal::App {
75
+ app${lines}
76
+ }
77
+ `;
78
+ }
79
+
80
+ /** @param {unknown} value as TypeScript source */
81
+ function source(value) {
82
+ return JSON.stringify(value).replaceAll('"', "'");
83
+ }
84
+
85
+ /**
86
+ * Add `key: value` to `permissions` in a `sepal.config.ts`, in place: the
87
+ * file is parsed (acorn with TypeScript) and the text inserted where it
88
+ * goes, nothing reprinted. Null when the file is not `export default
89
+ * defineConfig({ … })` with an object literal, which then needs the line
90
+ * by hand.
91
+ * @param {string} code @param {string} key @param {unknown} value
92
+ * @returns {{ code: string, changed: boolean } | null}
93
+ */
94
+ export function add_permission(code, key, value) {
95
+ /** @type {any} */
96
+ let ast;
97
+ try {
98
+ ast = Parser.extend(/** @type {any} */ (tsPlugin())).parse(code, { sourceType: 'module', ecmaVersion: 'latest' });
99
+ } catch {
100
+ return null;
101
+ }
102
+ const declaration = ast.body.find((/** @type {any} */ node) => node.type === 'ExportDefaultDeclaration')?.declaration;
103
+ const config = declaration?.type === 'CallExpression' ? declaration.arguments[0] : declaration;
104
+ if (config?.type !== 'ObjectExpression') return null;
105
+ const name = (/** @type {any} */ property) => property.key?.name ?? property.key?.value;
106
+ const edited = new MagicString(code);
107
+ /** Insert `text` as the last property of `object`, indented as its others. @param {any} object @param {string} text */
108
+ const append = (object, text) => {
109
+ const last = object.properties.at(-1);
110
+ if (!last) {
111
+ const indent = code.slice(code.lastIndexOf('\n', object.start) + 1).match(/^\s*/)?.[0] ?? '';
112
+ edited.appendLeft(object.start + 1, `\n${indent}\t${text}\n${indent}`);
113
+ return;
114
+ }
115
+ // On one line with its braces (`{ delay: true }`): stays on one line.
116
+ if (!code.slice(object.start, last.start).includes('\n')) {
117
+ edited.appendLeft(last.end, `, ${text}`);
118
+ return;
119
+ }
120
+ const indent = code.slice(code.lastIndexOf('\n', last.start) + 1).match(/^[ \t]*/)?.[0] ?? '';
121
+ edited.appendLeft(last.end, `,\n${indent}${text}`);
122
+ };
123
+ const permissions = config.properties.find((/** @type {any} */ property) => name(property) === 'permissions');
124
+ if (!permissions) {
125
+ append(config, `permissions: { ${key}: ${source(value)} }`);
126
+ } else if (permissions.value.type !== 'ObjectExpression') {
127
+ return null;
128
+ } else if (permissions.value.properties.some((/** @type {any} */ property) => name(property) === key)) {
129
+ return { code, changed: false };
130
+ } else {
131
+ append(permissions.value, `${key}: ${source(value)}`);
132
+ }
133
+ return { code: edited.toString(), changed: true };
134
+ }
135
+
136
+ /** @typedef {(command: string, args: string[], cwd: string) => { status: number | null }} Run */
137
+
138
+ /** @type {Run} */
139
+ const run_inheriting = (command, args, cwd) => spawnSync(command, args, { cwd, stdio: 'inherit' });
140
+
141
+ /**
142
+ * `sepal add <names…>`.
143
+ * @param {string} root the project
144
+ * @param {string[]} names
145
+ * @param {{ run?: Run, view?: (name: string) => boolean, crate_name: string, log?: (line: string) => void }} options
146
+ * `view` says whether a package that is not one of ours is a plugin (by default, the registry's word)
147
+ */
148
+ export function add(root, names, { run = run_inheriting, view = registry_says_plugin, crate_name, log = console.log }) {
149
+ for (const name of names) {
150
+ const pkg = FIRST_PARTY[name] ?? name;
151
+ let plugin = dependencies(root).includes(pkg) ? installed_plugin(root, pkg) : null;
152
+ if (!plugin && !FIRST_PARTY[name] && !view(name)) {
153
+ // Not a Sepal plugin: sv's add-ons work on a Sepal app as they are.
154
+ log(`sepal: ${name} is not a Sepal plugin; handing it to sv add`);
155
+ if (run('npx', ['sv', 'add', name], root).status !== 0) throw new Error(`sv add ${name} failed`);
156
+ continue;
157
+ }
158
+ if (!plugin) {
159
+ const manager = package_manager(root);
160
+ if (run(manager, [manager === 'npm' ? 'install' : 'add', pkg], root).status !== 0) {
161
+ throw new Error(`${manager} could not install ${pkg}`);
162
+ }
163
+ plugin = installed_plugin(root, pkg);
164
+ if (!plugin) throw new Error(`${pkg} is not a Sepal plugin: its package.json has no "sepal": { "plugin" }`);
165
+ }
166
+ if (!native_manifest(root)) {
167
+ init(root, crate_name);
168
+ log('sepal: wrote native/, the app’s own host');
169
+ }
170
+ // A plugin from this workspace (not from node_modules) is added by
171
+ // path; a published one at the package's version, its crate's.
172
+ const local = !plugin.dir.split(sep).includes('node_modules') && existsSync(join(plugin.dir, 'Cargo.toml'));
173
+ const manifest = join(root, 'native', 'Cargo.toml');
174
+ const crate = local ? [plugin.info.crate, '--path', plugin.dir] : [`${plugin.info.crate}@=${plugin.version}`];
175
+ if (run('cargo', ['add', ...crate, '--manifest-path', manifest], root).status !== 0) {
176
+ throw new Error(`cargo add ${plugin.info.crate} failed`);
177
+ }
178
+ write_plugins_rs(root);
179
+ const key = plugin.info.permission.key;
180
+ const config = ['sepal.config.ts', 'sepal.config.js', 'sepal.config.mjs'].map((file) => join(root, file)).find(existsSync);
181
+ const value = plugin.info.permission.default ?? true;
182
+ const edited = config ? add_permission(readFileSync(config, 'utf8'), key, value) : null;
183
+ if (config && edited) {
184
+ if (edited.changed) writeFileSync(config, edited.code);
185
+ log(`sepal: added ${pkg}: its crate to native/, \`${plugin.info.init}\` to native/src/plugins.rs, and ${edited.changed ? `\`${key}: ${source(value)}\` to permissions` : `\`${key}\` was in permissions already`}.`);
186
+ } else {
187
+ log(`sepal: added ${pkg} to native/. Add this to \`permissions\` in sepal.config.ts:\n\n ${key}: ${source(value)}\n`);
188
+ }
189
+ log('sepal: the next `vite build --watch` builds it into the app’s own host.');
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Whether a package that is not one of ours is a Sepal plugin, by asking
195
+ * the registry for its `sepal` field. Only then is it installed.
196
+ * @param {string} name
197
+ */
198
+ function registry_says_plugin(name) {
199
+ const viewed = spawnSync('npm', ['view', name, 'sepal', '--json'], { encoding: 'utf8' });
200
+ return viewed.status === 0 && viewed.stdout.includes('"plugin"');
201
+ }
202
+
203
+ /** Write native/src/plugins.rs again from the plugins the project has. @param {string} root */
204
+ export function write_plugins_rs(root) {
205
+ writeFileSync(join(root, 'native', 'src', 'plugins.rs'), plugins_rs(plugins(root).map((plugin) => plugin.info)));
206
+ }
207
+
208
+ /**
209
+ * `sepal check`'s own part: what has to agree between the npm packages,
210
+ * native/ and the config. svelte-check runs beside it.
211
+ * @param {string} root @param {Record<string, unknown> | undefined} permissions the config's
212
+ * @param {string} [version] this sepal's
213
+ * @returns {string[]} the problems
214
+ */
215
+ export function check(root, permissions, version = VERSION) {
216
+ const problems = [];
217
+ const installed = plugins(root);
218
+ for (const plugin of installed) {
219
+ // Said here, before cargo says "failed to select a version for `sepal`":
220
+ // native/ pins sepal exactly, and a build holds one sepal 0.x.
221
+ // ponytail: carets only, which is what the template and `workspace:^`
222
+ // publish; a range of another shape is not judged. A range parser
223
+ // when a plugin ships one.
224
+ const range = /^\^(\S+)$/.exec(plugin.sepal ?? '')?.[1];
225
+ if (range && !caret_accepts(range, version)) {
226
+ problems.push(
227
+ `${plugin.info.crate} ${plugin.version} is written for sepal ^${range}, and this is sepal ${version}: cargo finds no sepal that fits both. A plugin fits one 0.x line of sepal; install a ${plugin.info.crate} released for this one`
228
+ );
229
+ }
230
+ }
231
+ const manifest = native_manifest(root);
232
+ if (manifest) {
233
+ const tag = tag_problem(manifest, VERSION);
234
+ if (tag) problems.push(tag.trim());
235
+ const written = readFileSync(join(root, 'native', 'src', 'plugins.rs'), 'utf8');
236
+ if (written !== plugins_rs(installed.map((plugin) => plugin.info))) {
237
+ problems.push('native/src/plugins.rs does not list the plugins the app depends on: run `sepal add` again, or remove the package');
238
+ }
239
+ } else if (installed.length > 0) {
240
+ problems.push(`the app depends on ${installed.map((plugin) => plugin.info.crate).join(', ')} but has no native/ to build it into: \`sepal add\` writes one`);
241
+ }
242
+ const keys = installed.map((plugin) => plugin.info.permission.key);
243
+ for (const key of Object.keys(permissions ?? {})) {
244
+ if (!BUILT_IN.includes(key) && !keys.includes(key)) {
245
+ problems.push(`permissions.${key} is neither built in nor a plugin's the app has: the host stops at launch on it`);
246
+ }
247
+ }
248
+ for (const plugin of installed) {
249
+ if (!(plugin.info.permission.key in (permissions ?? {}))) {
250
+ problems.push(`${plugin.info.crate} needs permissions.${plugin.info.permission.key}; without it its commands are refused`);
251
+ }
252
+ }
253
+ return problems;
254
+ }