@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.
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,270 @@
1
+ import type * as ReactType from "react";
2
+ import type { Collection, Host, ReadTable, Row as AnyRow, Where } from "../index";
3
+ import { SCOPES, can_read, has_scope, parse_scope } from "../index.js";
4
+ import * as data from "./data";
5
+ import { notices, prompts, scans, settings } from "./bus";
6
+ import { SESSION } from "./seed";
7
+
8
+ export class ScopeError extends Error {}
9
+
10
+ type Row = data.Row;
11
+
12
+ type Manifest = { id: string; scopes: string[] };
13
+
14
+ const compare = (a: unknown, b: unknown) => (a === b ? 0 : (a as never) > (b as never) ? 1 : -1);
15
+
16
+ const collection = (source: () => Row[]): Collection<AnyRow> => {
17
+ const make = (steps: ((rows: Row[]) => Row[])[]): Collection<AnyRow> => {
18
+ const run = () => steps.reduce((rows, step) => step(rows), source());
19
+ const next = (step: (rows: Row[]) => Row[]) => make([...steps, step]);
20
+ return {
21
+ toArray: async () => run(),
22
+ first: async () => run()[0],
23
+ last: async () => run().at(-1),
24
+ count: async () => run().length,
25
+ filter: (fn) => next((rows) => rows.filter(fn)),
26
+ and: (fn) => next((rows) => rows.filter(fn)),
27
+ limit: (count) => next((rows) => rows.slice(0, Math.max(0, count))),
28
+ offset: (count) => next((rows) => rows.slice(Math.max(0, count))),
29
+ reverse: () => next((rows) => [...rows].reverse()),
30
+ sortBy: async (key) => [...run()].sort((a, b) => compare(data.value_of(a, key), data.value_of(b, key))),
31
+ primaryKeys: async () => run().map((row) => row.id),
32
+ };
33
+ };
34
+ return make([]);
35
+ };
36
+
37
+ const where = (name: string, index: string | AnyRow): Where<AnyRow> & Collection<AnyRow> => {
38
+ const all = () => data.rows(name);
39
+ if (typeof index !== "string") {
40
+ const entries = Object.entries(index);
41
+ return {
42
+ ...collection(() => all().filter((row) => entries.every(([key, value]) => data.value_of(row, key) === value))),
43
+ } as Where<AnyRow> & Collection<AnyRow>;
44
+ }
45
+ const by = (test: (value: unknown) => boolean) =>
46
+ collection(() => all().filter((row) => test(data.value_of(row, index))));
47
+ return {
48
+ ...collection(all),
49
+ equals: (value) => by((item) => item === value),
50
+ anyOf: (values) => by((item) => values.includes(item)),
51
+ noneOf: (values) => by((item) => !values.includes(item)),
52
+ above: (value) => by((item) => compare(item, value) > 0),
53
+ below: (value) => by((item) => compare(item, value) < 0),
54
+ between: (lower, upper) => by((item) => compare(item, lower) >= 0 && compare(item, upper) < 0),
55
+ startsWith: (prefix) => by((item) => typeof item === "string" && item.startsWith(prefix)),
56
+ startsWithIgnoreCase: (prefix) =>
57
+ by((item) => typeof item === "string" && item.toLowerCase().startsWith(prefix.toLowerCase())),
58
+ };
59
+ };
60
+
61
+ const read_table = (name: string): ReadTable<AnyRow> => ({
62
+ ...collection(() => data.rows(name)),
63
+ get: async (id) => data.get(name, id),
64
+ bulkGet: async (ids) => ids.map((id) => data.get(name, id)),
65
+ where: (index) => where(name, index),
66
+ orderBy: (index) =>
67
+ collection(() => data.rows(name).sort((a, b) => compare(data.value_of(a, index), data.value_of(b, index)))),
68
+ toCollection: () => collection(() => data.rows(name)),
69
+ });
70
+
71
+ const offline_id = () => `off_${crypto.randomUUID().replaceAll("-", "")}`;
72
+
73
+ const STORE = "stall-sandbox";
74
+
75
+ const store_of = (extension: string, name: string) => {
76
+ const key = `${STORE}:${extension}:${name}`;
77
+ const load = (): Row[] => {
78
+ try {
79
+ const parsed = JSON.parse(localStorage.getItem(key) ?? "[]");
80
+ return Array.isArray(parsed) ? parsed.filter((row) => row && typeof row.id === "string") : [];
81
+ } catch {
82
+ return [];
83
+ }
84
+ };
85
+ const save = (rows: Row[]) => localStorage.setItem(key, JSON.stringify(rows));
86
+ const query = (fn: (row: Row) => boolean = () => true) => ({
87
+ toArray: async () => load().filter(fn),
88
+ first: async () => load().find(fn),
89
+ count: async () => load().filter(fn).length,
90
+ });
91
+ return {
92
+ ...query(),
93
+ get: async (id: string) => load().find((row) => row.id === id),
94
+ put: async (row: Row) => {
95
+ save([...load().filter((item) => item.id !== row.id), structuredClone(row)]);
96
+ return row;
97
+ },
98
+ bulkPut: async (rows: Row[]) => {
99
+ const ids = new Set(rows.map((row) => row.id));
100
+ save([...load().filter((item) => !ids.has(item.id)), ...structuredClone(rows)]);
101
+ },
102
+ delete: async (id: string) => save(load().filter((row) => row.id !== id)),
103
+ clear: async () => localStorage.removeItem(key),
104
+ where: (fn: (row: Row) => boolean) => query(fn),
105
+ };
106
+ };
107
+
108
+ const sum = (rows: Row[], key: string) => rows.reduce((total, row) => total + (Number(row[key]) || 0), 0);
109
+
110
+ export const create_host = (manifest: Manifest, React: typeof ReactType): Host => {
111
+ const scopes = [...manifest.scopes];
112
+
113
+ const need = (scope: string, write = false) => {
114
+ if (!has_scope(scopes, scope, write))
115
+ throw new ScopeError(`'${manifest.id}' needs the '${write ? `${scope}:write` : scope}' scope`);
116
+ };
117
+
118
+ const db = new Proxy({} as Host["db"], {
119
+ get(_, table) {
120
+ if (typeof table !== "string") return undefined;
121
+ if (!can_read(scopes, table)) throw new ScopeError(`'${manifest.id}' can't read '${table}'`);
122
+ return read_table(table);
123
+ },
124
+ });
125
+
126
+ const writer = (scope: string) => ({
127
+ get: async (id: string) => {
128
+ need(scope);
129
+ return data.get(scope, id);
130
+ },
131
+ create: async (row: AnyRow) => {
132
+ need(scope, true);
133
+ return data.put(scope, { ...row, id: typeof row.id === "string" && row.id ? row.id : offline_id() });
134
+ },
135
+ update: async (id: string, changes: Partial<AnyRow>) => {
136
+ need(scope, true);
137
+ return data.patch(scope, id, changes);
138
+ },
139
+ delete: async (id: string) => {
140
+ need(scope, true);
141
+ data.remove(scope, id);
142
+ },
143
+ });
144
+
145
+ function useLiveQuery<T>(query: () => Promise<T> | T, deps: unknown[] = [], initial?: T) {
146
+ const [value, set_value] = React.useState<T | undefined>(initial);
147
+ React.useEffect(() => {
148
+ let live = true;
149
+ const run = () =>
150
+ Promise.resolve()
151
+ .then(query)
152
+ .then((result) => live && set_value(() => result))
153
+ .catch((error) => console.error("[sandbox] useLiveQuery", error));
154
+ run();
155
+ const stop = data.subscribe(run);
156
+ return () => {
157
+ live = false;
158
+ stop();
159
+ };
160
+ }, deps);
161
+ return value;
162
+ }
163
+
164
+ const report = (kind: "orders" | "payments") => async () => {
165
+ need("reports");
166
+ const rows = data.rows(kind);
167
+ return { mock: true, count: rows.length, gross: sum(rows, kind === "orders" ? "total" : "amount") };
168
+ };
169
+
170
+ const scan = Object.assign(
171
+ () => new Promise<string>((resolve, reject) => prompts.send({ kind: "scan", resolve, reject })),
172
+ { on: (fn: (code: string) => void) => scans.on(fn) },
173
+ );
174
+
175
+ const endpoints = new Proxy({} as Host["endpoints"], {
176
+ get(_, key) {
177
+ if (typeof key !== "string") return undefined;
178
+ throw new Error(`Endpoints need a network and aren't available in the sandbox ('${key}')`);
179
+ },
180
+ });
181
+
182
+ return Object.freeze({
183
+ extension: () => ({ id: manifest.id, scopes: [...scopes] }),
184
+ db,
185
+ useLiveQuery: useLiveQuery as Host["useLiveQuery"],
186
+ offline_id,
187
+ customers: writer("customers"),
188
+ orders: writer("orders"),
189
+ payments: { get: writer("payments").get },
190
+ pay: (input) => {
191
+ need("payments", true);
192
+ return new Promise((resolve) => prompts.send({ kind: "pay", input, resolve }));
193
+ },
194
+ fulfillments: {
195
+ ...writer("fulfillments"),
196
+ quote: async () => {
197
+ need("fulfillments");
198
+ return [];
199
+ },
200
+ },
201
+ taxes: {
202
+ calculate: async (input) => {
203
+ need("taxes");
204
+ const lines = input.lines.map((line) => {
205
+ const subtotal = line.price * line.quantity;
206
+ return { id: line.id, subtotal, tax: 0, total: subtotal, tax_lines: [] };
207
+ });
208
+ const subtotal = lines.reduce((total, line) => total + line.subtotal, 0);
209
+ return {
210
+ lines,
211
+ tax_lines: [],
212
+ subtotal,
213
+ tax: 0,
214
+ shipping: input.fulfillment_cost,
215
+ total: subtotal + input.fulfillment_cost,
216
+ };
217
+ },
218
+ },
219
+ store: { collection: (name: string) => store_of(manifest.id, name) } as unknown as Host["store"],
220
+ scan,
221
+ endpoints,
222
+ refunds: {
223
+ quote: async (input) => {
224
+ need("refunds", true);
225
+ const order = data.get("orders", input.order_id);
226
+ const paid = sum(
227
+ data.rows("payments").filter((row) => row.order_id === input.order_id && row.status === "completed"),
228
+ "amount",
229
+ );
230
+ const refunded = sum(
231
+ data.rows("refunds").filter((row) => row.order_id === input.order_id),
232
+ "amount",
233
+ );
234
+ const refundable = Math.max(0, paid - refunded);
235
+ return {
236
+ currency: String(order?.currency ?? SESSION.currency),
237
+ paid,
238
+ refunded,
239
+ refundable,
240
+ amount: Math.min(input.amount ?? refundable, refundable),
241
+ lines: [],
242
+ allocations: [],
243
+ tenders: [],
244
+ issues: order ? [] : ["Order not found"],
245
+ };
246
+ },
247
+ create: async (input) => {
248
+ need("refunds", true);
249
+ return data.put("refunds", { ...input, id: offline_id(), amount: input.amount ?? 0, created_at: new Date().toISOString() });
250
+ },
251
+ },
252
+ reports: { orders: report("orders"), payments: report("payments") },
253
+ session: {
254
+ user: () => ({ ...SESSION.user }),
255
+ location: () => ({ ...SESSION.location }),
256
+ device: () => ({ ...SESSION.device }),
257
+ currency: () => SESSION.currency,
258
+ active_currency: () => SESSION.currency,
259
+ rates: () => ({ ...SESSION.rates }),
260
+ },
261
+ can: async (module, action) => {
262
+ if (!settings.deny) return true;
263
+ notices.send(`Denied ${module}:${action}. Turn permissions back on in the sandbox bar.`);
264
+ return false;
265
+ },
266
+ } satisfies Host);
267
+ };
268
+
269
+ export const scope_tables = (scopes: string[]) =>
270
+ [...new Set(scopes.flatMap((value) => SCOPES[parse_scope(value).name] ?? []))];
@@ -0,0 +1,111 @@
1
+ const day = (offset: number) => new Date(Date.now() - offset * 86_400_000).toISOString();
2
+
3
+ export const SESSION = {
4
+ user: { id: "usr_sandbox", fullname: "Sandbox Staff", email: "staff@example.com", role: "admin", locations: ["loc_main"] },
5
+ location: { id: "loc_main", name: "Main Store", currency: "USD" },
6
+ device: { id: "dev_sandbox", name: "Sandbox Device", locations: ["loc_main"] },
7
+ currency: "USD",
8
+ rates: { USD: 1, ZAR: 18.2 },
9
+ };
10
+
11
+ const line = (id: string, name: string, price: number, quantity: number) => ({
12
+ id,
13
+ name,
14
+ price,
15
+ quantity,
16
+ total: price * quantity,
17
+ });
18
+
19
+ export const SEED: Record<string, unknown[]> = {
20
+ locations: [SESSION.location],
21
+ products: [
22
+ { id: "prd_coffee", name: "Flat White", price: 3.5, sku: "COF-001", status: "active" },
23
+ { id: "prd_bagel", name: "Bagel", price: 2.75, sku: "BAK-002", status: "active" },
24
+ { id: "prd_mug", name: "Stall Mug", price: 12, sku: "MRC-003", status: "active" },
25
+ ],
26
+ customers: [
27
+ { id: "cus_amy", name: "Amy Moyo", email: "amy@example.com", phone: "+27820000001", created_at: day(20) },
28
+ { id: "cus_ben", name: "Ben Khumalo", email: "ben@example.com", phone: "+27820000002", created_at: day(9) },
29
+ ],
30
+ orders: [
31
+ {
32
+ id: "ord_1001",
33
+ order_number: "1001",
34
+ status: "completed",
35
+ payment_status: "paid",
36
+ currency: "USD",
37
+ subtotal: 9.75,
38
+ total: 9.75,
39
+ customer: { id: "cus_amy", name: "Amy Moyo" },
40
+ line_items: [line("li_1", "Flat White", 3.5, 2), line("li_2", "Bagel", 2.75, 1)],
41
+ location_id: "loc_main",
42
+ notes: [],
43
+ created_at: day(2),
44
+ },
45
+ {
46
+ id: "ord_1002",
47
+ order_number: "1002",
48
+ status: "open",
49
+ payment_status: "partially_paid",
50
+ currency: "USD",
51
+ subtotal: 24,
52
+ total: 24,
53
+ customer: { id: "cus_ben", name: "Ben Khumalo" },
54
+ line_items: [line("li_3", "Stall Mug", 12, 2)],
55
+ location_id: "loc_main",
56
+ notes: [],
57
+ created_at: day(1),
58
+ },
59
+ {
60
+ id: "ord_1003",
61
+ order_number: "1003",
62
+ status: "open",
63
+ payment_status: "unpaid",
64
+ currency: "USD",
65
+ subtotal: 3.5,
66
+ total: 3.5,
67
+ customer: null,
68
+ line_items: [line("li_4", "Flat White", 3.5, 1)],
69
+ location_id: "loc_main",
70
+ notes: [],
71
+ created_at: day(0),
72
+ },
73
+ ],
74
+ payments: [
75
+ {
76
+ id: "pay_1",
77
+ order_id: "ord_1001",
78
+ amount: 9.75,
79
+ currency: "USD",
80
+ status: "completed",
81
+ payment_method: { id: "pm_cash", name: "Cash" },
82
+ created_at: day(2),
83
+ },
84
+ {
85
+ id: "pay_2",
86
+ order_id: "ord_1002",
87
+ amount: 10,
88
+ currency: "USD",
89
+ status: "completed",
90
+ payment_method: { id: "pm_card", name: "Card" },
91
+ created_at: day(1),
92
+ },
93
+ {
94
+ id: "pay_3",
95
+ order_id: "ord_1003",
96
+ amount: 3.5,
97
+ currency: "USD",
98
+ status: "pending",
99
+ payment_method: { id: "pm_mobile", name: "Mobile money" },
100
+ created_at: day(0),
101
+ },
102
+ ],
103
+ payment_methods: [
104
+ { id: "pm_cash", name: "Cash" },
105
+ { id: "pm_card", name: "Card" },
106
+ { id: "pm_mobile", name: "Mobile money" },
107
+ ],
108
+ refunds: [],
109
+ fulfillments: [],
110
+ register_sessions: [{ id: "reg_1", status: "open", opening_balance: 50, location_id: "loc_main", created_at: day(0) }],
111
+ };
@@ -0,0 +1,3 @@
1
+ declare module "stall-sandbox:shared" {
2
+ export const modules: Record<string, unknown>;
3
+ }
@@ -0,0 +1,132 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://usestall.com/schemas/extension.schema.json",
4
+ "title": "Stall extension manifest",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "required": [
8
+ "id",
9
+ "name",
10
+ "description",
11
+ "icon",
12
+ "color",
13
+ "version",
14
+ "host",
15
+ "authors",
16
+ "keywords",
17
+ "entrypoint",
18
+ "scopes",
19
+ "widgets",
20
+ "endpoints"
21
+ ],
22
+ "properties": {
23
+ "$schema": { "type": "string" },
24
+ "id": {
25
+ "type": "string",
26
+ "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",
27
+ "maxLength": 64,
28
+ "not": { "const": "system" },
29
+ "description": "Lowercase slug, unique across Stall"
30
+ },
31
+ "name": { "type": "string", "minLength": 1, "maxLength": 80 },
32
+ "description": { "type": "string", "minLength": 1, "maxLength": 500 },
33
+ "keywords": { "type": "array", "items": { "type": "string", "minLength": 1, "maxLength": 40 }, "maxItems": 20 },
34
+ "icon": { "type": "string", "description": "Path to the icon, e.g. /assets/icon.png" },
35
+ "color": { "type": "string", "pattern": "^(#[0-9a-fA-F]{6})?$" },
36
+ "version": { "type": "string", "minLength": 1, "description": "Must match package.json" },
37
+ "host": {
38
+ "type": "string",
39
+ "pattern": "^\\d{4}-(0[1-9]|1[0-2])$",
40
+ "description": "Host API version this extension was built against (YYYY-MM), e.g. 2026-12",
41
+ "examples": ["2026-12"]
42
+ },
43
+ "authors": { "type": "array", "items": { "type": "string", "minLength": 1 }, "maxItems": 20 },
44
+ "entrypoint": {
45
+ "type": "object",
46
+ "additionalProperties": false,
47
+ "required": ["id", "type"],
48
+ "properties": {
49
+ "id": { "type": "string", "minLength": 1 },
50
+ "type": { "enum": ["page", "lookup"] }
51
+ }
52
+ },
53
+ "scopes": {
54
+ "type": "array",
55
+ "uniqueItems": true,
56
+ "items": {
57
+ "type": "string",
58
+ "pattern": "^(locations|catalog|products|variants|categories|collections|inventory|customers|orders|refunds|payments|payment_methods|fulfillments|fulfillment_methods|taxes|sales_channels|register_sessions|reports)(:write)?$"
59
+ }
60
+ },
61
+ "widgets": { "type": "array", "maxItems": 100, "items": { "$ref": "#/$defs/widget" } },
62
+ "endpoints": {
63
+ "type": "object",
64
+ "propertyNames": { "pattern": "^[a-z0-9-]+$" },
65
+ "additionalProperties": { "$ref": "#/$defs/endpoint" }
66
+ }
67
+ },
68
+ "$defs": {
69
+ "widget": {
70
+ "type": "object",
71
+ "additionalProperties": false,
72
+ "required": ["id", "title", "icon", "type", "configs"],
73
+ "properties": {
74
+ "id": { "type": "string", "pattern": "^[a-z0-9-]+$" },
75
+ "title": { "type": "string", "minLength": 1 },
76
+ "icon": { "type": "string", "description": "A @use-stall/icons export name, or empty" },
77
+ "type": { "enum": ["action", "value"] },
78
+ "configs": {
79
+ "type": "object",
80
+ "additionalProperties": false,
81
+ "required": ["value_handler", "badge_handler", "required_permission", "on_click"],
82
+ "properties": {
83
+ "value_handler": { "type": "string" },
84
+ "badge_handler": { "type": "string" },
85
+ "required_permission": { "type": "string", "pattern": "^([a-z_]+:(create|read|update|delete))?$" },
86
+ "on_click": {
87
+ "type": "object",
88
+ "additionalProperties": false,
89
+ "required": ["type", "value"],
90
+ "properties": {
91
+ "type": { "enum": ["none", "navigate", "function"] },
92
+ "value": { "type": "string" }
93
+ }
94
+ }
95
+ }
96
+ }
97
+ }
98
+ },
99
+ "endpoint": {
100
+ "type": "object",
101
+ "additionalProperties": false,
102
+ "required": ["url", "paths"],
103
+ "properties": {
104
+ "url": { "type": "string", "pattern": "^https://" },
105
+ "paths": {
106
+ "type": "array",
107
+ "minItems": 1,
108
+ "maxItems": 100,
109
+ "items": {
110
+ "type": "object",
111
+ "additionalProperties": false,
112
+ "required": ["method", "path"],
113
+ "properties": {
114
+ "method": { "enum": ["GET", "POST", "PUT", "PATCH", "DELETE"] },
115
+ "path": { "type": "string", "maxLength": 256, "pattern": "^/" },
116
+ "schema": {
117
+ "type": "object",
118
+ "additionalProperties": false,
119
+ "properties": {
120
+ "params": { "type": "object" },
121
+ "query": { "type": "object" },
122
+ "body": { "type": "object" },
123
+ "response": { "type": "object" }
124
+ }
125
+ }
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }