orvyn-lang 0.1.1 → 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.
- package/GUIDE.md +149 -0
- package/LANGUAGE.md +877 -24
- package/README.md +227 -131
- package/brand/orvyn-sunset-animated.svg +15 -0
- package/package.json +3 -1
- package/src/cli/orvyn.js +216 -489
- package/src/core/signal.js +104 -6
- package/src/devtools/runtime.js +25 -1
- package/src/lang/a11y.js +102 -0
- package/src/lang/auth.js +239 -0
- package/src/lang/bundle-native.js +10 -6
- package/src/lang/codegen.js +498 -64
- 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 +160 -0
- 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 +43 -4
- package/src/lang/native/android/OrvynDevice.kt +163 -0
- package/src/lang/native/android/OrvynEngine.kt +154 -7
- package/src/lang/native/android/OrvynRenderer.kt +519 -40
- package/src/lang/native/android.js +74 -11
- package/src/lang/native/build.js +130 -60
- package/src/lang/native/config.js +108 -0
- package/src/lang/native/ios/OrvynApp.swift +6 -0
- package/src/lang/native/ios/OrvynEngine.swift +268 -4
- package/src/lang/native/ios/OrvynViews.swift +429 -31
- package/src/lang/native/ios.js +75 -2
- package/src/lang/native-runtime.js +423 -57
- package/src/lang/page.js +52 -0
- package/src/lang/parser.js +243 -15
- package/src/lang/prerender.js +300 -0
- package/src/lang/read-import.js +11 -0
- package/src/lang/router.js +266 -0
- package/src/lang/runtime-shared.js +820 -10
- package/src/lang/runtime.js +375 -52
- 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/test-runner.js +134 -0
- package/src/lang/types.js +312 -0
- package/src/lang/validation.js +55 -0
- package/src/lang/vite-plugin.js +82 -3
- 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/mount.js +116 -27
- package/src/runtime/patch.js +90 -11
- package/src/runtime/style.js +11 -1
- package/src/styling/fluid.js +91 -4
- package/src/styling/spec.js +306 -0
- package/src/core/context.js +0 -19
- package/src/core/lifecycle.js +0 -8
- package/src/core/resource.js +0 -27
- package/src/core/router.js +0 -20
- package/src/core/theme.js +0 -10
- package/src/devtools/devicePreview/PreviewFrame.js +0 -214
- package/src/devtools/devicePreview/index.js +0 -6
- package/src/devtools/overlay.js +0 -105
- package/src/runtime/createRenderer.js +0 -22
- package/src/runtime/h.js +0 -93
- package/src/runtime/hydrate.js +0 -59
- package/src/runtime/jsx-dev-runtime.js +0 -7
- package/src/runtime/jsx-runtime.js +0 -13
- package/src/runtime/partialHydration.js +0 -154
- package/src/runtime/platform.js +0 -135
- package/src/runtime/renderToStream.js +0 -127
- package/src/runtime/renderToString.js +0 -121
- package/src/runtime/resume.js +0 -62
package/src/core/signal.js
CHANGED
|
@@ -7,13 +7,54 @@ import {
|
|
|
7
7
|
recordSignalSubscriber,
|
|
8
8
|
recordSignalUpdate,
|
|
9
9
|
registerEffect,
|
|
10
|
-
registerSignal
|
|
10
|
+
registerSignal,
|
|
11
|
+
unregisterEffect,
|
|
12
|
+
unregisterSignal
|
|
11
13
|
} from "../devtools/runtime.js";
|
|
12
14
|
let activeEffect = null;
|
|
15
|
+
let currentOwner = null;
|
|
13
16
|
let activeEffectId = null;
|
|
14
17
|
let signalId = 0;
|
|
15
18
|
const signalRegistry = /* @__PURE__ */ new Map();
|
|
16
19
|
const resumedValues = /* @__PURE__ */ new Map();
|
|
20
|
+
function createOwner() {
|
|
21
|
+
return {
|
|
22
|
+
cleanups: [],
|
|
23
|
+
disposed: false
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function getOwner() {
|
|
27
|
+
return currentOwner;
|
|
28
|
+
}
|
|
29
|
+
function runWithOwner(owner, fn) {
|
|
30
|
+
const previous = currentOwner;
|
|
31
|
+
currentOwner = owner;
|
|
32
|
+
try {
|
|
33
|
+
return fn();
|
|
34
|
+
} finally {
|
|
35
|
+
currentOwner = previous;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function onCleanup(fn) {
|
|
39
|
+
if (!currentOwner) return;
|
|
40
|
+
if (currentOwner.disposed) {
|
|
41
|
+
fn();
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
currentOwner.cleanups.push(fn);
|
|
45
|
+
}
|
|
46
|
+
function disposeOwner(owner, final = true) {
|
|
47
|
+
const cleanups = owner.cleanups;
|
|
48
|
+
owner.cleanups = [];
|
|
49
|
+
if (final) owner.disposed = true;
|
|
50
|
+
for (let i = cleanups.length - 1; i >= 0; i--) {
|
|
51
|
+
try {
|
|
52
|
+
cleanups[i]();
|
|
53
|
+
} catch (error) {
|
|
54
|
+
console.error("[Orvyn] cleanup failed", error);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
17
58
|
function normalizeOptions(options) {
|
|
18
59
|
if (typeof options === "string") {
|
|
19
60
|
return {
|
|
@@ -30,11 +71,12 @@ function signal(initial, options) {
|
|
|
30
71
|
const restore = (newValue) => {
|
|
31
72
|
value = newValue;
|
|
32
73
|
};
|
|
33
|
-
|
|
74
|
+
const record = {
|
|
34
75
|
id,
|
|
35
76
|
get: () => value,
|
|
36
77
|
restore
|
|
37
|
-
}
|
|
78
|
+
};
|
|
79
|
+
signalRegistry.set(id, record);
|
|
38
80
|
registerSignal(
|
|
39
81
|
id,
|
|
40
82
|
value
|
|
@@ -45,6 +87,7 @@ function signal(initial, options) {
|
|
|
45
87
|
get() {
|
|
46
88
|
if (activeEffect) {
|
|
47
89
|
subscribers.add(activeEffect);
|
|
90
|
+
activeEffect.deps.add(subscribers);
|
|
48
91
|
recordSignalSubscriber(
|
|
49
92
|
id,
|
|
50
93
|
subscribers.size
|
|
@@ -64,16 +107,41 @@ function signal(initial, options) {
|
|
|
64
107
|
id,
|
|
65
108
|
value
|
|
66
109
|
);
|
|
67
|
-
subscribers.forEach((fn) => {
|
|
110
|
+
Array.from(subscribers).forEach((fn) => {
|
|
68
111
|
schedule(fn);
|
|
69
112
|
});
|
|
70
113
|
},
|
|
114
|
+
// Calls fn after every change. Inside a component or screen the
|
|
115
|
+
// subscription ends when it is removed; the returned function ends it early.
|
|
71
116
|
subscribe(fn) {
|
|
72
|
-
|
|
117
|
+
let active = true;
|
|
118
|
+
const listener = () => {
|
|
119
|
+
if (active) fn();
|
|
120
|
+
};
|
|
121
|
+
subscribers.add(listener);
|
|
73
122
|
recordSignalSubscriber(
|
|
74
123
|
id,
|
|
75
124
|
subscribers.size
|
|
76
125
|
);
|
|
126
|
+
const unsubscribe = () => {
|
|
127
|
+
active = false;
|
|
128
|
+
subscribers.delete(listener);
|
|
129
|
+
};
|
|
130
|
+
onCleanup(unsubscribe);
|
|
131
|
+
return unsubscribe;
|
|
132
|
+
},
|
|
133
|
+
// Number of effects and subscriptions currently watching this value.
|
|
134
|
+
subscriberCount() {
|
|
135
|
+
return subscribers.size;
|
|
136
|
+
},
|
|
137
|
+
// Forget a signal that is no longer used anywhere (for example the error
|
|
138
|
+
// state of a form that was removed).
|
|
139
|
+
dispose() {
|
|
140
|
+
subscribers.clear();
|
|
141
|
+
if (signalRegistry.get(id) === record) {
|
|
142
|
+
signalRegistry.delete(id);
|
|
143
|
+
unregisterSignal(id);
|
|
144
|
+
}
|
|
77
145
|
}
|
|
78
146
|
};
|
|
79
147
|
}
|
|
@@ -112,11 +180,24 @@ function restoreSignalState(state = {}) {
|
|
|
112
180
|
}
|
|
113
181
|
function effect(fn) {
|
|
114
182
|
const id = registerEffect(fn.name || "effect");
|
|
115
|
-
const
|
|
183
|
+
const runOwner = createOwner();
|
|
184
|
+
let stopped = false;
|
|
185
|
+
const leaveDependencies = () => {
|
|
186
|
+
runner.deps.forEach((subscribers) => {
|
|
187
|
+
subscribers.delete(runner);
|
|
188
|
+
});
|
|
189
|
+
runner.deps.clear();
|
|
190
|
+
};
|
|
191
|
+
const runner = (() => {
|
|
192
|
+
if (stopped) return;
|
|
193
|
+
leaveDependencies();
|
|
194
|
+
disposeOwner(runOwner, false);
|
|
116
195
|
const previousEffect = activeEffect;
|
|
117
196
|
const previousEffectId = activeEffectId;
|
|
197
|
+
const previousOwner = currentOwner;
|
|
118
198
|
activeEffect = runner;
|
|
119
199
|
activeEffectId = id;
|
|
200
|
+
currentOwner = runOwner;
|
|
120
201
|
if (globalThis.__ORVYN_DEBUG__) {
|
|
121
202
|
console.log("[Orvyn Effect Triggered]", id);
|
|
122
203
|
}
|
|
@@ -130,12 +211,24 @@ function effect(fn) {
|
|
|
130
211
|
);
|
|
131
212
|
activeEffect = previousEffect;
|
|
132
213
|
activeEffectId = previousEffectId;
|
|
214
|
+
currentOwner = previousOwner;
|
|
133
215
|
}
|
|
216
|
+
});
|
|
217
|
+
runner.deps = /* @__PURE__ */ new Set();
|
|
218
|
+
const stop = () => {
|
|
219
|
+
if (stopped) return;
|
|
220
|
+
stopped = true;
|
|
221
|
+
leaveDependencies();
|
|
222
|
+
disposeOwner(runOwner);
|
|
223
|
+
unregisterEffect(id);
|
|
134
224
|
};
|
|
225
|
+
onCleanup(stop);
|
|
135
226
|
runner();
|
|
227
|
+
return stop;
|
|
136
228
|
}
|
|
137
229
|
function computed(fn) {
|
|
138
230
|
const result = signal(fn());
|
|
231
|
+
onCleanup(() => result.dispose());
|
|
139
232
|
effect(() => {
|
|
140
233
|
result.set(fn());
|
|
141
234
|
});
|
|
@@ -143,8 +236,13 @@ function computed(fn) {
|
|
|
143
236
|
}
|
|
144
237
|
export {
|
|
145
238
|
computed,
|
|
239
|
+
createOwner,
|
|
240
|
+
disposeOwner,
|
|
146
241
|
effect,
|
|
242
|
+
getOwner,
|
|
243
|
+
onCleanup,
|
|
147
244
|
restoreSignalState,
|
|
245
|
+
runWithOwner,
|
|
148
246
|
serializeReactiveGraph,
|
|
149
247
|
serializeSignalState,
|
|
150
248
|
signal
|
package/src/devtools/runtime.js
CHANGED
|
@@ -73,6 +73,24 @@ function registerEffect(label = "effect") {
|
|
|
73
73
|
});
|
|
74
74
|
return id;
|
|
75
75
|
}
|
|
76
|
+
function unregisterEffect(id) {
|
|
77
|
+
if (!effects.delete(id)) return;
|
|
78
|
+
dependencyGraph.forEach((edge) => {
|
|
79
|
+
if (edge.startsWith(`${id}->`)) dependencyGraph.delete(edge);
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
function unregisterSignal(id) {
|
|
83
|
+
signals.delete(id);
|
|
84
|
+
}
|
|
85
|
+
function unregisterComponent(id) {
|
|
86
|
+
const component = components.get(id);
|
|
87
|
+
if (!component) return;
|
|
88
|
+
components.delete(id);
|
|
89
|
+
const parent = component.parentId ? components.get(component.parentId) : void 0;
|
|
90
|
+
if (parent) {
|
|
91
|
+
parent.children = parent.children.filter((child) => child !== id);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
76
94
|
function beginEffectRun(id) {
|
|
77
95
|
if (!enabled) return now();
|
|
78
96
|
const effect = effects.get(id);
|
|
@@ -80,6 +98,9 @@ function beginEffectRun(id) {
|
|
|
80
98
|
effect.runs++;
|
|
81
99
|
effect.lastRun = now();
|
|
82
100
|
effect.dependencies = [];
|
|
101
|
+
dependencyGraph.forEach((edge) => {
|
|
102
|
+
if (edge.startsWith(`${id}->`)) dependencyGraph.delete(edge);
|
|
103
|
+
});
|
|
83
104
|
}
|
|
84
105
|
return now();
|
|
85
106
|
}
|
|
@@ -186,5 +207,8 @@ export {
|
|
|
186
207
|
recordSignalUpdate,
|
|
187
208
|
registerComponent,
|
|
188
209
|
registerEffect,
|
|
189
|
-
registerSignal
|
|
210
|
+
registerSignal,
|
|
211
|
+
unregisterComponent,
|
|
212
|
+
unregisterEffect,
|
|
213
|
+
unregisterSignal
|
|
190
214
|
};
|
package/src/lang/a11y.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { theme } from "../styling/spec.js";
|
|
2
|
+
const NAMED = {
|
|
3
|
+
black: "#000000",
|
|
4
|
+
white: "#ffffff",
|
|
5
|
+
gray: "#808080",
|
|
6
|
+
grey: "#808080",
|
|
7
|
+
red: "#ff0000",
|
|
8
|
+
green: "#008000",
|
|
9
|
+
blue: "#0000ff",
|
|
10
|
+
yellow: "#ffff00",
|
|
11
|
+
orange: "#ffa500",
|
|
12
|
+
silver: "#c0c0c0"
|
|
13
|
+
};
|
|
14
|
+
function literal(expr) {
|
|
15
|
+
if (!expr) return null;
|
|
16
|
+
if (expr.kind === "Color") return expr.value;
|
|
17
|
+
if (expr.kind === "Ident") return expr.name;
|
|
18
|
+
if (expr.kind === "String" && expr.parts.length === 1 && typeof expr.parts[0] === "string") return expr.parts[0];
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
function rgb(value) {
|
|
22
|
+
if (!value) return null;
|
|
23
|
+
const colors = theme().colors;
|
|
24
|
+
let hex = (colors[value] ?? NAMED[value] ?? value).replace("#", "");
|
|
25
|
+
if (hex.length === 3) hex = [...hex].map((c) => c + c).join("");
|
|
26
|
+
return /^[0-9a-fA-F]{6}$/.test(hex) ? [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16)) : null;
|
|
27
|
+
}
|
|
28
|
+
function contrast(a, b) {
|
|
29
|
+
const light = (color) => color.map((v) => v / 255).map((v) => v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4).reduce((sum, v, i) => sum + v * [0.2126, 0.7152, 0.0722][i], 0);
|
|
30
|
+
const [high, low] = [light(a), light(b)].sort((x, y) => y - x);
|
|
31
|
+
return (high + 0.05) / (low + 0.05);
|
|
32
|
+
}
|
|
33
|
+
function checkAccessibility(program) {
|
|
34
|
+
const warnings = [];
|
|
35
|
+
const visit = (node, background) => {
|
|
36
|
+
if (node.kind === "ViewIf") {
|
|
37
|
+
node.then.forEach((n) => visit(n, background));
|
|
38
|
+
node.else?.forEach((n) => visit(n, background));
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (node.kind === "ViewFor") return node.body.forEach((n) => visit(n, background));
|
|
42
|
+
const prop = (key) => {
|
|
43
|
+
const found = node.props.find((p) => p.key === key);
|
|
44
|
+
return found?.value.kind === "Expr" ? found.value.expr : void 0;
|
|
45
|
+
};
|
|
46
|
+
const has = (key) => node.props.some((p) => p.key === key);
|
|
47
|
+
const warn = (message) => warnings.push({ line: node.line, col: node.col, message });
|
|
48
|
+
const text = literal(node.arg ?? void 0);
|
|
49
|
+
if (node.name === "Image" && !has("label") && !has("alt")) {
|
|
50
|
+
warn(`Image needs a label for screen readers, like label: "Photo of the product" (label: "" if it is decoration)`);
|
|
51
|
+
}
|
|
52
|
+
if ((node.name === "Button" || node.name === "Link") && !has("label")) {
|
|
53
|
+
const quoted = node.arg?.kind === "String" ? node.arg.parts.filter((p) => typeof p === "string").join("") : null;
|
|
54
|
+
const onlySymbols = node.arg?.kind === "String" && node.arg.parts.length === 1 && !/[\p{L}\p{N}]/u.test(quoted);
|
|
55
|
+
if (!node.arg && !node.children.length || onlySymbols) {
|
|
56
|
+
warn(`${node.name} ${quoted ? `"${quoted}"` : ""} needs a label for screen readers, like label: "Remove"`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const ownBackground = literal(prop("bg")) ?? background;
|
|
60
|
+
const color = literal(prop("color"));
|
|
61
|
+
const onButton = node.name === "Button" && has("bg");
|
|
62
|
+
if (color && ["Text", "Heading", "Button", "Link", "SubmitButton", "Checkbox", "Switch"].includes(node.name)) {
|
|
63
|
+
const front = rgb(color);
|
|
64
|
+
const back = rgb(ownBackground);
|
|
65
|
+
const size = Number(literal(prop("size")) ?? (prop("size")?.kind === "Number" ? prop("size").value : 0));
|
|
66
|
+
const needed = node.name === "Heading" || size >= 24 || onButton ? 3 : 4.5;
|
|
67
|
+
if (front && back) {
|
|
68
|
+
const ratio = contrast(front, back);
|
|
69
|
+
if (ratio < needed) warn(`"${color}" on "${ownBackground}" is hard to read (contrast ${ratio.toFixed(1)}, needs ${needed})${text ? `: ${text}` : ""}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
node.children.forEach((child) => visit(child, ownBackground));
|
|
73
|
+
};
|
|
74
|
+
const screens = program.body.filter((d) => d.kind === "Screen" && d.type === "screen");
|
|
75
|
+
const usesPage = screens.some((s) => s.page);
|
|
76
|
+
const titles = /* @__PURE__ */ new Map();
|
|
77
|
+
for (const screen of screens) {
|
|
78
|
+
if (!usesPage || screen.requiresAuth || ["NotFound", "ErrorPage"].includes(screen.name)) continue;
|
|
79
|
+
const field = (key) => {
|
|
80
|
+
const value = screen.page?.find((p) => p.key === key)?.value;
|
|
81
|
+
return value?.kind === "Expr" ? value.expr : void 0;
|
|
82
|
+
};
|
|
83
|
+
const warn = (message) => warnings.push({ line: screen.line, col: screen.col, message: `SEO: ${message}` });
|
|
84
|
+
for (const key of ["title", "description"]) {
|
|
85
|
+
if (!field(key)) warn(`screen ${screen.name} has no ${key}. Add: page title: "...", description: "..."`);
|
|
86
|
+
}
|
|
87
|
+
const title = literal(field("title"));
|
|
88
|
+
if (title) {
|
|
89
|
+
if (title.length > 60) warn(`the title of ${screen.name} is long (${title.length}); search results cut it near 60`);
|
|
90
|
+
if (titles.has(title)) warn(`${screen.name} and ${titles.get(title)} have the same title`);
|
|
91
|
+
titles.set(title, screen.name);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
for (const decl of program.body) {
|
|
95
|
+
if (decl.kind === "Screen") decl.body.forEach((node) => visit(node, "bg"));
|
|
96
|
+
}
|
|
97
|
+
return warnings;
|
|
98
|
+
}
|
|
99
|
+
export {
|
|
100
|
+
checkAccessibility,
|
|
101
|
+
contrast
|
|
102
|
+
};
|
package/src/lang/auth.js
ADDED
|
@@ -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:
|
|
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
|
-
${
|
|
42
|
-
|
|
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 {
|