sepal 0.1.0-alpha.2 → 0.2.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.
@@ -1,21 +0,0 @@
1
- /**
2
- * For typing `load` functions, and for writing a router of your own against
3
- * `virtual:sepal/routes`.
4
- */
5
- export type LoadEvent = import("./routing.svelte.js").LoadEvent;
6
- /**
7
- * For typing `load` functions, and for writing a router of your own against
8
- * `virtual:sepal/routes`.
9
- */
10
- export type PageUrl = import("./routing.svelte.js").PageUrl;
11
- /**
12
- * For typing `load` functions, and for writing a router of your own against
13
- * `virtual:sepal/routes`.
14
- */
15
- export type Route = import("./routing.svelte.js").Route;
16
- /**
17
- * For typing `load` functions, and for writing a router of your own against
18
- * `virtual:sepal/routes`.
19
- */
20
- export type RouteNode = import("./routing.svelte.js").RouteNode;
21
- export { error, redirect, goto, back, forward, page } from "./routing.svelte.js";
@@ -1,41 +0,0 @@
1
- /**
2
- * @param {string} dir absolute path of `src/routes`
3
- * @returns {{ routes: ScannedRoute[], fallback: { layouts: NodeFiles[], error: string | null }, files: string[] }}
4
- */
5
- export function scan_routes(dir: string): {
6
- routes: ScannedRoute[];
7
- fallback: {
8
- layouts: NodeFiles[];
9
- error: string | null;
10
- };
11
- files: string[];
12
- };
13
- /**
14
- * @param {string[]} segments
15
- * @returns {{ pattern: string, names: string[] }} `pattern` is regular expression source
16
- */
17
- export function route_pattern(segments: string[]): {
18
- pattern: string;
19
- names: string[];
20
- };
21
- /**
22
- * The source of `virtual:sepal/routes`.
23
- * @param {string} dir absolute path of `src/routes`
24
- * @returns {{ code: string, files: string[] }} `files` are what the module was built from
25
- */
26
- export function generate_routes(dir: string): {
27
- code: string;
28
- files: string[];
29
- };
30
- export type NodeFiles = {
31
- component: string | null;
32
- module: string | null;
33
- };
34
- export type ScannedRoute = {
35
- id: string;
36
- segments: string[];
37
- layouts: NodeFiles[];
38
- page: NodeFiles;
39
- error: string | null;
40
- error_depth: number;
41
- };
@@ -1,131 +0,0 @@
1
- /**
2
- * Stop a `load` and show the nearest `+error.svelte` with this status.
3
- * @param {number} status
4
- * @param {string} [message]
5
- * @returns {never}
6
- */
7
- export function error(status: number, message?: string): never;
8
- /**
9
- * Stop a `load` and go somewhere else instead.
10
- * @param {number} status kept for parity with SvelteKit; it has no effect here
11
- * @param {string} location
12
- * @returns {never}
13
- */
14
- export function redirect(status: number, location: string): never;
15
- /**
16
- * Navigate to another page, like SvelteKit's `goto`.
17
- * @param {string} href a path; relative ones resolve against the current page
18
- * @param {{ replaceState?: boolean }} [options] `replaceState` replaces the current history entry instead of adding one
19
- * @returns {Promise<void>} resolves when the new page is showing
20
- */
21
- export function goto(href: string, { replaceState }?: {
22
- replaceState?: boolean;
23
- }): Promise<void>;
24
- /**
25
- * Go back one page, like `history.back()` in a browser. Does nothing on the first page.
26
- * @returns {Promise<void>}
27
- */
28
- export function back(): Promise<void>;
29
- /**
30
- * Go forward again after `back()`.
31
- * @returns {Promise<void>}
32
- */
33
- export function forward(): Promise<void>;
34
- /**
35
- * Called once by the generated entry module.
36
- * @param {{ routes: Route[], fallback: typeof fallback }} manifest
37
- * @param {import('svelte').Component<any>} error_component shown when no `+error.svelte` applies
38
- */
39
- export function start(manifest: {
40
- routes: Route[];
41
- fallback: typeof fallback;
42
- }, error_component: import("svelte").Component<any>): Promise<void>;
43
- /**
44
- * The page that is showing. Reactive; the same shape as `page` in SvelteKit's
45
- * `$app/state`, except that `url` is a plain object.
46
- * @type {{
47
- * url: PageUrl,
48
- * params: Record<string, string>,
49
- * route: { id: string | null },
50
- * data: Record<string, any>,
51
- * status: number,
52
- * error: { message: string } | null
53
- * }}
54
- */
55
- export const page: {
56
- url: PageUrl;
57
- params: Record<string, string>;
58
- route: {
59
- id: string | null;
60
- };
61
- data: Record<string, any>;
62
- status: number;
63
- error: {
64
- message: string;
65
- } | null;
66
- };
67
- export namespace router {
68
- const view: View | null;
69
- }
70
- /**
71
- * A `+layout` or `+page`: its component and the `load` from the `.js`/`.ts`
72
- * file next to it. A layout may have only a `load`.
73
- */
74
- export type RouteNode = {
75
- component: import("svelte").Component<any> | null;
76
- load?: (event: LoadEvent) => any;
77
- };
78
- /**
79
- * `error` is the nearest `+error.svelte`; `error_depth` is how many of the
80
- * route's layouts stay on screen around it (those down to its own directory).
81
- */
82
- export type Route = {
83
- id: string;
84
- pattern: RegExp;
85
- names: string[];
86
- layouts: RouteNode[];
87
- page: RouteNode;
88
- error: import("svelte").Component<any> | null;
89
- error_depth: number;
90
- };
91
- /**
92
- * What a `load` function receives.
93
- */
94
- export type LoadEvent = {
95
- params: Record<string, string>;
96
- url: PageUrl;
97
- route: {
98
- id: string | null;
99
- };
100
- parent: () => Promise<Record<string, any>>;
101
- };
102
- /**
103
- * The current location. A plain object with the commonly used parts of a
104
- * `URL`; the engine has no `URL` class.
105
- */
106
- export type PageUrl = {
107
- href: string;
108
- pathname: string;
109
- search: string;
110
- hash: string;
111
- searchParams: {
112
- get(name: string): string | null;
113
- has(name: string): boolean;
114
- };
115
- };
116
- /**
117
- * What is on screen: the layouts from the outside in, then the page (or an
118
- * error component in its place). `data[i]` is what layout `i` receives.
119
- */
120
- export type View = {
121
- layouts: RouteNode[];
122
- data: Record<string, any>[];
123
- page: import("svelte").Component<any>;
124
- page_data: Record<string, any>;
125
- };
126
- /** Used when nothing matches: the root layouts around the root `+error.svelte`. */
127
- declare let fallback: {
128
- layouts: RouteNode[];
129
- error: import("svelte").Component<any> | null;
130
- };
131
- export {};
@@ -1 +0,0 @@
1
- export { page } from "./routing.svelte.js";
@@ -1,32 +0,0 @@
1
- <!--
2
- Renders the current view: each layout around the next one, the page innermost.
3
- A layout keeps its instance (and its state) for as long as it stays in the
4
- chain; only what is below a change is replaced.
5
- -->
6
- <!-- Without a rune in the file Svelte would compile it in legacy mode, where a
7
- component tag is resolved once and never switches. -->
8
- <svelte:options runes={true} />
9
-
10
- <script>
11
- import { page, router } from './routing.svelte.js';
12
- </script>
13
-
14
- {#snippet level(index)}
15
- {@const view = router.view}
16
- {#if index < view.layouts.length}
17
- {@const Layout = view.layouts[index].component}
18
- {#if Layout}
19
- <Layout data={view.data[index]} params={page.params}>
20
- {@render level(index + 1)}
21
- </Layout>
22
- {:else}
23
- {@render level(index + 1)}
24
- {/if}
25
- {:else}
26
- <view.page data={view.page_data} params={page.params} />
27
- {/if}
28
- {/snippet}
29
-
30
- {#if router.view}
31
- {@render level(0)}
32
- {/if}
@@ -1,11 +0,0 @@
1
- <!-- Shown when a route fails and the app has no +error.svelte for it. -->
2
- <!-- Without a rune in the file Svelte would compile it in legacy mode, where a
3
- component tag is resolved once and never switches. -->
4
- <svelte:options runes={true} />
5
-
6
- <script>
7
- import { page } from './routing.svelte.js';
8
- </script>
9
-
10
- <h1>{page.status}</h1>
11
- <p>{page.error?.message}</p>
@@ -1,3 +0,0 @@
1
- // `$app/navigation`. `back` and `forward` are additions: SvelteKit apps use
2
- // `history.back()`, and there is no `history` here.
3
- export { goto, back, forward } from './routing.svelte.js';
@@ -1,12 +0,0 @@
1
- // The entry module of an app that uses the built-in router. The Vite preset
2
- // points the build at this file; `virtual:sepal/routes` is the route table it
3
- // generates from that directory.
4
-
5
- import { mount } from 'sepal';
6
- import Router from './Router.svelte';
7
- import RouterError from './RouterError.svelte';
8
- import { start } from './routing.svelte.js';
9
- import * as manifest from 'virtual:sepal/routes';
10
-
11
- start(manifest, RouterError);
12
- mount(Router);
package/vite/router.js DELETED
@@ -1,17 +0,0 @@
1
- // The router's runtime API in one place:
2
- //
3
- // import { error, redirect, goto, page } from 'sepal/router';
4
- //
5
- // `$app/navigation` and `$app/state` are the SvelteKit-style names for parts of it.
6
-
7
- export { error, redirect, goto, back, forward, page } from './routing.svelte.js';
8
-
9
- /**
10
- * For typing `load` functions, and for writing a router of your own against
11
- * `virtual:sepal/routes`.
12
- *
13
- * @typedef {import('./routing.svelte.js').LoadEvent} LoadEvent
14
- * @typedef {import('./routing.svelte.js').PageUrl} PageUrl
15
- * @typedef {import('./routing.svelte.js').Route} Route
16
- * @typedef {import('./routing.svelte.js').RouteNode} RouteNode
17
- */
package/vite/routes.js DELETED
@@ -1,219 +0,0 @@
1
- // Reads `src/routes` and turns it into the route table the router runs on.
2
- // Runs in Node, inside the Vite preset.
3
- //
4
- // The conventions are SvelteKit's:
5
- //
6
- // +page.svelte a page +page.js / +page.ts its `load`
7
- // +layout.svelte wraps what is below +layout.js / +layout.ts its `load`
8
- // +error.svelte shown for errors at or below this directory
9
- // [name] a parameter [...name] the rest of the path
10
- // (name) a group: layouts apply, the path does not change
11
- //
12
- // Not supported, and reported as build errors rather than ignored: anything
13
- // that needs a server (`+page.server`, `+layout.server`, `+server`), optional
14
- // parameters (`[[name]]`) and matchers (`[name=matcher]`).
15
-
16
- import { readdirSync } from 'node:fs';
17
-
18
- /**
19
- * @typedef {{ component: string | null, module: string | null }} NodeFiles
20
- * @typedef {{
21
- * id: string,
22
- * segments: string[],
23
- * layouts: NodeFiles[],
24
- * page: NodeFiles,
25
- * error: string | null,
26
- * error_depth: number
27
- * }} ScannedRoute
28
- */
29
-
30
- /** @param {string} message @returns {never} */
31
- function fail(message) {
32
- throw new Error(`sepal routes: ${message}`);
33
- }
34
-
35
- /**
36
- * @param {string} dir absolute path of `src/routes`
37
- * @returns {{ routes: ScannedRoute[], fallback: { layouts: NodeFiles[], error: string | null }, files: string[] }}
38
- */
39
- export function scan_routes(dir) {
40
- /** @type {ScannedRoute[]} */
41
- const routes = [];
42
- /** @type {string[]} */
43
- const files = [];
44
- let fallback = /** @type {{ layouts: NodeFiles[], error: string | null }} */ ({ layouts: [], error: null });
45
-
46
- /**
47
- * @param {string} current directory being read
48
- * @param {string[]} id_parts every directory name from the root, groups included
49
- * @param {NodeFiles[]} layouts layouts that apply here, outermost first
50
- * @param {string | null} error nearest `+error.svelte`
51
- * @param {number} error_depth how many of `layouts` stay on screen around that error page
52
- */
53
- function walk(current, id_parts, layouts, error, error_depth) {
54
- const entries = readdirSync(current, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1));
55
- /** @type {Record<string, string>} */
56
- const found = {};
57
-
58
- for (const entry of entries) {
59
- if (entry.isDirectory() || !entry.name.startsWith('+')) continue;
60
- const path = `${current}/${entry.name}`;
61
- const match = /^\+(page|layout|error)\.(svelte|js|ts)$/.exec(entry.name);
62
- if (/^\+(page|layout)\.server\.|^\+server\./.test(entry.name)) {
63
- fail(`${path} needs a server, and there is none: the app runs entirely in the window. Use +page.js/+page.ts instead.`);
64
- }
65
- if (match === null || (match[1] === 'error' && match[2] !== 'svelte')) {
66
- fail(`${path} is not a route file this renderer knows.`);
67
- }
68
- const kind = match[2] === 'svelte' ? `${match[1]}.svelte` : `${match[1]}.module`;
69
- if (found[kind]) fail(`${path} and ${found[kind]} are the same route file twice.`);
70
- found[kind] = path;
71
- files.push(path);
72
- }
73
-
74
- if (found['layout.svelte'] || found['layout.module']) {
75
- layouts = [...layouts, { component: found['layout.svelte'] ?? null, module: found['layout.module'] ?? null }];
76
- }
77
- // After the layout: an error page renders inside the layout of its own directory.
78
- if (found['error.svelte']) {
79
- error = found['error.svelte'];
80
- error_depth = layouts.length;
81
- }
82
- if (id_parts.length === 0) fallback = { layouts, error };
83
-
84
- if (found['page.module'] && !found['page.svelte']) {
85
- fail(`${found['page.module']} has no +page.svelte next to it.`);
86
- }
87
- if (found['page.svelte']) {
88
- routes.push({
89
- id: '/' + id_parts.join('/'),
90
- segments: id_parts.filter((part) => !/^\(.*\)$/.test(part)),
91
- layouts,
92
- page: { component: found['page.svelte'], module: found['page.module'] ?? null },
93
- error,
94
- error_depth
95
- });
96
- }
97
-
98
- for (const entry of entries) {
99
- if (!entry.isDirectory()) continue;
100
- const path = `${current}/${entry.name}`;
101
- if (/\[\[|\]\]|=/.test(entry.name)) {
102
- fail(`${path}: optional parameters ([[name]]) and matchers ([name=matcher]) are not supported.`);
103
- }
104
- walk(path, [...id_parts, entry.name], layouts, error, error_depth);
105
- }
106
- }
107
-
108
- // With `/` on Windows too: the files are imported by these paths, and that
109
- // is how Vite writes a module's id.
110
- walk(dir.replaceAll('\\', '/'), [], [], null, 0);
111
-
112
- const seen = new Map();
113
- for (const route of routes) {
114
- const path = '/' + route.segments.join('/');
115
- if (seen.has(path)) fail(`${route.id} and ${seen.get(path)} are both the page for ${path}.`);
116
- seen.set(path, route.id);
117
- }
118
-
119
- routes.sort(by_specificity);
120
- return { routes, fallback, files };
121
- }
122
-
123
- /** 0 for fixed text, 1 for a segment with a parameter, 2 for a rest parameter. @param {string} segment */
124
- const rank = (segment) => (segment.includes('[...') ? 2 : segment.includes('[') ? 1 : 0);
125
-
126
- /**
127
- * The first route that matches wins, so the more specific one has to come
128
- * first: `/items/new` before `/items/[id]` before `/items/[...rest]`.
129
- * @param {ScannedRoute} a
130
- * @param {ScannedRoute} b
131
- */
132
- function by_specificity(a, b) {
133
- const length = Math.max(a.segments.length, b.segments.length);
134
- for (let index = 0; index < length; index++) {
135
- // Running out of segments ranks between a parameter and a rest parameter:
136
- // `/docs` must not lose to `/docs/[...path]`, which also matches it.
137
- const [ra, rb] = [a, b].map((route) => (index < route.segments.length ? rank(route.segments[index]) : 1.5));
138
- if (ra !== rb) return ra - rb;
139
- }
140
- return a.id < b.id ? -1 : 1;
141
- }
142
-
143
- /**
144
- * @param {string[]} segments
145
- * @returns {{ pattern: string, names: string[] }} `pattern` is regular expression source
146
- */
147
- export function route_pattern(segments) {
148
- /** @type {string[]} */
149
- const names = [];
150
- let pattern = '';
151
- for (const segment of segments) {
152
- const rest = /^\[\.\.\.(\w+)\]$/.exec(segment);
153
- if (rest) {
154
- // Matches nothing as well: `/docs/[...path]` is also the page for `/docs`.
155
- names.push(rest[1]);
156
- pattern += '(?:/(.*))?';
157
- continue;
158
- }
159
- pattern += '/';
160
- // Text and parameters can share a segment: `v[major].[minor]`.
161
- for (const part of segment.split(/(\[\w+\])/)) {
162
- const param = /^\[(\w+)\]$/.exec(part);
163
- if (param) {
164
- names.push(param[1]);
165
- pattern += '([^/]+)';
166
- } else {
167
- pattern += part.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
168
- }
169
- }
170
- }
171
- return { pattern: `^${pattern || '/'}$`, names };
172
- }
173
-
174
- /**
175
- * The source of `virtual:sepal/routes`.
176
- * @param {string} dir absolute path of `src/routes`
177
- * @returns {{ code: string, files: string[] }} `files` are what the module was built from
178
- */
179
- export function generate_routes(dir) {
180
- const { routes, fallback, files } = scan_routes(dir);
181
- /** @type {string[]} */
182
- const imports = [];
183
- /** @type {Map<string, string>} */
184
- const names = new Map();
185
-
186
- /** A variable holding the default export (a component) or the whole module. @param {string | null} file @param {boolean} whole */
187
- const use = (file, whole) => {
188
- if (file === null) return 'null';
189
- let name = names.get(file);
190
- if (name === undefined) {
191
- name = `_${names.size}`;
192
- names.set(file, name);
193
- imports.push(`import ${whole ? '* as ' : ''}${name} from ${JSON.stringify(file)};`);
194
- }
195
- return name;
196
- };
197
- /** @param {NodeFiles} files */
198
- const node = (files) => {
199
- const module = use(files.module, true);
200
- return `{ component: ${use(files.component, false)}, load: ${module === 'null' ? 'undefined' : `${module}.load`} }`;
201
- };
202
- /** @param {NodeFiles[]} list */
203
- const nodes = (list) => `[${list.map(node).join(', ')}]`;
204
-
205
- const table = routes.map((route) => {
206
- const { pattern, names: params } = route_pattern(route.segments);
207
- return (
208
- `\t{ id: ${JSON.stringify(route.id)}, pattern: new RegExp(${JSON.stringify(pattern)}), names: ${JSON.stringify(params)}, ` +
209
- `layouts: ${nodes(route.layouts)}, page: ${node(route.page)}, ` +
210
- `error: ${use(route.error, false)}, error_depth: ${route.error_depth} }`
211
- );
212
- });
213
-
214
- const code =
215
- `${imports.join('\n')}\n\n` +
216
- `export const routes = [\n${table.join(',\n')}\n];\n\n` +
217
- `export const fallback = { layouts: ${nodes(fallback.layouts)}, error: ${use(fallback.error, false)} };\n`;
218
- return { code, files };
219
- }