@use-stall/extensions 0.0.0-stage → 0.1.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/README.md +56 -2
- package/bunfig.toml +5 -0
- package/cli/bin.js +18 -0
- package/cli/build.ts +109 -0
- package/cli/check/check.ts +123 -0
- package/cli/check/endpoints.ts +212 -0
- package/cli/check/manifest.ts +162 -0
- package/cli/check/source.ts +116 -0
- package/cli/check/widgets.ts +133 -0
- package/cli/dev.ts +266 -0
- package/cli/introspect-child.ts +101 -0
- package/cli/introspect.ts +146 -0
- package/cli/main.ts +94 -0
- package/cli/pack.ts +76 -0
- package/cli/paths.ts +58 -0
- package/cli/types.ts +285 -0
- package/host.d.ts +3 -0
- package/host.js +7 -0
- package/index.d.ts +177 -0
- package/index.js +59 -0
- package/package.json +71 -4
- package/sandbox/app.tsx +467 -0
- package/sandbox/bus.ts +26 -0
- package/sandbox/client.tsx +64 -0
- package/sandbox/data.ts +94 -0
- package/sandbox/flex.css +1 -0
- package/sandbox/fonts/Geist-Bold.ttf +0 -0
- package/sandbox/fonts/Geist-Medium.ttf +0 -0
- package/sandbox/fonts/Geist-Regular.ttf +0 -0
- package/sandbox/fonts/Geist-SemiBold.ttf +0 -0
- package/sandbox/host.ts +270 -0
- package/sandbox/seed.ts +111 -0
- package/sandbox/shared.d.ts +3 -0
- package/schema/extension.schema.json +132 -0
package/sandbox/app.tsx
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
import { Navigate, Route, Routes, useNavigate, useParams } from "react-router-dom";
|
|
3
|
+
import { Toaster, toast } from "sonner";
|
|
4
|
+
import { FancyButton, Input } from "@use-stall/ui";
|
|
5
|
+
import type {
|
|
6
|
+
ExtensionLookupGroup,
|
|
7
|
+
ExtensionWidget,
|
|
8
|
+
LookupActionHelpersType,
|
|
9
|
+
RuntimeProps,
|
|
10
|
+
StallExtension,
|
|
11
|
+
} from "@use-stall/types";
|
|
12
|
+
import { HOST_VERSION, can_read } from "../index.js";
|
|
13
|
+
import * as data from "./data";
|
|
14
|
+
import { notices, prompts, scans, settings, type Prompt } from "./bus";
|
|
15
|
+
import { SESSION } from "./seed";
|
|
16
|
+
|
|
17
|
+
export type Manifest = {
|
|
18
|
+
id: string;
|
|
19
|
+
name: string;
|
|
20
|
+
version: string;
|
|
21
|
+
host: string;
|
|
22
|
+
scopes: string[];
|
|
23
|
+
widgets: ExtensionWidget[];
|
|
24
|
+
entrypoint: { id: string; type: "lookup" | "page" };
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export type Module = {
|
|
28
|
+
app: StallExtension;
|
|
29
|
+
ui: { components: Record<string, React.ComponentType<{ extension_ui_props: RuntimeProps }>> };
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export type Loaded = { manifest: Manifest; module: Module | null; error: string; version: number };
|
|
33
|
+
|
|
34
|
+
const TIMEOUT = 5000;
|
|
35
|
+
|
|
36
|
+
const page_path = (extension: string, value: string) => {
|
|
37
|
+
const page = value.trim().replace(/^\/+/, "").replace(/\/+$/, "");
|
|
38
|
+
if (!/^[\w-]*$/.test(page)) return "";
|
|
39
|
+
const base = `/extensions/${encodeURIComponent(extension)}`;
|
|
40
|
+
return page ? `${base}/${page}` : base;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const settle = async (run: () => unknown) => {
|
|
44
|
+
const timer = new Promise((_, reject) => setTimeout(() => reject(new Error("Handler timed out")), TIMEOUT));
|
|
45
|
+
const value = await Promise.race([Promise.resolve().then(run), timer]);
|
|
46
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const message = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
|
50
|
+
|
|
51
|
+
const Ctx = React.createContext<{ state: Loaded; open: (group: string) => void }>(null!);
|
|
52
|
+
|
|
53
|
+
const useCtx = () => React.useContext(Ctx);
|
|
54
|
+
|
|
55
|
+
const Bar = ({ build }: { build: string }) => {
|
|
56
|
+
const { state } = useCtx();
|
|
57
|
+
const [deny, set_deny] = React.useState(settings.deny);
|
|
58
|
+
const [code, set_code] = React.useState("");
|
|
59
|
+
const navigate = useNavigate();
|
|
60
|
+
const outdated = state.manifest.host !== HOST_VERSION;
|
|
61
|
+
|
|
62
|
+
return (
|
|
63
|
+
<header className="sticky top-0 z-40 flex flex-wrap items-center gap-3 border-b border-border bg-background px-4 py-2 text-sm">
|
|
64
|
+
<button type="button" className="font-semibold" onClick={() => navigate("/")}>
|
|
65
|
+
{state.manifest.name} <span className="text-muted-foreground">v{state.manifest.version}</span>
|
|
66
|
+
</button>
|
|
67
|
+
<span className={outdated ? "text-destructive" : "text-muted-foreground"}>
|
|
68
|
+
host {state.manifest.host || "missing"} · SDK {HOST_VERSION}
|
|
69
|
+
</span>
|
|
70
|
+
<span className={build ? "text-destructive" : "text-muted-foreground"}>{build ? "Build failed" : "Build ok"}</span>
|
|
71
|
+
<span className="flex-1" />
|
|
72
|
+
<form
|
|
73
|
+
className="flex items-center gap-2"
|
|
74
|
+
onSubmit={(event) => {
|
|
75
|
+
event.preventDefault();
|
|
76
|
+
if (!code.trim()) return;
|
|
77
|
+
scans.send(code.trim());
|
|
78
|
+
set_code("");
|
|
79
|
+
}}
|
|
80
|
+
>
|
|
81
|
+
<Input value={code} onChange={(event) => set_code(event.target.value)} placeholder="Simulate scan" className="h-8 w-40" />
|
|
82
|
+
</form>
|
|
83
|
+
<label className="flex items-center gap-2">
|
|
84
|
+
<input
|
|
85
|
+
type="checkbox"
|
|
86
|
+
checked={deny}
|
|
87
|
+
onChange={(event) => {
|
|
88
|
+
settings.deny = event.target.checked;
|
|
89
|
+
set_deny(event.target.checked);
|
|
90
|
+
}}
|
|
91
|
+
/>
|
|
92
|
+
Deny permissions
|
|
93
|
+
</label>
|
|
94
|
+
<button type="button" className="text-muted-foreground hover:text-foreground" onClick={data.reset}>
|
|
95
|
+
Reset data
|
|
96
|
+
</button>
|
|
97
|
+
<button
|
|
98
|
+
type="button"
|
|
99
|
+
className="text-muted-foreground hover:text-foreground"
|
|
100
|
+
onClick={() => {
|
|
101
|
+
const dark = document.documentElement.classList.toggle("dark");
|
|
102
|
+
localStorage.setItem("stall-sandbox:theme", dark ? "dark" : "light");
|
|
103
|
+
}}
|
|
104
|
+
>
|
|
105
|
+
Theme
|
|
106
|
+
</button>
|
|
107
|
+
</header>
|
|
108
|
+
);
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const useHandler = (name: string) => {
|
|
112
|
+
const { state } = useCtx();
|
|
113
|
+
const [value, set_value] = React.useState<number | null>(null);
|
|
114
|
+
React.useEffect(() => {
|
|
115
|
+
const handler = name ? state.module?.app.handlers?.[name] : undefined;
|
|
116
|
+
if (typeof handler !== "function") return;
|
|
117
|
+
let live = true;
|
|
118
|
+
const run = () =>
|
|
119
|
+
settle(() => handler({ seen: "" }))
|
|
120
|
+
.then((result) => live && set_value(result))
|
|
121
|
+
.catch((error) => {
|
|
122
|
+
console.error(`[sandbox] handler '${name}'`, error);
|
|
123
|
+
if (live) set_value(null);
|
|
124
|
+
});
|
|
125
|
+
run();
|
|
126
|
+
const stop = data.subscribe(run);
|
|
127
|
+
return () => {
|
|
128
|
+
live = false;
|
|
129
|
+
stop();
|
|
130
|
+
};
|
|
131
|
+
}, [name, state]);
|
|
132
|
+
return value;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const Widget = ({ widget }: { widget: ExtensionWidget }) => {
|
|
136
|
+
const { state, open } = useCtx();
|
|
137
|
+
const navigate = useNavigate();
|
|
138
|
+
const value = useHandler(widget.type === "value" ? widget.configs.value_handler : "");
|
|
139
|
+
const badge = useHandler(widget.configs.badge_handler);
|
|
140
|
+
|
|
141
|
+
const press = async () => {
|
|
142
|
+
const { required_permission, on_click } = widget.configs;
|
|
143
|
+
if (on_click.type === "none") return;
|
|
144
|
+
if (required_permission && settings.deny) return toast.error(`Needs approval: ${required_permission}`);
|
|
145
|
+
if (on_click.type === "navigate") {
|
|
146
|
+
const path = page_path(state.manifest.id, on_click.value);
|
|
147
|
+
return path ? navigate(path) : toast.error(`'${on_click.value}' isn't a valid page path`);
|
|
148
|
+
}
|
|
149
|
+
if ((on_click.type as string) === "lookup") return open(on_click.value);
|
|
150
|
+
const handler = state.module?.app.handlers?.[on_click.value];
|
|
151
|
+
if (typeof handler !== "function") return toast.error(`No '${on_click.value}' handler`);
|
|
152
|
+
try {
|
|
153
|
+
await handler({ seen: "" });
|
|
154
|
+
} catch (error) {
|
|
155
|
+
toast.error(message(error));
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
return (
|
|
160
|
+
<button
|
|
161
|
+
type="button"
|
|
162
|
+
onClick={press}
|
|
163
|
+
className="relative flex min-h-28 flex-col justify-between gap-2 rounded-xl border border-border bg-background p-4 text-left"
|
|
164
|
+
>
|
|
165
|
+
<span className="text-sm text-muted-foreground">{widget.title}</span>
|
|
166
|
+
{widget.type === "value" ? <span className="text-2xl font-semibold tabular-nums">{value ?? "--"}</span> : null}
|
|
167
|
+
{badge ? (
|
|
168
|
+
<span className="absolute right-3 top-3 rounded-full bg-primary px-2 text-xs text-primary-foreground">{badge}</span>
|
|
169
|
+
) : null}
|
|
170
|
+
</button>
|
|
171
|
+
);
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const Home = () => {
|
|
175
|
+
const { state, open } = useCtx();
|
|
176
|
+
const navigate = useNavigate();
|
|
177
|
+
const { entrypoint, widgets } = state.manifest;
|
|
178
|
+
|
|
179
|
+
const start = () =>
|
|
180
|
+
entrypoint.type === "lookup" ? open(entrypoint.id) : navigate(page_path(state.manifest.id, entrypoint.id));
|
|
181
|
+
|
|
182
|
+
return (
|
|
183
|
+
<main className="mx-auto flex w-full max-w-5xl flex-col gap-6 p-6">
|
|
184
|
+
<section className="flex items-center justify-between gap-4">
|
|
185
|
+
<div className="flex flex-col">
|
|
186
|
+
<h1 className="text-xl font-semibold">Home</h1>
|
|
187
|
+
<span className="text-sm text-muted-foreground">
|
|
188
|
+
Signed in as {SESSION.user.fullname} at {SESSION.location.name}
|
|
189
|
+
</span>
|
|
190
|
+
</div>
|
|
191
|
+
<FancyButton variant="primary" onClick={start} className="h-10 px-4">
|
|
192
|
+
Open {state.manifest.name}
|
|
193
|
+
</FancyButton>
|
|
194
|
+
</section>
|
|
195
|
+
{widgets.length ? (
|
|
196
|
+
<section className="grid grid-cols-2 gap-3 md:grid-cols-4">
|
|
197
|
+
{widgets.map((widget) => (
|
|
198
|
+
<Widget key={widget.id} widget={widget} />
|
|
199
|
+
))}
|
|
200
|
+
</section>
|
|
201
|
+
) : (
|
|
202
|
+
<p className="text-sm text-muted-foreground">This extension has no widgets.</p>
|
|
203
|
+
)}
|
|
204
|
+
{state.module?.app.lookup.length ? (
|
|
205
|
+
<section className="flex flex-col gap-2">
|
|
206
|
+
<h2 className="text-sm font-medium text-muted-foreground">Lookups</h2>
|
|
207
|
+
<div className="flex flex-wrap gap-2">
|
|
208
|
+
{state.module.app.lookup.map((group) => (
|
|
209
|
+
<button
|
|
210
|
+
key={group.id}
|
|
211
|
+
type="button"
|
|
212
|
+
onClick={() => open(group.id)}
|
|
213
|
+
className="rounded-full bg-muted px-3 py-1 text-sm"
|
|
214
|
+
>
|
|
215
|
+
{group.title}
|
|
216
|
+
</button>
|
|
217
|
+
))}
|
|
218
|
+
</div>
|
|
219
|
+
</section>
|
|
220
|
+
) : null}
|
|
221
|
+
</main>
|
|
222
|
+
);
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
class Boundary extends React.Component<{ children: React.ReactNode }, { error: string }> {
|
|
226
|
+
override state = { error: "" };
|
|
227
|
+
static getDerivedStateFromError(error: unknown) {
|
|
228
|
+
return { error: error instanceof Error ? error.stack ?? error.message : String(error) };
|
|
229
|
+
}
|
|
230
|
+
override render() {
|
|
231
|
+
if (!this.state.error) return this.props.children;
|
|
232
|
+
return <pre className="m-6 whitespace-pre-wrap rounded-xl bg-muted p-4 text-sm text-destructive">{this.state.error}</pre>;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const Page = () => {
|
|
237
|
+
const { state } = useCtx();
|
|
238
|
+
const { extension, page } = useParams();
|
|
239
|
+
const app = state.module?.app;
|
|
240
|
+
if (extension !== state.manifest.id) return <Navigate to="/" replace />;
|
|
241
|
+
const active = app?.pages.find((item) => (page ? item.id === page : item.index));
|
|
242
|
+
const View = active ? state.module?.ui?.components?.[active.ui] : undefined;
|
|
243
|
+
if (!View) return <p className="p-6 text-sm text-destructive">No page '{page ?? "index"}' in this extension.</p>;
|
|
244
|
+
return (
|
|
245
|
+
<Boundary key={`${state.version}:${active!.id}`}>
|
|
246
|
+
<View extension_ui_props={{ base_currency: SESSION.currency }} />
|
|
247
|
+
</Boundary>
|
|
248
|
+
);
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
const label = (row: Record<string, any>, key: string) => {
|
|
252
|
+
const value = key ? data.value_of(row as data.Row, key) : "";
|
|
253
|
+
return value === undefined || value === null ? "" : String(value);
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
const Lookup = ({ group, close, open }: { group: string; close: () => void; open: (group: string) => void }) => {
|
|
257
|
+
const { state } = useCtx();
|
|
258
|
+
const navigate = useNavigate();
|
|
259
|
+
const [query, set_query] = React.useState("");
|
|
260
|
+
const [items, set_items] = React.useState<Record<string, any>[]>([]);
|
|
261
|
+
const [error, set_error] = React.useState("");
|
|
262
|
+
const found = state.module?.app.lookup.find((item) => item.id === group) as ExtensionLookupGroup | undefined;
|
|
263
|
+
|
|
264
|
+
const helpers: LookupActionHelpersType = {
|
|
265
|
+
navigate: (path) => {
|
|
266
|
+
close();
|
|
267
|
+
if (typeof path === "number") navigate(path);
|
|
268
|
+
else navigate(path);
|
|
269
|
+
},
|
|
270
|
+
open_group: (arg) => open(String((arg as { id?: string }).id ?? "")),
|
|
271
|
+
go_back: () => close(),
|
|
272
|
+
close_lookup: () => close(),
|
|
273
|
+
set_search_query: set_query,
|
|
274
|
+
get_lookup_state: () => null,
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
React.useEffect(() => {
|
|
278
|
+
if (!found) return;
|
|
279
|
+
let live = true;
|
|
280
|
+
const run = async () => {
|
|
281
|
+
try {
|
|
282
|
+
if (found.data_origin === "local" && !can_read(state.manifest.scopes, found.source))
|
|
283
|
+
throw new Error(`'${state.manifest.id}' can't read '${found.source}'`);
|
|
284
|
+
const rows =
|
|
285
|
+
found.data_origin === "local"
|
|
286
|
+
? data.rows(found.source)
|
|
287
|
+
: await found.fetch({ filters: found.filters, search_query: query, helpers });
|
|
288
|
+
const text = query.toLowerCase();
|
|
289
|
+
const shown = (Array.isArray(rows) ? rows : []).filter(
|
|
290
|
+
(row) => !text || label(row, found.keys.title.value).toLowerCase().includes(text),
|
|
291
|
+
);
|
|
292
|
+
if (live) {
|
|
293
|
+
set_items(shown.slice(0, 200));
|
|
294
|
+
set_error("");
|
|
295
|
+
}
|
|
296
|
+
} catch (reason) {
|
|
297
|
+
if (live) set_error(message(reason));
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
run();
|
|
301
|
+
return data.subscribe(run);
|
|
302
|
+
}, [found, query]);
|
|
303
|
+
|
|
304
|
+
if (!found) return null;
|
|
305
|
+
|
|
306
|
+
return (
|
|
307
|
+
<div className="fixed inset-0 z-50 flex items-start justify-center bg-black/70 p-6 pt-[10vh]" onClick={close}>
|
|
308
|
+
<div
|
|
309
|
+
className="flex max-h-[70vh] w-full max-w-2xl flex-col gap-3 overflow-hidden rounded-2xl bg-background p-4"
|
|
310
|
+
onClick={(event) => event.stopPropagation()}
|
|
311
|
+
>
|
|
312
|
+
<div className="flex items-center justify-between">
|
|
313
|
+
<span className="font-semibold">{found.title}</span>
|
|
314
|
+
<span className="text-xs text-muted-foreground">{found.data_origin} · {found.source}</span>
|
|
315
|
+
</div>
|
|
316
|
+
<Input autoFocus value={query} onChange={(event) => set_query(event.target.value)} placeholder="Search…" />
|
|
317
|
+
{error ? <p className="text-sm text-destructive">{error}</p> : null}
|
|
318
|
+
<div className="flex flex-col gap-1 overflow-y-auto">
|
|
319
|
+
{items.map((item, index) => (
|
|
320
|
+
<div key={String(item.id ?? index)} className="flex items-center justify-between gap-3 rounded-lg px-2 py-2 hover:bg-muted">
|
|
321
|
+
<div className="flex min-w-0 flex-col">
|
|
322
|
+
<span className="truncate text-sm font-medium">{label(item, found.keys.title.value)}</span>
|
|
323
|
+
{found.keys.description ? (
|
|
324
|
+
<span className="truncate text-xs text-muted-foreground">{label(item, found.keys.description.value)}</span>
|
|
325
|
+
) : null}
|
|
326
|
+
</div>
|
|
327
|
+
<div className="flex shrink-0 gap-1">
|
|
328
|
+
{found.actions.map((action) => (
|
|
329
|
+
<button
|
|
330
|
+
key={action.id}
|
|
331
|
+
type="button"
|
|
332
|
+
className="rounded-md bg-muted px-2 py-1 text-xs"
|
|
333
|
+
onClick={async () => {
|
|
334
|
+
try {
|
|
335
|
+
await action.run({ item, search_query: query, helpers });
|
|
336
|
+
if (action.close_on_complete) close();
|
|
337
|
+
} catch (reason) {
|
|
338
|
+
toast.error(message(reason));
|
|
339
|
+
}
|
|
340
|
+
}}
|
|
341
|
+
>
|
|
342
|
+
{action.label}
|
|
343
|
+
</button>
|
|
344
|
+
))}
|
|
345
|
+
</div>
|
|
346
|
+
</div>
|
|
347
|
+
))}
|
|
348
|
+
{!items.length && !error ? <p className="px-2 py-6 text-center text-sm text-muted-foreground">No results</p> : null}
|
|
349
|
+
</div>
|
|
350
|
+
</div>
|
|
351
|
+
</div>
|
|
352
|
+
);
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
const Pay = ({ prompt }: { prompt: Extract<Prompt, { kind: "pay" }> }) => {
|
|
356
|
+
const navigate = useNavigate();
|
|
357
|
+
const { input } = prompt;
|
|
358
|
+
|
|
359
|
+
const finish = (status: "completed" | "pending" | "cancelled") => {
|
|
360
|
+
const payments =
|
|
361
|
+
status === "cancelled"
|
|
362
|
+
? []
|
|
363
|
+
: [
|
|
364
|
+
data.put("payments", {
|
|
365
|
+
id: `pay_${crypto.randomUUID().slice(0, 8)}`,
|
|
366
|
+
order_id: input.order_id,
|
|
367
|
+
amount: input.amount,
|
|
368
|
+
currency: input.currency,
|
|
369
|
+
status: status === "completed" ? "completed" : "pending",
|
|
370
|
+
payment_method: { id: "pm_sandbox", name: "Sandbox" },
|
|
371
|
+
note: input.note,
|
|
372
|
+
created_at: new Date().toISOString(),
|
|
373
|
+
}),
|
|
374
|
+
];
|
|
375
|
+
prompts.send(null);
|
|
376
|
+
prompt.resolve({ status, paid: status === "completed" ? input.amount : 0, payments: payments as never });
|
|
377
|
+
if (status !== "completed") return;
|
|
378
|
+
if (typeof input.done === "function") input.done();
|
|
379
|
+
else if (input.done) navigate(input.done);
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
return (
|
|
383
|
+
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-6">
|
|
384
|
+
<div className="flex w-full max-w-sm flex-col gap-4 rounded-2xl bg-background p-6 text-center">
|
|
385
|
+
<span className="text-sm text-muted-foreground">Simulated payment</span>
|
|
386
|
+
<span className="text-3xl font-semibold tabular-nums">
|
|
387
|
+
{input.currency} {input.amount.toFixed(2)}
|
|
388
|
+
</span>
|
|
389
|
+
<span className="text-xs text-muted-foreground">Order {input.order_id || "none"}</span>
|
|
390
|
+
<FancyButton variant="primary" className="h-11" onClick={() => finish("completed")}>
|
|
391
|
+
Complete
|
|
392
|
+
</FancyButton>
|
|
393
|
+
<FancyButton variant="ghost" className="h-11 bg-muted" onClick={() => finish("pending")}>
|
|
394
|
+
Leave pending
|
|
395
|
+
</FancyButton>
|
|
396
|
+
<FancyButton variant="ghost" className="h-11" onClick={() => finish("cancelled")}>
|
|
397
|
+
Cancel
|
|
398
|
+
</FancyButton>
|
|
399
|
+
</div>
|
|
400
|
+
</div>
|
|
401
|
+
);
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
const Scan = ({ prompt }: { prompt: Extract<Prompt, { kind: "scan" }> }) => {
|
|
405
|
+
const [code, set_code] = React.useState("");
|
|
406
|
+
const done = (value: string | null) => {
|
|
407
|
+
prompts.send(null);
|
|
408
|
+
if (value) prompt.resolve(value);
|
|
409
|
+
else prompt.reject(new Error("Scan cancelled"));
|
|
410
|
+
};
|
|
411
|
+
return (
|
|
412
|
+
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-6">
|
|
413
|
+
<form
|
|
414
|
+
className="flex w-full max-w-sm flex-col gap-3 rounded-2xl bg-background p-6"
|
|
415
|
+
onSubmit={(event) => {
|
|
416
|
+
event.preventDefault();
|
|
417
|
+
done(code.trim() || null);
|
|
418
|
+
}}
|
|
419
|
+
>
|
|
420
|
+
<span className="font-semibold">Simulate a scan</span>
|
|
421
|
+
<Input autoFocus value={code} onChange={(event) => set_code(event.target.value)} placeholder="Barcode" />
|
|
422
|
+
<FancyButton type="submit" variant="primary" className="h-10">
|
|
423
|
+
Scan
|
|
424
|
+
</FancyButton>
|
|
425
|
+
<FancyButton type="button" variant="ghost" className="h-10" onClick={() => done(null)}>
|
|
426
|
+
Cancel
|
|
427
|
+
</FancyButton>
|
|
428
|
+
</form>
|
|
429
|
+
</div>
|
|
430
|
+
);
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
const Problem = ({ text }: { text: string }) => (
|
|
434
|
+
<pre className="fixed inset-x-4 bottom-4 z-50 max-h-[40vh] overflow-auto whitespace-pre-wrap rounded-xl bg-background p-4 text-xs text-destructive shadow-2xl">
|
|
435
|
+
{text}
|
|
436
|
+
</pre>
|
|
437
|
+
);
|
|
438
|
+
|
|
439
|
+
const App = ({ state, build }: { state: Loaded; build: string }) => {
|
|
440
|
+
const [group, set_group] = React.useState("");
|
|
441
|
+
const [prompt, set_prompt] = React.useState<Prompt | null>(null);
|
|
442
|
+
|
|
443
|
+
React.useEffect(() => prompts.on(set_prompt), []);
|
|
444
|
+
React.useEffect(() => notices.on((text) => toast(text)), []);
|
|
445
|
+
|
|
446
|
+
const ctx = React.useMemo(() => ({ state, open: set_group }), [state]);
|
|
447
|
+
|
|
448
|
+
return (
|
|
449
|
+
<Ctx.Provider value={ctx}>
|
|
450
|
+
<div className="bg-main-background text-foreground" style={{ minHeight: "100dvh" }}>
|
|
451
|
+
<Bar build={build} />
|
|
452
|
+
<Routes>
|
|
453
|
+
<Route path="/" element={<Home />} />
|
|
454
|
+
<Route path="/extensions/:extension/:page?" element={<Page />} />
|
|
455
|
+
<Route path="*" element={<Navigate to="/" replace />} />
|
|
456
|
+
</Routes>
|
|
457
|
+
{group ? <Lookup group={group} close={() => set_group("")} open={set_group} /> : null}
|
|
458
|
+
{prompt?.kind === "pay" ? <Pay prompt={prompt} /> : null}
|
|
459
|
+
{prompt?.kind === "scan" ? <Scan prompt={prompt} /> : null}
|
|
460
|
+
{build || state.error ? <Problem text={build || state.error} /> : null}
|
|
461
|
+
<Toaster position="top-center" />
|
|
462
|
+
</div>
|
|
463
|
+
</Ctx.Provider>
|
|
464
|
+
);
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
export default App;
|
package/sandbox/bus.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { PayInput, PayResult } from "../index";
|
|
2
|
+
|
|
3
|
+
export type Prompt =
|
|
4
|
+
| { kind: "pay"; input: PayInput; resolve: (result: PayResult) => void }
|
|
5
|
+
| { kind: "scan"; resolve: (code: string) => void; reject: (error: Error) => void };
|
|
6
|
+
|
|
7
|
+
type Listener<T> = (value: T) => void;
|
|
8
|
+
|
|
9
|
+
const make = <T>() => {
|
|
10
|
+
const listeners = new Set<Listener<T>>();
|
|
11
|
+
return {
|
|
12
|
+
on: (fn: Listener<T>) => {
|
|
13
|
+
listeners.add(fn);
|
|
14
|
+
return () => void listeners.delete(fn);
|
|
15
|
+
},
|
|
16
|
+
send: (value: T) => listeners.forEach((fn) => fn(value)),
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export const prompts = make<Prompt | null>();
|
|
21
|
+
|
|
22
|
+
export const scans = make<string>();
|
|
23
|
+
|
|
24
|
+
export const notices = make<string>();
|
|
25
|
+
|
|
26
|
+
export const settings = { deny: false };
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
import { createRoot } from "react-dom/client";
|
|
3
|
+
import { BrowserRouter } from "react-router-dom";
|
|
4
|
+
import { modules } from "stall-sandbox:shared";
|
|
5
|
+
import { HOST_MODULE, REGISTRY } from "../index.js";
|
|
6
|
+
import App, { type Loaded, type Manifest, type Module } from "./app";
|
|
7
|
+
import { create_host } from "./host";
|
|
8
|
+
import * as data from "./data";
|
|
9
|
+
|
|
10
|
+
const json = async <T,>(path: string): Promise<T> => {
|
|
11
|
+
const response = await fetch(path, { cache: "no-store" });
|
|
12
|
+
if (!response.ok) throw new Error(`${path} returned ${response.status}`);
|
|
13
|
+
return (await response.json()) as T;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const registry: Record<string, unknown> = { ...modules };
|
|
17
|
+
|
|
18
|
+
Object.defineProperty(globalThis, REGISTRY, { value: registry, configurable: false, writable: false });
|
|
19
|
+
|
|
20
|
+
const theme = localStorage.getItem("stall-sandbox:theme");
|
|
21
|
+
if (theme === "dark" || (!theme && matchMedia("(prefers-color-scheme: dark)").matches))
|
|
22
|
+
document.documentElement.classList.add("dark");
|
|
23
|
+
|
|
24
|
+
const load = async (version: number): Promise<Loaded> => {
|
|
25
|
+
const manifest = await json<Manifest>("/__sandbox/manifest.json");
|
|
26
|
+
registry[HOST_MODULE] = Object.freeze({ host: create_host(manifest, React) });
|
|
27
|
+
try {
|
|
28
|
+
const module = (await import(`/__sandbox/extension.js?v=${version}`)) as Module;
|
|
29
|
+
return { manifest, module, error: "", version };
|
|
30
|
+
} catch (error) {
|
|
31
|
+
return { manifest, module: null, error: error instanceof Error ? error.stack ?? error.message : String(error), version };
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const Root = () => {
|
|
36
|
+
const [state, set_state] = React.useState<Loaded | null>(null);
|
|
37
|
+
const [build, set_build] = React.useState("");
|
|
38
|
+
|
|
39
|
+
React.useEffect(() => {
|
|
40
|
+
let alive = true;
|
|
41
|
+
json<Record<string, unknown>>("/__sandbox/seed.json")
|
|
42
|
+
.then(data.seed)
|
|
43
|
+
.catch((error) => console.error("[sandbox] seed", error));
|
|
44
|
+
const events = new EventSource("/__sandbox/events");
|
|
45
|
+
events.addEventListener("build", (event) => {
|
|
46
|
+
const message = JSON.parse((event as MessageEvent<string>).data) as { ok: boolean; version: number; error: string };
|
|
47
|
+
set_build(message.ok ? "" : message.error);
|
|
48
|
+
if (message.ok) load(message.version).then((next) => alive && set_state(next));
|
|
49
|
+
});
|
|
50
|
+
return () => {
|
|
51
|
+
alive = false;
|
|
52
|
+
events.close();
|
|
53
|
+
};
|
|
54
|
+
}, []);
|
|
55
|
+
|
|
56
|
+
if (!state) return <div className="p-6 text-sm text-muted-foreground">Loading extension…</div>;
|
|
57
|
+
return <App state={state} build={build} />;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
createRoot(document.getElementById("root")!).render(
|
|
61
|
+
<BrowserRouter>
|
|
62
|
+
<Root />
|
|
63
|
+
</BrowserRouter>,
|
|
64
|
+
);
|
package/sandbox/data.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { SEED } from "./seed";
|
|
2
|
+
|
|
3
|
+
export type Row = Record<string, any> & { id: string };
|
|
4
|
+
|
|
5
|
+
type Tables = Map<string, Map<string, Row>>;
|
|
6
|
+
|
|
7
|
+
const FORBIDDEN = new Set(["__proto__", "constructor", "prototype"]);
|
|
8
|
+
|
|
9
|
+
const clone = <T>(value: T): T => structuredClone(value);
|
|
10
|
+
|
|
11
|
+
const clean = (value: unknown): Row | null => {
|
|
12
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
13
|
+
const row: Record<string, unknown> = {};
|
|
14
|
+
for (const [key, item] of Object.entries(value)) if (!FORBIDDEN.has(key)) row[key] = item;
|
|
15
|
+
return typeof row.id === "string" && row.id ? (row as Row) : null;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const fill = (seed: Record<string, unknown>) => {
|
|
19
|
+
const tables: Tables = new Map();
|
|
20
|
+
for (const [name, rows] of Object.entries(seed)) {
|
|
21
|
+
if (FORBIDDEN.has(name) || !Array.isArray(rows)) continue;
|
|
22
|
+
const table = new Map<string, Row>();
|
|
23
|
+
for (const item of rows.slice(0, 5000)) {
|
|
24
|
+
const row = clean(item);
|
|
25
|
+
if (row) table.set(row.id, row);
|
|
26
|
+
}
|
|
27
|
+
tables.set(name, table);
|
|
28
|
+
}
|
|
29
|
+
return tables;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const listeners = new Set<() => void>();
|
|
33
|
+
|
|
34
|
+
let tables: Tables = fill(SEED);
|
|
35
|
+
|
|
36
|
+
let extra: Record<string, unknown> = {};
|
|
37
|
+
|
|
38
|
+
export const emit = () => listeners.forEach((fn) => fn());
|
|
39
|
+
|
|
40
|
+
export const subscribe = (fn: () => void) => {
|
|
41
|
+
listeners.add(fn);
|
|
42
|
+
return () => void listeners.delete(fn);
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export const seed = (custom: Record<string, unknown>) => {
|
|
46
|
+
extra = custom;
|
|
47
|
+
reset();
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export const reset = () => {
|
|
51
|
+
tables = fill({ ...SEED, ...extra });
|
|
52
|
+
emit();
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const table = (name: string) => {
|
|
56
|
+
let found = tables.get(name);
|
|
57
|
+
if (!found) {
|
|
58
|
+
found = new Map();
|
|
59
|
+
tables.set(name, found);
|
|
60
|
+
}
|
|
61
|
+
return found;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export const rows = (name: string) => [...table(name).values()].map(clone);
|
|
65
|
+
|
|
66
|
+
export const get = (name: string, id: string) => {
|
|
67
|
+
const row = table(name).get(String(id));
|
|
68
|
+
return row ? clone(row) : undefined;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export const put = (name: string, value: Row) => {
|
|
72
|
+
const row = clean(clone(value));
|
|
73
|
+
if (!row) throw new Error(`Rows in '${name}' need a string id`);
|
|
74
|
+
table(name).set(row.id, row);
|
|
75
|
+
emit();
|
|
76
|
+
return clone(row);
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export const patch = (name: string, id: string, changes: Record<string, unknown>) => {
|
|
80
|
+
const current = table(name).get(String(id));
|
|
81
|
+
if (!current) throw new Error(`'${id}' doesn't exist in '${name}'`);
|
|
82
|
+
return put(name, { ...current, ...clean({ ...changes, id: current.id })!, id: current.id });
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
export const remove = (name: string, id: string) => {
|
|
86
|
+
table(name).delete(String(id));
|
|
87
|
+
emit();
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
export const value_of = (row: Row, path: string): unknown =>
|
|
91
|
+
path.split(".").reduce<unknown>((node, key) => {
|
|
92
|
+
if (!node || typeof node !== "object" || FORBIDDEN.has(key)) return undefined;
|
|
93
|
+
return (node as Record<string, unknown>)[key];
|
|
94
|
+
}, row);
|