orvyn-lang 0.2.0 → 0.4.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/GUIDE.md +198 -0
- package/LANGUAGE.md +818 -30
- package/README.md +211 -250
- package/brand/orvyn-sunset-animated.svg +15 -0
- package/package.json +3 -1
- package/src/cli/orvyn.js +207 -16
- package/src/core/signal.js +104 -6
- package/src/devtools/runtime.js +25 -1
- package/src/lang/a11y.js +152 -0
- package/src/lang/auth.js +239 -0
- package/src/lang/bundle-native.js +10 -6
- package/src/lang/codegen.js +615 -58
- package/src/lang/device.js +41 -0
- package/src/lang/doctor.js +60 -0
- package/src/lang/env.js +27 -0
- package/src/lang/errors.js +513 -0
- package/src/lang/form.js +69 -8
- package/src/lang/index.js +2 -1
- package/src/lang/lexer.js +2 -0
- package/src/lang/list.js +44 -0
- package/src/lang/native/android/MainActivity.kt +65 -4
- package/src/lang/native/android/OrvynDevice.kt +163 -0
- package/src/lang/native/android/OrvynEngine.kt +176 -7
- package/src/lang/native/android/OrvynRenderer.kt +970 -50
- package/src/lang/native/android.js +74 -11
- package/src/lang/native/assets.js +39 -0
- package/src/lang/native/build.js +140 -63
- package/src/lang/native/compatibility.js +57 -0
- package/src/lang/native/config.js +108 -0
- package/src/lang/native/ios/OrvynApp.swift +6 -0
- package/src/lang/native/ios/OrvynEngine.swift +291 -4
- package/src/lang/native/ios/OrvynViews.swift +769 -41
- package/src/lang/native/ios.js +81 -2
- package/src/lang/native-runtime.js +541 -55
- package/src/lang/native-size.js +53 -0
- package/src/lang/page-files.js +71 -0
- package/src/lang/page.js +63 -0
- package/src/lang/parser.js +278 -15
- package/src/lang/prerender.js +300 -0
- package/src/lang/read-import.js +12 -0
- package/src/lang/router.js +266 -0
- package/src/lang/runtime-shared.js +796 -10
- package/src/lang/runtime.js +399 -51
- package/src/lang/select.js +13 -0
- package/src/lang/server-code.js +233 -0
- package/src/lang/server-export.js +78 -0
- package/src/lang/server-libs.js +53 -0
- package/src/lang/server.js +409 -0
- package/src/lang/style-check.js +60 -0
- package/src/lang/test-runner.js +134 -0
- package/src/lang/types.js +317 -0
- package/src/lang/vite-plugin.js +108 -6
- package/src/lang/web-overlay.js +578 -0
- package/src/lang/widgets.js +94 -0
- package/src/lang/words.js +38 -0
- package/src/runtime/animations.js +24 -0
- package/src/runtime/appear.js +73 -0
- package/src/runtime/marquee.js +57 -0
- package/src/runtime/mount.js +120 -27
- package/src/runtime/patch.js +90 -11
- package/src/runtime/style.js +50 -9
- package/src/styling/fluid.js +129 -6
- package/src/styling/spec.js +319 -0
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { runInNewContext } from "node:vm";
|
|
5
|
+
import { orvynLang } from "./vite-plugin.js";
|
|
6
|
+
import { configFile } from "./native/config.js";
|
|
7
|
+
const AI_CRAWLERS = ["GPTBot", "ClaudeBot", "Google-Extended", "PerplexityBot", "CCBot", "Applebot-Extended"];
|
|
8
|
+
const VOID = /* @__PURE__ */ new Set(["img", "input", "br", "hr", "meta", "link"]);
|
|
9
|
+
const UNITLESS_TEXT = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
10
|
+
class Node_ {
|
|
11
|
+
childNodes = [];
|
|
12
|
+
parentNode = null;
|
|
13
|
+
attributes = /* @__PURE__ */ new Map();
|
|
14
|
+
data = "";
|
|
15
|
+
value = "";
|
|
16
|
+
disabled = false;
|
|
17
|
+
checked = false;
|
|
18
|
+
style = {
|
|
19
|
+
setProperty(name, value) {
|
|
20
|
+
this[name] = value;
|
|
21
|
+
},
|
|
22
|
+
removeProperty(name) {
|
|
23
|
+
delete this[name];
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
classList = {
|
|
27
|
+
add: (name) => this.setAttribute("class", [this.getAttribute("class"), name].filter(Boolean).join(" "))
|
|
28
|
+
};
|
|
29
|
+
nodeName;
|
|
30
|
+
constructor(nodeName) {
|
|
31
|
+
this.nodeName = nodeName;
|
|
32
|
+
}
|
|
33
|
+
get textContent() {
|
|
34
|
+
return this.nodeName === "#text" ? this.data : this.childNodes.map((n) => n.textContent).join("");
|
|
35
|
+
}
|
|
36
|
+
set textContent(value) {
|
|
37
|
+
if (this.nodeName === "#text") {
|
|
38
|
+
this.data = String(value);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
this.childNodes = [];
|
|
42
|
+
if (value !== "") this.appendChild(Object.assign(new Node_("#text"), { data: String(value) }));
|
|
43
|
+
}
|
|
44
|
+
appendChild(child) {
|
|
45
|
+
return this.insertBefore(child, null);
|
|
46
|
+
}
|
|
47
|
+
insertBefore(child, before) {
|
|
48
|
+
if (child.nodeName === "#fragment") {
|
|
49
|
+
for (const n of [...child.childNodes]) this.insertBefore(n, before);
|
|
50
|
+
return child;
|
|
51
|
+
}
|
|
52
|
+
child.remove();
|
|
53
|
+
const at = before ? this.childNodes.indexOf(before) : -1;
|
|
54
|
+
this.childNodes.splice(at < 0 ? this.childNodes.length : at, 0, child);
|
|
55
|
+
child.parentNode = this;
|
|
56
|
+
return child;
|
|
57
|
+
}
|
|
58
|
+
prepend(child) {
|
|
59
|
+
this.insertBefore(child, this.childNodes[0] ?? null);
|
|
60
|
+
}
|
|
61
|
+
replaceChild(next, old) {
|
|
62
|
+
this.insertBefore(next, old);
|
|
63
|
+
old.remove();
|
|
64
|
+
}
|
|
65
|
+
remove() {
|
|
66
|
+
if (!this.parentNode) return;
|
|
67
|
+
this.parentNode.childNodes.splice(this.parentNode.childNodes.indexOf(this), 1);
|
|
68
|
+
this.parentNode = null;
|
|
69
|
+
}
|
|
70
|
+
setAttribute(name, value) {
|
|
71
|
+
this.attributes.set(name, String(value));
|
|
72
|
+
}
|
|
73
|
+
getAttribute(name) {
|
|
74
|
+
return this.attributes.get(name) ?? null;
|
|
75
|
+
}
|
|
76
|
+
removeAttribute(name) {
|
|
77
|
+
this.attributes.delete(name);
|
|
78
|
+
}
|
|
79
|
+
addEventListener() {
|
|
80
|
+
}
|
|
81
|
+
removeEventListener() {
|
|
82
|
+
}
|
|
83
|
+
all() {
|
|
84
|
+
return [this, ...this.childNodes.flatMap((n) => n.all())];
|
|
85
|
+
}
|
|
86
|
+
querySelector(selector) {
|
|
87
|
+
const [, tag, name, value] = selector.match(/^(\w*)(?:\[([\w-]+)(?:="([^"]*)")?\])?$/) ?? [];
|
|
88
|
+
return this.all().slice(1).find((n) => (!tag || n.nodeName === tag) && (!name || (value === void 0 ? n.attributes.has(name) : n.getAttribute(name) === value))) ?? null;
|
|
89
|
+
}
|
|
90
|
+
toHTML() {
|
|
91
|
+
if (this.nodeName === "#text") return UNITLESS_TEXT(this.data);
|
|
92
|
+
const attributes = new Map(this.attributes);
|
|
93
|
+
const css = Object.entries(this.style).filter(([, v]) => typeof v === "string" && v !== "").map(([k, v]) => `${k.startsWith("--") ? k : k.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}:${v}`);
|
|
94
|
+
if (css.length) attributes.set("style", css.join(";"));
|
|
95
|
+
const open = `<${this.nodeName}${[...attributes].map(([k, v]) => ` ${k}="${UNITLESS_TEXT(v)}"`).join("")}>`;
|
|
96
|
+
if (VOID.has(this.nodeName)) return open;
|
|
97
|
+
const raw = this.nodeName === "style" || this.nodeName === "script";
|
|
98
|
+
const inside = raw ? this.textContent.replace(/<\//g, "<\\/") : this.childNodes.map((n) => n.toHTML()).join("");
|
|
99
|
+
return `${open}${inside}</${this.nodeName}>`;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function fakeDocument() {
|
|
103
|
+
const head = new Node_("head");
|
|
104
|
+
const body = new Node_("body");
|
|
105
|
+
return {
|
|
106
|
+
head,
|
|
107
|
+
body,
|
|
108
|
+
title: "",
|
|
109
|
+
createElement: (tag) => new Node_(tag.toLowerCase()),
|
|
110
|
+
createTextNode: (data) => Object.assign(new Node_("#text"), { data: String(data) }),
|
|
111
|
+
createDocumentFragment: () => new Node_("#fragment"),
|
|
112
|
+
getElementById: (id) => [head, body].flatMap((n) => n.all()).find((n) => n.getAttribute("id") === id) ?? null,
|
|
113
|
+
querySelector: (s) => head.querySelector(s) ?? body.querySelector(s)
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
async function bundle(entry, env) {
|
|
117
|
+
const { build } = await import("vite");
|
|
118
|
+
const ext = import.meta.url.endsWith(".ts") ? ".ts" : ".js";
|
|
119
|
+
const runtime = resolve(new URL(".", import.meta.url).pathname, `runtime${ext}`);
|
|
120
|
+
const result = await build({
|
|
121
|
+
configFile: false,
|
|
122
|
+
logLevel: "silent",
|
|
123
|
+
plugins: [orvynLang({ env, dev: false })],
|
|
124
|
+
resolve: { alias: [{ find: /^orvyn\/lang\/runtime$/, replacement: runtime }] },
|
|
125
|
+
define: { "import.meta.env.DEV": "false", "import.meta.env.PROD": "true" },
|
|
126
|
+
build: { write: false, minify: false, lib: { entry, formats: ["iife"], name: "OrvynApp", fileName: () => "app.js" }, rollupOptions: { output: { exports: "named" } } }
|
|
127
|
+
});
|
|
128
|
+
return (Array.isArray(result) ? result[0] : result).output.find((item) => item.type === "chunk").code;
|
|
129
|
+
}
|
|
130
|
+
function draw(code, path, site) {
|
|
131
|
+
const document = fakeDocument();
|
|
132
|
+
const location = { origin: site, pathname: path, search: "", hash: "" };
|
|
133
|
+
const network = { pending: 0, failed: [] };
|
|
134
|
+
const timers = /* @__PURE__ */ new Set();
|
|
135
|
+
const buildFetch = (url, init = {}) => {
|
|
136
|
+
const address = String(url);
|
|
137
|
+
const method = String(init.method ?? "GET").toUpperCase();
|
|
138
|
+
if (method !== "GET" || !/^https?:\/\//i.test(address)) return new Promise(() => {
|
|
139
|
+
});
|
|
140
|
+
network.pending++;
|
|
141
|
+
return fetch(address, { headers: init.headers, signal: AbortSignal.timeout(15e3) }).then((response) => {
|
|
142
|
+
if (!response.ok) network.failed.push(`${address} answered ${response.status}`);
|
|
143
|
+
return response;
|
|
144
|
+
}, (error) => {
|
|
145
|
+
network.failed.push(`${address}: ${error.message}`);
|
|
146
|
+
throw error;
|
|
147
|
+
}).finally(() => {
|
|
148
|
+
network.pending--;
|
|
149
|
+
});
|
|
150
|
+
};
|
|
151
|
+
const context = {
|
|
152
|
+
document,
|
|
153
|
+
location,
|
|
154
|
+
Node: Node_,
|
|
155
|
+
URL,
|
|
156
|
+
queueMicrotask,
|
|
157
|
+
performance,
|
|
158
|
+
window: { location, history: { pushState() {
|
|
159
|
+
}, replaceState() {
|
|
160
|
+
} }, addEventListener() {
|
|
161
|
+
}, removeEventListener() {
|
|
162
|
+
} },
|
|
163
|
+
fetch: buildFetch,
|
|
164
|
+
setTimeout: (fn, ms) => {
|
|
165
|
+
const t = setTimeout(fn, ms);
|
|
166
|
+
timers.add(t);
|
|
167
|
+
return t;
|
|
168
|
+
},
|
|
169
|
+
clearTimeout,
|
|
170
|
+
console: { log() {
|
|
171
|
+
}, warn() {
|
|
172
|
+
}, error() {
|
|
173
|
+
} }
|
|
174
|
+
};
|
|
175
|
+
context.globalThis = context;
|
|
176
|
+
runInNewContext(`${code}
|
|
177
|
+
globalThis.__app = OrvynApp`, context);
|
|
178
|
+
const target = document.createElement("div");
|
|
179
|
+
target.setAttribute("id", "app");
|
|
180
|
+
document.body.appendChild(target);
|
|
181
|
+
const stop = context.__app.mountApp(target);
|
|
182
|
+
const ready = async () => {
|
|
183
|
+
for (let quiet = 0; quiet < 5; ) {
|
|
184
|
+
await new Promise((resolve2) => setTimeout(resolve2, network.pending ? 20 : 1));
|
|
185
|
+
quiet = network.pending ? 0 : quiet + 1;
|
|
186
|
+
}
|
|
187
|
+
if (network.failed.length) throw new Error(`${path}: could not get the data. ${network.failed[0]}`);
|
|
188
|
+
};
|
|
189
|
+
const close = () => {
|
|
190
|
+
stop();
|
|
191
|
+
for (const timer of timers) clearTimeout(timer);
|
|
192
|
+
};
|
|
193
|
+
return { document, target, context, ready, close };
|
|
194
|
+
}
|
|
195
|
+
async function listed(name, screen) {
|
|
196
|
+
const values = await screen.__prebuild();
|
|
197
|
+
if (!Array.isArray(values)) throw new Error(`prebuild in ${name} must be a list, like [1, 2, 3]`);
|
|
198
|
+
return values.map((value) => {
|
|
199
|
+
const one = String(value && typeof value === "object" ? value[screen.__params[0]] : value);
|
|
200
|
+
if (!/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/.test(one) || value == null) {
|
|
201
|
+
throw new Error(`prebuild in ${name}: "${one}" can't be part of an address. Use letters, numbers, - and _`);
|
|
202
|
+
}
|
|
203
|
+
return `/${name.toLowerCase()}/${one}`;
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
async function renderPages(entry, options = {}) {
|
|
207
|
+
const code = await bundle(resolve(entry), options.env);
|
|
208
|
+
const site = (options.site ?? "").replace(/\/$/, "");
|
|
209
|
+
const first = draw(code, "/", site);
|
|
210
|
+
const screens = first.context.__app.screens;
|
|
211
|
+
const home = screens.App ?? screens.Home ?? Object.entries(screens).find(([name]) => !["NotFound", "ErrorPage"].includes(name))?.[1];
|
|
212
|
+
const paths = [];
|
|
213
|
+
try {
|
|
214
|
+
for (const [name, screen] of Object.entries(screens)) {
|
|
215
|
+
if (["NotFound", "ErrorPage"].includes(name) || screen.__requiresAuth) continue;
|
|
216
|
+
if (screen.__prebuild) paths.push(...await listed(name, screen));
|
|
217
|
+
else if (!screen.__params?.length) paths.push(screen === home ? "/" : `/${name.toLowerCase()}`);
|
|
218
|
+
}
|
|
219
|
+
} finally {
|
|
220
|
+
first.close();
|
|
221
|
+
}
|
|
222
|
+
if (screens.NotFound) paths.push("/404");
|
|
223
|
+
const pages = [];
|
|
224
|
+
for (const path of paths) {
|
|
225
|
+
const { document, target, ready, close } = draw(code, path, site);
|
|
226
|
+
try {
|
|
227
|
+
await ready();
|
|
228
|
+
const questions = target.all().filter((n) => n.getAttribute("data-orvyn-question") !== null).map((n) => ({
|
|
229
|
+
"@type": "Question",
|
|
230
|
+
name: n.getAttribute("data-orvyn-question"),
|
|
231
|
+
acceptedAnswer: { "@type": "Answer", text: n.childNodes.slice(1).map((c) => c.textContent).join(" ").trim() }
|
|
232
|
+
}));
|
|
233
|
+
const faq = questions.length ? `<script type="application/ld+json">${JSON.stringify({ "@context": "https://schema.org", "@type": "FAQPage", mainEntity: questions }).replace(/</g, "\\u003c")}<\/script>` : "";
|
|
234
|
+
pages.push({
|
|
235
|
+
path,
|
|
236
|
+
title: document.title,
|
|
237
|
+
noindex: path === "/404" || Boolean(document.head.querySelector('meta[name="robots"]')),
|
|
238
|
+
head: document.head.childNodes.filter((n) => n.nodeName !== "title").map((n) => n.toHTML()).join("\n") + faq,
|
|
239
|
+
body: target.childNodes.map((n) => n.toHTML()).join("")
|
|
240
|
+
});
|
|
241
|
+
} finally {
|
|
242
|
+
close();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return { pages, site };
|
|
246
|
+
}
|
|
247
|
+
function insertPage(template, page) {
|
|
248
|
+
let html = template;
|
|
249
|
+
if (page.title) {
|
|
250
|
+
html = html.replace(/<title>[\s\S]*?<\/title>/, () => `<title>${UNITLESS_TEXT(page.title)}</title>`);
|
|
251
|
+
}
|
|
252
|
+
html = html.replace("</head>", () => `${page.head}
|
|
253
|
+
</head>`);
|
|
254
|
+
const target = /<div id="app">\s*<\/div>/;
|
|
255
|
+
if (!target.test(html)) throw new Error(`index.html needs an empty <div id="app"></div>`);
|
|
256
|
+
return html.replace(target, () => `<div id="app" class="orvyn-app" data-orvyn-static>${page.body}</div>`);
|
|
257
|
+
}
|
|
258
|
+
async function prerender(cwd, entry, outDir, env) {
|
|
259
|
+
const path = configFile(cwd);
|
|
260
|
+
const config = path ? (await import(pathToFileURL(path).href)).default ?? {} : {};
|
|
261
|
+
const template = readFileSync(join(outDir, "index.html"), "utf-8");
|
|
262
|
+
const { pages, site } = await renderPages(entry, { env, site: config.site });
|
|
263
|
+
const written = [];
|
|
264
|
+
const write = (file, content) => {
|
|
265
|
+
mkdirSync(join(outDir, file, ".."), { recursive: true });
|
|
266
|
+
writeFileSync(join(outDir, file), content);
|
|
267
|
+
written.push(file);
|
|
268
|
+
};
|
|
269
|
+
write("app.html", template);
|
|
270
|
+
for (const page of pages) {
|
|
271
|
+
const file = page.path === "/" ? "index.html" : page.path === "/404" ? "404.html" : `${page.path.slice(1)}/index.html`;
|
|
272
|
+
write(file, insertPage(template, page));
|
|
273
|
+
}
|
|
274
|
+
const mine = (file) => existsSync(join(cwd, "public", file));
|
|
275
|
+
if (site && !mine("sitemap.xml")) {
|
|
276
|
+
const urls = pages.filter((p) => !p.noindex).map((p) => ` <url><loc>${UNITLESS_TEXT(site + p.path)}</loc></url>`);
|
|
277
|
+
write("sitemap.xml", `<?xml version="1.0" encoding="UTF-8"?>
|
|
278
|
+
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
279
|
+
${urls.join("\n")}
|
|
280
|
+
</urlset>
|
|
281
|
+
`);
|
|
282
|
+
}
|
|
283
|
+
if (!mine("robots.txt")) {
|
|
284
|
+
const blocked = config.seo?.allowAI === false ? AI_CRAWLERS.map((bot) => `User-agent: ${bot}
|
|
285
|
+
Disallow: /
|
|
286
|
+
|
|
287
|
+
`).join("") : "";
|
|
288
|
+
write("robots.txt", `${blocked}User-agent: *
|
|
289
|
+
Allow: /
|
|
290
|
+
${site ? `
|
|
291
|
+
Sitemap: ${site}/sitemap.xml
|
|
292
|
+
` : ""}`);
|
|
293
|
+
}
|
|
294
|
+
return written;
|
|
295
|
+
}
|
|
296
|
+
export {
|
|
297
|
+
insertPage,
|
|
298
|
+
prerender,
|
|
299
|
+
renderPages
|
|
300
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
function readImportFrom(file) {
|
|
4
|
+
return (path) => {
|
|
5
|
+
const base = resolve(dirname(file), path.endsWith(".orv") ? path : `${path}.orv`);
|
|
6
|
+
const full = existsSync(base) ? base : resolve(dirname(file), path, "index.orv");
|
|
7
|
+
return existsSync(full) ? { source: readFileSync(full, "utf-8"), resolve: readImportFrom(full) } : null;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
export {
|
|
11
|
+
readImportFrom
|
|
12
|
+
};
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { signal } from "../core/signal.js";
|
|
2
|
+
import { enterScreen } from "./runtime-shared.js";
|
|
3
|
+
function decodeParam(raw) {
|
|
4
|
+
if (raw === "true") return true;
|
|
5
|
+
if (raw === "false") return false;
|
|
6
|
+
if (raw === "null") return null;
|
|
7
|
+
if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(raw)) {
|
|
8
|
+
const num = Number(raw);
|
|
9
|
+
if (Number.isSafeInteger(num) || raw.includes(".")) return num;
|
|
10
|
+
}
|
|
11
|
+
return raw;
|
|
12
|
+
}
|
|
13
|
+
function decodeText(raw) {
|
|
14
|
+
try {
|
|
15
|
+
return decodeURIComponent(raw);
|
|
16
|
+
} catch {
|
|
17
|
+
return raw;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function normalizeScreenParams(screen, arg) {
|
|
21
|
+
if (arg === void 0 || arg === null) return {};
|
|
22
|
+
if (typeof arg === "object" && !Array.isArray(arg)) {
|
|
23
|
+
return { ...arg };
|
|
24
|
+
}
|
|
25
|
+
const paramName = screen.__params?.[0] ?? "value";
|
|
26
|
+
return { [paramName]: arg };
|
|
27
|
+
}
|
|
28
|
+
function formatRouteUrl(screen, params, entryScreen) {
|
|
29
|
+
const name = screen.__name ?? screen.name;
|
|
30
|
+
if (name === "NotFound" && typeof params.url === "string" && params.url.startsWith("/")) {
|
|
31
|
+
return params.url;
|
|
32
|
+
}
|
|
33
|
+
const isEntry = entryScreen && screen === entryScreen;
|
|
34
|
+
const slug = isEntry ? "/" : `/${name.toLowerCase()}`;
|
|
35
|
+
const pairs = [];
|
|
36
|
+
for (const [key, value] of Object.entries(params)) {
|
|
37
|
+
if (value === void 0) continue;
|
|
38
|
+
const serialized = typeof value === "object" && value !== null ? JSON.stringify(value) : String(value);
|
|
39
|
+
pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(serialized)}`);
|
|
40
|
+
}
|
|
41
|
+
return pairs.length ? `${slug}?${pairs.join("&")}` : slug;
|
|
42
|
+
}
|
|
43
|
+
function parseRouteUrl(rawUrl, screens, entryScreen) {
|
|
44
|
+
if (!rawUrl) return null;
|
|
45
|
+
let pathAndQuery = rawUrl.trim();
|
|
46
|
+
const hashIdx = pathAndQuery.indexOf("#");
|
|
47
|
+
if (hashIdx >= 0) {
|
|
48
|
+
pathAndQuery = pathAndQuery.slice(hashIdx + 1);
|
|
49
|
+
} else {
|
|
50
|
+
const schemeMatch = pathAndQuery.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/(.*)$/);
|
|
51
|
+
if (schemeMatch) {
|
|
52
|
+
const rest = schemeMatch[2];
|
|
53
|
+
const scheme = schemeMatch[1].toLowerCase();
|
|
54
|
+
if (scheme === "http" || scheme === "https") {
|
|
55
|
+
const slash = rest.indexOf("/");
|
|
56
|
+
pathAndQuery = slash >= 0 ? rest.slice(slash) : "/";
|
|
57
|
+
} else {
|
|
58
|
+
pathAndQuery = "/" + rest.replace(/^\/+/, "");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (!pathAndQuery) return null;
|
|
63
|
+
const [rawPath, rawQuery = ""] = pathAndQuery.split("?");
|
|
64
|
+
const segments = rawPath.split("/").filter(Boolean);
|
|
65
|
+
let matched = null;
|
|
66
|
+
const params = {};
|
|
67
|
+
if (segments.length === 0) {
|
|
68
|
+
matched = entryScreen;
|
|
69
|
+
} else {
|
|
70
|
+
const first = segments[0].toLowerCase();
|
|
71
|
+
for (const [name, fn] of Object.entries(screens)) {
|
|
72
|
+
if (name.toLowerCase() === first) {
|
|
73
|
+
matched = fn;
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (matched && segments.length > 1) {
|
|
78
|
+
const paramName = matched.__params?.[0] ?? "id";
|
|
79
|
+
params[paramName] = decodeParam(decodeText(segments[1]));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (!matched) {
|
|
83
|
+
if (!screens.NotFound) return null;
|
|
84
|
+
const url = `/${segments.join("/")}${rawQuery ? `?${rawQuery}` : ""}`;
|
|
85
|
+
return { screen: screens.NotFound, params: { url } };
|
|
86
|
+
}
|
|
87
|
+
if (rawQuery) {
|
|
88
|
+
for (const part of rawQuery.split("&")) {
|
|
89
|
+
if (!part) continue;
|
|
90
|
+
const eq = part.indexOf("=");
|
|
91
|
+
const rawKey = eq >= 0 ? part.slice(0, eq) : part;
|
|
92
|
+
const rawVal = eq >= 0 ? part.slice(eq + 1) : "";
|
|
93
|
+
const key = decodeText(rawKey.replace(/\+/g, " "));
|
|
94
|
+
const val = decodeText(rawVal.replace(/\+/g, " "));
|
|
95
|
+
params[key] = decodeParam(val);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return { screen: matched, params };
|
|
99
|
+
}
|
|
100
|
+
function createRouter() {
|
|
101
|
+
const route = signal(null, "__orvyn_route");
|
|
102
|
+
const historyIndexSignal = signal(0, "__orvyn_history_index");
|
|
103
|
+
let stack = [];
|
|
104
|
+
let index = -1;
|
|
105
|
+
let visitCounter = 0;
|
|
106
|
+
let entryScreen = null;
|
|
107
|
+
let screenMap = {};
|
|
108
|
+
let adapter = {};
|
|
109
|
+
let guard = null;
|
|
110
|
+
const guarded = (screen, params) => {
|
|
111
|
+
const redirect = guard?.(screen, params);
|
|
112
|
+
return redirect && redirect !== screen ? { screen: redirect, params: {} } : { screen, params };
|
|
113
|
+
};
|
|
114
|
+
const makeEntry = (screen, params) => ({
|
|
115
|
+
screen,
|
|
116
|
+
params,
|
|
117
|
+
key: `${screen.name || "Screen"}#${++visitCounter}`
|
|
118
|
+
});
|
|
119
|
+
const applyEntry = (next, isSameScreen) => {
|
|
120
|
+
if (!isSameScreen) enterScreen();
|
|
121
|
+
route.set(next);
|
|
122
|
+
historyIndexSignal.set(index);
|
|
123
|
+
};
|
|
124
|
+
function start(entry, screens = {}, initialParams = {}, nextAdapter = {}) {
|
|
125
|
+
entryScreen = entry;
|
|
126
|
+
screenMap = Object.keys(screens).length ? screens : { [entry.name || "Home"]: entry };
|
|
127
|
+
adapter = nextAdapter;
|
|
128
|
+
stack = [];
|
|
129
|
+
index = -1;
|
|
130
|
+
let startScreen = entry;
|
|
131
|
+
let startParams = { ...initialParams };
|
|
132
|
+
const initialUrl = adapter.getInitialUrl?.();
|
|
133
|
+
if (initialUrl) {
|
|
134
|
+
const parsed = parseRouteUrl(initialUrl, screenMap, entryScreen);
|
|
135
|
+
if (parsed) {
|
|
136
|
+
startScreen = parsed.screen;
|
|
137
|
+
startParams = { ...startParams, ...parsed.params };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
;
|
|
141
|
+
({ screen: startScreen, params: startParams } = guarded(startScreen, startParams));
|
|
142
|
+
const first = makeEntry(startScreen, startParams);
|
|
143
|
+
stack = [first];
|
|
144
|
+
index = 0;
|
|
145
|
+
enterScreen();
|
|
146
|
+
route.set(first);
|
|
147
|
+
historyIndexSignal.set(0);
|
|
148
|
+
adapter.replaceUrl?.(formatRouteUrl(startScreen, startParams, entryScreen), { __orvynIndex: 0 });
|
|
149
|
+
}
|
|
150
|
+
function go(screen, paramOrProps) {
|
|
151
|
+
if (typeof screen !== "function") {
|
|
152
|
+
throw new Error("[Orvyn] go() needs a screen, like go(Home)");
|
|
153
|
+
}
|
|
154
|
+
let target = screen;
|
|
155
|
+
let params = normalizeScreenParams(target, paramOrProps);
|
|
156
|
+
({ screen: target, params } = guarded(target, params));
|
|
157
|
+
const current2 = route.get();
|
|
158
|
+
const isIdentical = current2 && current2.screen === target && JSON.stringify(current2.params) === JSON.stringify(params);
|
|
159
|
+
if (isIdentical) return;
|
|
160
|
+
const next = makeEntry(target, params);
|
|
161
|
+
stack = stack.slice(0, index + 1);
|
|
162
|
+
stack.push(next);
|
|
163
|
+
index = stack.length - 1;
|
|
164
|
+
applyEntry(next, false);
|
|
165
|
+
adapter.pushUrl?.(formatRouteUrl(target, params, entryScreen), { __orvynIndex: index });
|
|
166
|
+
}
|
|
167
|
+
function canGoBack() {
|
|
168
|
+
return historyIndexSignal.get() > 0;
|
|
169
|
+
}
|
|
170
|
+
function back(fallback, paramOrProps) {
|
|
171
|
+
if (index <= 0) {
|
|
172
|
+
if (typeof fallback === "function") {
|
|
173
|
+
go(fallback, paramOrProps);
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
if (adapter.goBack?.()) return true;
|
|
179
|
+
index -= 1;
|
|
180
|
+
const target = stack[index];
|
|
181
|
+
applyEntry(target, false);
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
function handlePopState(state, currentUrl) {
|
|
185
|
+
if (state && typeof state.__orvynIndex === "number") {
|
|
186
|
+
const nextIdx = state.__orvynIndex;
|
|
187
|
+
if (nextIdx >= 0 && nextIdx < stack.length) {
|
|
188
|
+
index = nextIdx;
|
|
189
|
+
applyEntry(stack[index], false);
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (currentUrl) {
|
|
194
|
+
const parsed = parseRouteUrl(currentUrl, screenMap, entryScreen);
|
|
195
|
+
if (parsed) {
|
|
196
|
+
const allowed = guarded(parsed.screen, parsed.params);
|
|
197
|
+
const next = makeEntry(allowed.screen, allowed.params);
|
|
198
|
+
stack = [next];
|
|
199
|
+
index = 0;
|
|
200
|
+
applyEntry(next, false);
|
|
201
|
+
return true;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
function openUrl(rawUrl) {
|
|
207
|
+
const parsed = parseRouteUrl(rawUrl, screenMap, entryScreen);
|
|
208
|
+
if (!parsed) return false;
|
|
209
|
+
go(parsed.screen, parsed.params);
|
|
210
|
+
return parsed.screen !== screenMap.NotFound;
|
|
211
|
+
}
|
|
212
|
+
function replace(screen, paramOrProps) {
|
|
213
|
+
const allowed = guarded(screen, normalizeScreenParams(screen, paramOrProps));
|
|
214
|
+
const next = makeEntry(allowed.screen, allowed.params);
|
|
215
|
+
if (index < 0) {
|
|
216
|
+
stack = [next];
|
|
217
|
+
index = 0;
|
|
218
|
+
} else {
|
|
219
|
+
stack = [...stack.slice(0, index), next];
|
|
220
|
+
}
|
|
221
|
+
applyEntry(next, false);
|
|
222
|
+
adapter.replaceUrl?.(formatRouteUrl(allowed.screen, allowed.params, entryScreen), { __orvynIndex: index });
|
|
223
|
+
}
|
|
224
|
+
function resetTo(screen, paramOrProps) {
|
|
225
|
+
const params = normalizeScreenParams(screen, paramOrProps);
|
|
226
|
+
const next = makeEntry(screen, params);
|
|
227
|
+
stack = [next];
|
|
228
|
+
index = 0;
|
|
229
|
+
applyEntry(next, false);
|
|
230
|
+
adapter.replaceUrl?.(formatRouteUrl(screen, params, entryScreen), { __orvynIndex: 0 });
|
|
231
|
+
}
|
|
232
|
+
function setGuard(next) {
|
|
233
|
+
guard = next;
|
|
234
|
+
}
|
|
235
|
+
function current() {
|
|
236
|
+
return route.get();
|
|
237
|
+
}
|
|
238
|
+
function reset() {
|
|
239
|
+
stack = [];
|
|
240
|
+
index = -1;
|
|
241
|
+
entryScreen = null;
|
|
242
|
+
screenMap = {};
|
|
243
|
+
adapter = {};
|
|
244
|
+
route.set(null);
|
|
245
|
+
historyIndexSignal.set(0);
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
start,
|
|
249
|
+
go,
|
|
250
|
+
back,
|
|
251
|
+
canGoBack,
|
|
252
|
+
handlePopState,
|
|
253
|
+
openUrl,
|
|
254
|
+
replace,
|
|
255
|
+
resetTo,
|
|
256
|
+
setGuard,
|
|
257
|
+
current,
|
|
258
|
+
reset
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
export {
|
|
262
|
+
createRouter,
|
|
263
|
+
formatRouteUrl,
|
|
264
|
+
normalizeScreenParams,
|
|
265
|
+
parseRouteUrl
|
|
266
|
+
};
|