orvyn-lang 0.2.0 → 0.3.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 (55) hide show
  1. package/GUIDE.md +149 -0
  2. package/LANGUAGE.md +744 -27
  3. package/README.md +211 -250
  4. package/brand/orvyn-sunset-animated.svg +15 -0
  5. package/package.json +3 -1
  6. package/src/cli/orvyn.js +186 -10
  7. package/src/core/signal.js +104 -6
  8. package/src/devtools/runtime.js +25 -1
  9. package/src/lang/a11y.js +102 -0
  10. package/src/lang/auth.js +239 -0
  11. package/src/lang/bundle-native.js +10 -6
  12. package/src/lang/codegen.js +428 -57
  13. package/src/lang/device.js +41 -0
  14. package/src/lang/doctor.js +60 -0
  15. package/src/lang/env.js +27 -0
  16. package/src/lang/errors.js +513 -0
  17. package/src/lang/form.js +69 -8
  18. package/src/lang/index.js +2 -1
  19. package/src/lang/lexer.js +2 -0
  20. package/src/lang/list.js +44 -0
  21. package/src/lang/native/android/MainActivity.kt +43 -4
  22. package/src/lang/native/android/OrvynDevice.kt +163 -0
  23. package/src/lang/native/android/OrvynEngine.kt +154 -7
  24. package/src/lang/native/android/OrvynRenderer.kt +518 -44
  25. package/src/lang/native/android.js +74 -11
  26. package/src/lang/native/build.js +130 -60
  27. package/src/lang/native/config.js +108 -0
  28. package/src/lang/native/ios/OrvynApp.swift +6 -0
  29. package/src/lang/native/ios/OrvynEngine.swift +266 -4
  30. package/src/lang/native/ios/OrvynViews.swift +429 -34
  31. package/src/lang/native/ios.js +75 -2
  32. package/src/lang/native-runtime.js +406 -56
  33. package/src/lang/page.js +52 -0
  34. package/src/lang/parser.js +243 -15
  35. package/src/lang/prerender.js +300 -0
  36. package/src/lang/read-import.js +11 -0
  37. package/src/lang/router.js +266 -0
  38. package/src/lang/runtime-shared.js +792 -10
  39. package/src/lang/runtime.js +362 -52
  40. package/src/lang/select.js +13 -0
  41. package/src/lang/server-code.js +233 -0
  42. package/src/lang/server-export.js +78 -0
  43. package/src/lang/server-libs.js +53 -0
  44. package/src/lang/server.js +409 -0
  45. package/src/lang/test-runner.js +134 -0
  46. package/src/lang/types.js +312 -0
  47. package/src/lang/vite-plugin.js +82 -3
  48. package/src/lang/web-overlay.js +578 -0
  49. package/src/lang/widgets.js +94 -0
  50. package/src/lang/words.js +38 -0
  51. package/src/runtime/mount.js +116 -27
  52. package/src/runtime/patch.js +90 -11
  53. package/src/runtime/style.js +11 -1
  54. package/src/styling/fluid.js +91 -4
  55. package/src/styling/spec.js +306 -0
@@ -0,0 +1,239 @@
1
+ import { signal } from "../core/signal.js";
2
+ const TOKEN = "__auth_token";
3
+ const REFRESH = "__auth_refresh";
4
+ const USER = "__auth_user";
5
+ function originOf(address) {
6
+ const found = String(address).match(/^(https?):\/\/([a-z0-9.-]+|\[[0-9a-f:]+\])(?::(\d{1,5}))?(?=[\/?#]|$)/i);
7
+ if (!found) return null;
8
+ const scheme = found[1].toLowerCase();
9
+ const port = found[3] && Number(found[3]) !== (scheme === "https" ? 443 : 80) ? `:${Number(found[3])}` : "";
10
+ return `${scheme}://${found[2].toLowerCase()}${port}`;
11
+ }
12
+ function isUnauthorized(error) {
13
+ return Number(error?.status) === 401;
14
+ }
15
+ function createAuth(secure, deps = {}) {
16
+ let config = {};
17
+ let router = null;
18
+ let pending = null;
19
+ let refreshing = null;
20
+ let rawFetch = null;
21
+ const readUser = () => {
22
+ const raw = secure.get(USER);
23
+ if (raw == null) return null;
24
+ try {
25
+ return JSON.parse(raw);
26
+ } catch {
27
+ return null;
28
+ }
29
+ };
30
+ const tokenSig = signal(secure.get(TOKEN), "__orvyn_auth_token");
31
+ const userSig = signal(readUser(), "__orvyn_auth_user");
32
+ const errorSig = signal("", "__orvyn_auth_error");
33
+ function store(token, refresh, user) {
34
+ if (token) secure.set(TOKEN, token);
35
+ else secure.remove(TOKEN);
36
+ if (refresh !== void 0) {
37
+ if (refresh) secure.set(REFRESH, refresh);
38
+ else secure.remove(REFRESH);
39
+ }
40
+ if (user !== void 0) {
41
+ if (user == null) secure.remove(USER);
42
+ else secure.set(USER, JSON.stringify(user));
43
+ userSig.set(user ?? null);
44
+ }
45
+ tokenSig.set(token);
46
+ }
47
+ function normalize(input) {
48
+ const out = { ...input };
49
+ const alias = (from, to) => {
50
+ if (from in out) {
51
+ if (!(to in out)) out[to] = out[from];
52
+ delete out[from];
53
+ }
54
+ };
55
+ alias("login", "loginScreen");
56
+ alias("home", "homeScreen");
57
+ alias("logout", "logoutScreen");
58
+ if (typeof out.refresh === "string") {
59
+ out.refreshUrl = out.refresh;
60
+ delete out.refresh;
61
+ }
62
+ if ("api" in out) {
63
+ out.apiOrigins = [...out.apiOrigins || [], ...Array.isArray(out.api) ? out.api : [out.api]];
64
+ delete out.api;
65
+ }
66
+ for (const key of ["loginScreen", "homeScreen", "logoutScreen"]) {
67
+ if (key in out && typeof out[key] !== "function") {
68
+ throw new Error(`[Orvyn] auth ${key.replace("Screen", "")}: needs a screen, like login: Login`);
69
+ }
70
+ }
71
+ return out;
72
+ }
73
+ function setup(input = {}) {
74
+ const next = normalize(input);
75
+ config = { ...config, ...next };
76
+ const current = router?.current();
77
+ if (current && config.loginScreen && current.screen.__requiresAuth && !tokenSig.get()) {
78
+ pending = { screen: current.screen, params: current.params };
79
+ router.replace(config.loginScreen);
80
+ }
81
+ }
82
+ function login(tokenOrData, refresh, user) {
83
+ let token = tokenOrData;
84
+ if (tokenOrData && typeof tokenOrData === "object") {
85
+ token = tokenOrData.token ?? tokenOrData.accessToken ?? tokenOrData.access_token;
86
+ refresh = tokenOrData.refresh ?? tokenOrData.refreshToken ?? tokenOrData.refresh_token ?? refresh;
87
+ user = tokenOrData.user ?? user;
88
+ }
89
+ if (typeof token !== "string" || !token) {
90
+ throw new Error("[Orvyn] auth.login() needs a token, like auth.login(res.token)");
91
+ }
92
+ errorSig.set("");
93
+ store(token, refresh ?? null, user ?? null);
94
+ const target = pending;
95
+ pending = null;
96
+ if (router) {
97
+ if (target) router.replace(target.screen, target.params);
98
+ else if (config.homeScreen) router.replace(config.homeScreen);
99
+ }
100
+ }
101
+ function logout() {
102
+ const wasLoggedIn = Boolean(tokenSig.get());
103
+ store(null, null, null);
104
+ pending = null;
105
+ refreshing = null;
106
+ if (!config.keepSaved) try {
107
+ deps.onLogoutReset?.();
108
+ } catch {
109
+ }
110
+ try {
111
+ config.onLogout?.();
112
+ } catch (error) {
113
+ console.warn("[Orvyn] auth onLogout failed:", error);
114
+ }
115
+ const to = config.logoutScreen ?? config.loginScreen;
116
+ if (router && to && (wasLoggedIn || router.current()?.screen !== to)) router.resetTo(to);
117
+ }
118
+ function setUser(user) {
119
+ if (user == null) secure.remove(USER);
120
+ else secure.set(USER, JSON.stringify(user));
121
+ userSig.set(user ?? null);
122
+ }
123
+ function mayReceiveToken(url) {
124
+ const s = String(url);
125
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(s) && !s.startsWith("//")) return true;
126
+ const origin = originOf(s.startsWith("//") ? `https:${s}` : s);
127
+ return origin !== null && (config.apiOrigins || []).some((o) => originOf(String(o)) === origin);
128
+ }
129
+ async function doRefresh() {
130
+ const refreshToken = secure.get(REFRESH);
131
+ if (!config.refresh && !(config.refreshUrl && refreshToken)) return false;
132
+ try {
133
+ const res = config.refresh ? await config.refresh(refreshToken) : await rawFetch(config.refreshUrl, { method: "POST", body: { refresh: refreshToken } });
134
+ const token = typeof res === "string" ? res : res?.token ?? res?.accessToken ?? res?.access_token;
135
+ if (typeof token !== "string" || !token) return false;
136
+ const nextRefresh = typeof res === "object" ? res.refresh ?? res.refreshToken ?? res.refresh_token : void 0;
137
+ store(token, nextRefresh === void 0 ? void 0 : nextRefresh);
138
+ return true;
139
+ } catch {
140
+ return false;
141
+ }
142
+ }
143
+ function refreshOnce() {
144
+ if (!refreshing) {
145
+ refreshing = doRefresh().finally(() => {
146
+ refreshing = null;
147
+ });
148
+ }
149
+ return refreshing;
150
+ }
151
+ function withAuthHeader(url, options) {
152
+ const token = tokenSig.get();
153
+ if (!token || options?.auth === false || options?.__noAuth || !mayReceiveToken(url)) return options;
154
+ const name = config.header || "Authorization";
155
+ const scheme = config.scheme ?? "Bearer ";
156
+ const headers = { ...options?.headers || {} };
157
+ const hasHeader = Object.keys(headers).some((k) => k.toLowerCase() === name.toLowerCase());
158
+ if (!hasHeader) headers[name] = `${scheme}${token}`;
159
+ return { ...options, headers };
160
+ }
161
+ function wrapFetch(fetchData) {
162
+ rawFetch = fetchData;
163
+ return async (url, options = {}) => {
164
+ const { auth: _auth, __noAuth: _noAuth, ...clean } = options || {};
165
+ void _auth;
166
+ void _noAuth;
167
+ const attached = withAuthHeader(url, options);
168
+ const sentToken = attached !== options;
169
+ const send = (opts) => {
170
+ const { auth: _a, __noAuth: _n, ...rest } = opts || {};
171
+ void _a;
172
+ void _n;
173
+ return fetchData(url, rest);
174
+ };
175
+ try {
176
+ return await send(sentToken ? attached : clean);
177
+ } catch (error) {
178
+ if (!sentToken || !isUnauthorized(error)) throw error;
179
+ const ok = await refreshOnce();
180
+ if (!ok) {
181
+ errorSig.set("Your session has expired. Please log in again.");
182
+ logout();
183
+ throw error;
184
+ }
185
+ try {
186
+ return await send(withAuthHeader(url, options));
187
+ } catch (retryError) {
188
+ if (isUnauthorized(retryError)) {
189
+ errorSig.set("Your session has expired. Please log in again.");
190
+ logout();
191
+ }
192
+ throw retryError;
193
+ }
194
+ }
195
+ };
196
+ }
197
+ function guard(screen, params) {
198
+ if (!screen.__requiresAuth || tokenSig.get()) return null;
199
+ if (!config.loginScreen) {
200
+ console.warn(`[Orvyn] ${screen.name || "This screen"} requires auth. Call auth.setup({ loginScreen: Login }) so users can log in.`);
201
+ return null;
202
+ }
203
+ pending = { screen, params };
204
+ return config.loginScreen;
205
+ }
206
+ return {
207
+ get isLoggedIn() {
208
+ return Boolean(tokenSig.get());
209
+ },
210
+ get token() {
211
+ return tokenSig.get();
212
+ },
213
+ get user() {
214
+ return userSig.get();
215
+ },
216
+ get error() {
217
+ return errorSig.get();
218
+ },
219
+ clearError() {
220
+ errorSig.set("");
221
+ },
222
+ setup,
223
+ login,
224
+ logout,
225
+ setUser,
226
+ refresh: refreshOnce,
227
+ // internal hooks for the runtimes
228
+ __wrapFetch: wrapFetch,
229
+ __guard: guard,
230
+ __attachRouter(next) {
231
+ router = next;
232
+ }
233
+ };
234
+ }
235
+ export {
236
+ createAuth,
237
+ isUnauthorized,
238
+ originOf
239
+ };
@@ -1,5 +1,5 @@
1
1
  import { fileURLToPath } from "node:url";
2
- import { resolve } from "node:path";
2
+ import { basename, dirname, resolve } from "node:path";
3
3
  import { orvynLang } from "./vite-plugin.js";
4
4
  const here = fileURLToPath(new URL(".", import.meta.url));
5
5
  const ext = import.meta.url.endsWith(".ts") ? ".ts" : ".js";
@@ -11,12 +11,15 @@ if (typeof console === "undefined") {
11
11
  this.console = { log: function () {}, error: function () {}, warn: function () {} };
12
12
  }
13
13
  `;
14
- async function bundleNative(entry) {
14
+ async function bundleNative(entry, options = {}) {
15
15
  const { build } = await import("vite");
16
+ const entryPath = resolve(entry);
17
+ const fallbackAppId = basename(entryPath, ".orv").toLowerCase().replace(/[^a-z0-9._-]/g, "") || "app";
18
+ const appId = options.appId || fallbackAppId;
16
19
  const result = await build({
17
20
  configFile: false,
18
21
  logLevel: "warn",
19
- plugins: [orvynLang()],
22
+ plugins: [orvynLang({ root: dirname(entryPath), dev: Boolean(options.dev), env: options.env, tests: options.tests })],
20
23
  resolve: {
21
24
  alias: [
22
25
  { find: /^orvyn\/lang\/runtime$/, replacement: resolve(here, `native-runtime${ext}`) }
@@ -28,7 +31,7 @@ async function bundleNative(entry) {
28
31
  target: "es2019",
29
32
  rollupOptions: { output: { exports: "named" } },
30
33
  lib: {
31
- entry: resolve(entry),
34
+ entry: entryPath,
32
35
  formats: ["iife"],
33
36
  name: "OrvynApp",
34
37
  fileName: () => "app.js"
@@ -38,8 +41,9 @@ async function bundleNative(entry) {
38
41
  const output = Array.isArray(result) ? result[0].output : result.output;
39
42
  const chunk = output.find((item) => item.type === "chunk");
40
43
  return `${PRELUDE}
41
- ${chunk.code}
42
- OrvynApp.mountApp(null);
44
+ var __orvynAppId = ${JSON.stringify(appId)};
45
+ ${options.dev ? "globalThis.__orvynDev = true;\n" : ""}${chunk.code}
46
+ var __orvynStop = OrvynApp.mountApp(null);
43
47
  `;
44
48
  }
45
49
  export {