create-signet-app 0.5.0 → 0.7.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 +31 -8
- package/base/api/api/app.ts +57 -8
- package/base/api/api/db/schema.ts +16 -4
- package/base/api/api/env.ts +8 -0
- package/base/api/api/server.ts +6 -0
- package/base/api/api/services.ts +43 -3
- package/base/api/drizzle/0002_ai_paywalls_workflows.sql +77 -0
- package/base/api/drizzle/meta/0002_snapshot.json +1759 -0
- package/base/api/drizzle/meta/_journal.json +7 -0
- package/base/shared/README.md +87 -0
- package/base/web/index.html +5 -0
- package/base/web/src/main.tsx +2 -0
- package/base/web/src/routeTree.gen.ts +25 -0
- package/base/web/src/router.test.ts +1 -0
- package/base/web/src/routes/_app/index.tsx +7 -0
- package/base/web/src/routes/_app.tsx +96 -49
- package/package.json +5 -2
- package/parts/ai/api/api/routes/ai.ts +28 -0
- package/parts/ai/api/test/ai.test.ts +52 -0
- package/parts/ai/part.ts +16 -0
- package/parts/dashboard/part.ts +6 -0
- package/parts/dashboard/web/src/components/overview.test.tsx +16 -0
- package/parts/dashboard/web/src/components/overview.tsx +175 -0
- package/parts/paywalls/api/api/routes/paywall.ts +126 -0
- package/parts/paywalls/api/test/paywalls.test.ts +71 -0
- package/parts/paywalls/part.ts +8 -0
- package/parts/pwa/part.ts +6 -0
- package/parts/pwa/web/public/icon.svg +6 -0
- package/parts/pwa/web/public/manifest.webmanifest +10 -0
- package/parts/pwa/web/public/sw.js +69 -0
- package/parts/pwa/web/src/components/install-button.tsx +14 -0
- package/parts/pwa/web/src/lib/pwa.ts +39 -0
- package/parts/workflows/api/api/workflows.ts +33 -0
- package/parts/workflows/api/test/workflows.test.ts +44 -0
- package/parts/workflows/part.ts +7 -0
- package/parts/workflows/web/src/routes/_app/approvals.tsx +34 -0
- package/src/compose.ts +107 -30
- package/src/desktop.ts +1 -1
- package/src/index.ts +49 -8
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { Badge } from "@dapplelight/signet-ui/components/badge"
|
|
2
|
+
import { Card, CardContent, CardHeader, CardTitle } from "@dapplelight/signet-ui/components/card"
|
|
3
|
+
import { EmptyState } from "@dapplelight/signet-ui/components/empty-state"
|
|
4
|
+
import { ErrorState } from "@dapplelight/signet-ui/components/error-state"
|
|
5
|
+
import { Skeleton } from "@dapplelight/signet-ui/components/skeleton"
|
|
6
|
+
import { type StatItem, StatStrip } from "@dapplelight/signet-ui/components/stat-strip"
|
|
7
|
+
import {
|
|
8
|
+
Table,
|
|
9
|
+
TableBody,
|
|
10
|
+
TableCell,
|
|
11
|
+
TableHead,
|
|
12
|
+
TableHeader,
|
|
13
|
+
TableRow,
|
|
14
|
+
} from "@dapplelight/signet-ui/components/table"
|
|
15
|
+
import { useQuery } from "@tanstack/react-query"
|
|
16
|
+
|
|
17
|
+
export type OverviewData = {
|
|
18
|
+
stats: StatItem[]
|
|
19
|
+
series: { label: string; value: number }[]
|
|
20
|
+
rows: {
|
|
21
|
+
id: string
|
|
22
|
+
name: string
|
|
23
|
+
status: string
|
|
24
|
+
tone?: "default" | "secondary" | "outline" | "destructive"
|
|
25
|
+
date: string
|
|
26
|
+
}[]
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Sample data for the first run. Replace loadOverview with a call to your API
|
|
30
|
+
// (src/lib/api.ts); the page already handles loading, empty and error.
|
|
31
|
+
export const SAMPLE_OVERVIEW: OverviewData = {
|
|
32
|
+
stats: [
|
|
33
|
+
{ label: "Visitors", value: "12,480", meta: "+8.2% vs last week", tone: "good" },
|
|
34
|
+
{ label: "Sign-ups", value: "684", meta: "+3.1% vs last week", tone: "good" },
|
|
35
|
+
{ label: "Active users", value: "3,912", meta: "-1.4% vs last week", tone: "warn" },
|
|
36
|
+
{ label: "Projects", value: "1,207", meta: "42 created today" },
|
|
37
|
+
],
|
|
38
|
+
series: [
|
|
39
|
+
{ label: "Mon", value: 1420 },
|
|
40
|
+
{ label: "Tue", value: 1760 },
|
|
41
|
+
{ label: "Wed", value: 1680 },
|
|
42
|
+
{ label: "Thu", value: 2040 },
|
|
43
|
+
{ label: "Fri", value: 2310 },
|
|
44
|
+
{ label: "Sat", value: 1590 },
|
|
45
|
+
{ label: "Sun", value: 1680 },
|
|
46
|
+
],
|
|
47
|
+
rows: [
|
|
48
|
+
{ id: "1", name: "Acme Studio", status: "Active", date: "Nov 16" },
|
|
49
|
+
{ id: "2", name: "Northwind", status: "Trial", tone: "secondary", date: "Nov 15" },
|
|
50
|
+
{ id: "3", name: "Globex", status: "Active", date: "Nov 15" },
|
|
51
|
+
{ id: "4", name: "Initech", status: "Paused", tone: "outline", date: "Nov 13" },
|
|
52
|
+
{ id: "5", name: "Umbrella Labs", status: "Past due", tone: "destructive", date: "Nov 12" },
|
|
53
|
+
],
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function loadOverview(): Promise<OverviewData> {
|
|
57
|
+
return SAMPLE_OVERVIEW
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function Overview() {
|
|
61
|
+
const q = useQuery({ queryKey: ["overview"], queryFn: loadOverview })
|
|
62
|
+
return (
|
|
63
|
+
<OverviewView
|
|
64
|
+
state={q.isPending ? "loading" : q.isError ? "error" : "ready"}
|
|
65
|
+
data={q.data}
|
|
66
|
+
onRetry={() => q.refetch()}
|
|
67
|
+
/>
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The page itself, by state: what a test or a preview renders without fetching. */
|
|
72
|
+
export function OverviewView({
|
|
73
|
+
state,
|
|
74
|
+
data,
|
|
75
|
+
onRetry,
|
|
76
|
+
}: {
|
|
77
|
+
state: "loading" | "error" | "ready"
|
|
78
|
+
data?: OverviewData
|
|
79
|
+
onRetry?: () => void
|
|
80
|
+
}) {
|
|
81
|
+
const empty = !data || (!data.stats.length && !data.series.length && !data.rows.length)
|
|
82
|
+
return (
|
|
83
|
+
<section className="flex flex-col gap-4 md:gap-6" aria-busy={state === "loading" || undefined}>
|
|
84
|
+
<h1 className="text-title font-semibold">Overview</h1>
|
|
85
|
+
{state === "error" ? (
|
|
86
|
+
<Card>
|
|
87
|
+
<CardContent>
|
|
88
|
+
<ErrorState message="The overview did not load." onRetry={onRetry} />
|
|
89
|
+
</CardContent>
|
|
90
|
+
</Card>
|
|
91
|
+
) : state === "loading" ? (
|
|
92
|
+
<div role="status" aria-label="Loading overview" className="contents">
|
|
93
|
+
<div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
|
|
94
|
+
{[0, 1, 2, 3].map((i) => (
|
|
95
|
+
<Skeleton key={i} className="h-24" />
|
|
96
|
+
))}
|
|
97
|
+
</div>
|
|
98
|
+
<Skeleton className="h-64" />
|
|
99
|
+
<Skeleton className="h-56" />
|
|
100
|
+
</div>
|
|
101
|
+
) : empty ? (
|
|
102
|
+
<Card>
|
|
103
|
+
<CardContent>
|
|
104
|
+
<EmptyState
|
|
105
|
+
title="Nothing here yet"
|
|
106
|
+
description="Numbers show up here once there is activity."
|
|
107
|
+
/>
|
|
108
|
+
</CardContent>
|
|
109
|
+
</Card>
|
|
110
|
+
) : (
|
|
111
|
+
<>
|
|
112
|
+
<StatStrip items={data.stats} />
|
|
113
|
+
<Card>
|
|
114
|
+
<CardHeader>
|
|
115
|
+
<CardTitle>This week</CardTitle>
|
|
116
|
+
</CardHeader>
|
|
117
|
+
<CardContent>
|
|
118
|
+
<BarChart points={data.series} />
|
|
119
|
+
</CardContent>
|
|
120
|
+
</Card>
|
|
121
|
+
<Card>
|
|
122
|
+
<CardHeader>
|
|
123
|
+
<CardTitle>Recent activity</CardTitle>
|
|
124
|
+
</CardHeader>
|
|
125
|
+
<CardContent>
|
|
126
|
+
<Table>
|
|
127
|
+
<TableHeader>
|
|
128
|
+
<TableRow>
|
|
129
|
+
<TableHead>Name</TableHead>
|
|
130
|
+
<TableHead>Status</TableHead>
|
|
131
|
+
<TableHead className="text-right">Date</TableHead>
|
|
132
|
+
</TableRow>
|
|
133
|
+
</TableHeader>
|
|
134
|
+
<TableBody>
|
|
135
|
+
{data.rows.map((r) => (
|
|
136
|
+
<TableRow key={r.id}>
|
|
137
|
+
<TableCell className="font-medium">{r.name}</TableCell>
|
|
138
|
+
<TableCell>
|
|
139
|
+
<Badge variant={r.tone ?? "default"}>{r.status}</Badge>
|
|
140
|
+
</TableCell>
|
|
141
|
+
<TableCell className="text-right text-text-muted">{r.date}</TableCell>
|
|
142
|
+
</TableRow>
|
|
143
|
+
))}
|
|
144
|
+
</TableBody>
|
|
145
|
+
</Table>
|
|
146
|
+
</CardContent>
|
|
147
|
+
</Card>
|
|
148
|
+
</>
|
|
149
|
+
)}
|
|
150
|
+
</section>
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ponytail: plain bars, no chart library. For axes, tooltips or many series,
|
|
155
|
+
// install recharts (an optional peer of signet-ui) and use its Chart component.
|
|
156
|
+
function BarChart({ points }: { points: OverviewData["series"] }) {
|
|
157
|
+
const max = Math.max(1, ...points.map((p) => p.value))
|
|
158
|
+
const summary = points.map((p) => `${p.label} ${p.value.toLocaleString()}`).join(", ")
|
|
159
|
+
return (
|
|
160
|
+
<div role="img" aria-label={`Bar chart: ${summary}`} className="flex h-48 items-end gap-2">
|
|
161
|
+
{points.map((p) => (
|
|
162
|
+
<div key={p.label} className="flex h-full flex-1 flex-col items-center gap-1">
|
|
163
|
+
<div className="flex w-full flex-1 items-end">
|
|
164
|
+
<div
|
|
165
|
+
className="w-full rounded-t-md bg-primary"
|
|
166
|
+
style={{ height: `${(p.value / max) * 100}%` }}
|
|
167
|
+
title={`${p.label}: ${p.value.toLocaleString()}`}
|
|
168
|
+
/>
|
|
169
|
+
</div>
|
|
170
|
+
<span className="text-xs text-text-muted">{p.label}</span>
|
|
171
|
+
</div>
|
|
172
|
+
))}
|
|
173
|
+
</div>
|
|
174
|
+
)
|
|
175
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { ApiException } from "@dapplelight/signet-server/http/errors"
|
|
2
|
+
import { zValidator } from "@dapplelight/signet-server/http/validate"
|
|
3
|
+
import { Hono } from "hono"
|
|
4
|
+
import { z } from "zod"
|
|
5
|
+
import type { AppEnv } from "../app.ts"
|
|
6
|
+
import type { Services } from "../services.ts"
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The paywall a placement ("onboarding", "upgrade") serves the caller now:
|
|
10
|
+
* the first audience override that matches, else the placement's offering.
|
|
11
|
+
* What it serves changes without a release: publish a new offering version
|
|
12
|
+
* and point the placement at it, from code with `s.offerings.publish(...)`
|
|
13
|
+
* and `s.offerings.setPlacement(...)` (see README, "Paywalls"). // @!admin
|
|
14
|
+
* and point the placement at it, through /api/admin/paywalls (below) or from // @admin
|
|
15
|
+
* code with `s.offerings.publish(...)` and `setPlacement(...)`. // @admin
|
|
16
|
+
*
|
|
17
|
+
* GET /:placement?country=IN&platform=web { offering }, or 404
|
|
18
|
+
*/
|
|
19
|
+
export const paywallRoutes = (s: Services) =>
|
|
20
|
+
new Hono<AppEnv>().get(
|
|
21
|
+
"/:placement",
|
|
22
|
+
zValidator("param", z.object({ placement: z.string().min(1).max(64) })),
|
|
23
|
+
zValidator(
|
|
24
|
+
"query",
|
|
25
|
+
z.object({
|
|
26
|
+
country: z.string().length(2).optional(),
|
|
27
|
+
platform: z.string().min(1).max(32).optional(),
|
|
28
|
+
}),
|
|
29
|
+
),
|
|
30
|
+
async (c) => {
|
|
31
|
+
const offering = await s.offerings.current(
|
|
32
|
+
c.req.valid("param").placement,
|
|
33
|
+
c.req.valid("query"),
|
|
34
|
+
c.get("user").id,
|
|
35
|
+
)
|
|
36
|
+
if (!offering) throw new ApiException(404, "No paywall for this placement.", "NOT_FOUND")
|
|
37
|
+
return c.json({ offering })
|
|
38
|
+
},
|
|
39
|
+
)
|
|
40
|
+
// admin:begin
|
|
41
|
+
|
|
42
|
+
const product = z.object({
|
|
43
|
+
/** The store product id, or the web gateway's plan id. */
|
|
44
|
+
id: z.string(),
|
|
45
|
+
store: z.string(),
|
|
46
|
+
/** A plan from api/plans.ts. */
|
|
47
|
+
plan: z.string(),
|
|
48
|
+
interval: z.enum(["month", "year", "once"]).optional(),
|
|
49
|
+
/** What the paywall shows, in minor units. */
|
|
50
|
+
price: z.object({ amount: z.number().int(), currency: z.string() }).optional(),
|
|
51
|
+
/** Trials, intro and win-back offers; checked by signet-db's offerings. */
|
|
52
|
+
offers: z.array(z.any()).optional(),
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
const paywall = z
|
|
56
|
+
.object({
|
|
57
|
+
title: z.string(),
|
|
58
|
+
subtitle: z.string(),
|
|
59
|
+
plans: z.array(z.string()),
|
|
60
|
+
highlight: z.string(),
|
|
61
|
+
badge: z.string(),
|
|
62
|
+
trial: z.string(),
|
|
63
|
+
cta: z.string(),
|
|
64
|
+
})
|
|
65
|
+
.partial()
|
|
66
|
+
|
|
67
|
+
/** signet-db refuses a product, plan or placement that does not check out: a 400. */
|
|
68
|
+
const invalid = (e: unknown): never => {
|
|
69
|
+
if (e instanceof Error && e.name === "SignetDbError")
|
|
70
|
+
throw new ApiException(400, e.message, "VALIDATION_FAILED")
|
|
71
|
+
throw e
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Publishing, for platform admins and staff. A publish is a new version; a
|
|
76
|
+
* published version never changes, so the admin panel only reads these tables.
|
|
77
|
+
*
|
|
78
|
+
* POST /offerings/:key { products, paywall?, note? } the next version
|
|
79
|
+
* PUT /placements/:placement { offering, version?, overrides? }
|
|
80
|
+
*/
|
|
81
|
+
export const paywallAdminRoutes = (s: Services) =>
|
|
82
|
+
new Hono<AppEnv>()
|
|
83
|
+
.use(async (c, next) => {
|
|
84
|
+
const { role } = c.get("user")
|
|
85
|
+
if (role !== "admin" && role !== "staff")
|
|
86
|
+
throw new ApiException(403, "Admins only.", "FORBIDDEN")
|
|
87
|
+
await next()
|
|
88
|
+
})
|
|
89
|
+
.post(
|
|
90
|
+
"/offerings/:key",
|
|
91
|
+
zValidator(
|
|
92
|
+
"json",
|
|
93
|
+
z.object({
|
|
94
|
+
products: z.array(product),
|
|
95
|
+
paywall: paywall.nullish(),
|
|
96
|
+
note: z.string().optional(),
|
|
97
|
+
}),
|
|
98
|
+
),
|
|
99
|
+
async (c) => {
|
|
100
|
+
const actor = { type: "user" as const, id: c.get("user").id }
|
|
101
|
+
const offering = await s.offerings
|
|
102
|
+
.publish(c.req.param("key"), c.req.valid("json"), { actor })
|
|
103
|
+
.catch(invalid)
|
|
104
|
+
return c.json({ offering }, 201)
|
|
105
|
+
},
|
|
106
|
+
)
|
|
107
|
+
.put(
|
|
108
|
+
"/placements/:placement",
|
|
109
|
+
zValidator(
|
|
110
|
+
"json",
|
|
111
|
+
z.object({
|
|
112
|
+
offering: z.string(),
|
|
113
|
+
version: z.number().int().nullish(),
|
|
114
|
+
/** [{ when: { country?, platform?, attributes? }, offering, version? }], first match wins. */
|
|
115
|
+
overrides: z.array(z.any()).optional(),
|
|
116
|
+
}),
|
|
117
|
+
),
|
|
118
|
+
async (c) => {
|
|
119
|
+
const actor = { type: "user" as const, id: c.get("user").id }
|
|
120
|
+
const placement = await s.offerings
|
|
121
|
+
.setPlacement(c.req.param("placement"), c.req.valid("json"), { actor })
|
|
122
|
+
.catch(invalid)
|
|
123
|
+
return c.json({ placement })
|
|
124
|
+
},
|
|
125
|
+
)
|
|
126
|
+
// admin:end
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { createOfferings } from "@dapplelight/signet-db/offerings"
|
|
3
|
+
import { eq } from "drizzle-orm" // @admin
|
|
4
|
+
import * as schema from "../api/db/schema.ts"
|
|
5
|
+
import { app, db, signIn } from "./helpers.ts"
|
|
6
|
+
|
|
7
|
+
const get = (path: string, cookie: string) => app.request(path, { headers: { cookie } })
|
|
8
|
+
|
|
9
|
+
test("a placement serves its offering per audience; an unknown one is a 404", async () => {
|
|
10
|
+
// Published from code, as an app does without the admin panel.
|
|
11
|
+
const offerings = createOfferings(db, { tables: schema })
|
|
12
|
+
const actor = { actor: { type: "system" as const, id: "test" } }
|
|
13
|
+
const products = [
|
|
14
|
+
{ id: "plan_pro_monthly", store: "web", plan: "pro", interval: "month" as const },
|
|
15
|
+
]
|
|
16
|
+
await offerings.publish("standard", { products, paywall: { title: "Go further" } }, actor)
|
|
17
|
+
await offerings.publish("regional", { products, paywall: { title: "Regional" } }, actor)
|
|
18
|
+
await offerings.setPlacement(
|
|
19
|
+
"upgrade",
|
|
20
|
+
{ offering: "standard", overrides: [{ when: { country: ["IN"] }, offering: "regional" }] },
|
|
21
|
+
actor,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
expect((await app.request("/api/paywall/upgrade")).status).toBe(401)
|
|
25
|
+
const cookie = await signIn("+919000000051")
|
|
26
|
+
const res = await get("/api/paywall/upgrade", cookie)
|
|
27
|
+
expect(res.status).toBe(200)
|
|
28
|
+
expect(await res.json()).toMatchObject({
|
|
29
|
+
offering: { key: "standard", version: 1, paywall: { title: "Go further" } },
|
|
30
|
+
})
|
|
31
|
+
expect(await (await get("/api/paywall/upgrade?country=IN", cookie)).json()).toMatchObject({
|
|
32
|
+
offering: { key: "regional" },
|
|
33
|
+
})
|
|
34
|
+
expect((await get("/api/paywall/nowhere", cookie)).status).toBe(404)
|
|
35
|
+
})
|
|
36
|
+
// admin:begin
|
|
37
|
+
|
|
38
|
+
test("admins publish offerings and place them; users get 403", async () => {
|
|
39
|
+
const send = (method: string, path: string, cookie: string, body: unknown) =>
|
|
40
|
+
app.request(path, {
|
|
41
|
+
method,
|
|
42
|
+
headers: { "content-type": "application/json", cookie },
|
|
43
|
+
body: JSON.stringify(body),
|
|
44
|
+
})
|
|
45
|
+
const offering = {
|
|
46
|
+
products: [{ id: "plan_pro_monthly", store: "web", plan: "pro" }],
|
|
47
|
+
paywall: { title: "Pro" },
|
|
48
|
+
}
|
|
49
|
+
const user = await signIn("+919000000052")
|
|
50
|
+
expect((await send("POST", "/api/admin/paywalls/offerings/launch", user, offering)).status).toBe(
|
|
51
|
+
403,
|
|
52
|
+
)
|
|
53
|
+
const staffPhone = "+919000000053"
|
|
54
|
+
const admin = await signIn(staffPhone)
|
|
55
|
+
db.orm.update(schema.users).set({ role: "staff" }).where(eq(schema.users.phone, staffPhone)).run()
|
|
56
|
+
expect((await send("POST", "/api/admin/paywalls/offerings/launch", admin, offering)).status).toBe(
|
|
57
|
+
201,
|
|
58
|
+
)
|
|
59
|
+
const unknownPlan = { products: [{ id: "x", store: "web", plan: "none" }] }
|
|
60
|
+
expect(
|
|
61
|
+
(await send("POST", "/api/admin/paywalls/offerings/launch", admin, unknownPlan)).status,
|
|
62
|
+
).toBe(400)
|
|
63
|
+
const placed = await send("PUT", "/api/admin/paywalls/placements/onboarding", admin, {
|
|
64
|
+
offering: "launch",
|
|
65
|
+
})
|
|
66
|
+
expect(placed.status).toBe(200)
|
|
67
|
+
expect(await (await get("/api/paywall/onboarding", user)).json()).toMatchObject({
|
|
68
|
+
offering: { key: "launch", version: 1 },
|
|
69
|
+
})
|
|
70
|
+
})
|
|
71
|
+
// admin:end
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
|
2
|
+
<!-- A placeholder icon: replace it with your own (keep a square viewBox). -->
|
|
3
|
+
<title>__APP_NAME__</title>
|
|
4
|
+
<rect width="512" height="512" rx="112" fill="#18181b" />
|
|
5
|
+
<circle cx="256" cy="256" r="120" fill="none" stroke="#fafafa" stroke-width="40" />
|
|
6
|
+
</svg>
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "__APP_NAME__",
|
|
3
|
+
"short_name": "__APP_NAME__",
|
|
4
|
+
"start_url": "/",
|
|
5
|
+
"scope": "/",
|
|
6
|
+
"display": "standalone",
|
|
7
|
+
"background_color": "#ffffff",
|
|
8
|
+
"theme_color": "#ffffff",
|
|
9
|
+
"icons": [{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }]
|
|
10
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// The service worker: the app shell works offline. src/lib/pwa.ts registers it
|
|
2
|
+
// in built apps only. Pages come from the network and fall back to the cached
|
|
3
|
+
// shell (index.html); built files under /assets/ have hashed names, so once
|
|
4
|
+
// cached they are served from the cache. /api and /mcp always go to the
|
|
5
|
+
// network, so nothing private is cached. A route chunk never loaded while
|
|
6
|
+
// online is not cached; visit it once, or list it in cacheShell.
|
|
7
|
+
// ponytail: one cache that grows by a few files per deploy; change VERSION to
|
|
8
|
+
// start a fresh one.
|
|
9
|
+
const VERSION = "v1"
|
|
10
|
+
const CACHE = `app-shell-${VERSION}`
|
|
11
|
+
|
|
12
|
+
async function cacheShell() {
|
|
13
|
+
const cache = await caches.open(CACHE)
|
|
14
|
+
const res = await fetch("/", { cache: "no-cache" })
|
|
15
|
+
const html = await res.clone().text()
|
|
16
|
+
const assets = [...html.matchAll(/\/assets\/[^"'\s]+/g)].map((m) => m[0])
|
|
17
|
+
await cache.put("/", res)
|
|
18
|
+
await cache.addAll(["/manifest.webmanifest", "/icon.svg", ...new Set(assets)])
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
self.addEventListener("install", (event) => {
|
|
22
|
+
event.waitUntil(cacheShell().then(() => self.skipWaiting()))
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
self.addEventListener("activate", (event) => {
|
|
26
|
+
event.waitUntil(
|
|
27
|
+
caches
|
|
28
|
+
.keys()
|
|
29
|
+
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
|
|
30
|
+
.then(() => self.clients.claim()),
|
|
31
|
+
)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
self.addEventListener("fetch", (event) => {
|
|
35
|
+
const { request } = event
|
|
36
|
+
const url = new URL(request.url)
|
|
37
|
+
if (request.method !== "GET" || url.origin !== self.location.origin) return
|
|
38
|
+
if (url.pathname.startsWith("/api/") || url.pathname.startsWith("/mcp")) return
|
|
39
|
+
|
|
40
|
+
if (request.mode === "navigate") {
|
|
41
|
+
// Every page is index.html (the server's SPA fallback): keep the newest.
|
|
42
|
+
event.respondWith(
|
|
43
|
+
fetch(request)
|
|
44
|
+
.then((res) => {
|
|
45
|
+
if (res.ok) {
|
|
46
|
+
const copy = res.clone()
|
|
47
|
+
event.waitUntil(caches.open(CACHE).then((c) => c.put("/", copy)))
|
|
48
|
+
}
|
|
49
|
+
return res
|
|
50
|
+
})
|
|
51
|
+
.catch(async () => (await caches.match("/")) ?? Response.error()),
|
|
52
|
+
)
|
|
53
|
+
return
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
event.respondWith(
|
|
57
|
+
caches.match(request).then(
|
|
58
|
+
(hit) =>
|
|
59
|
+
hit ??
|
|
60
|
+
fetch(request).then((res) => {
|
|
61
|
+
if (res.ok && url.pathname.startsWith("/assets/")) {
|
|
62
|
+
const copy = res.clone()
|
|
63
|
+
event.waitUntil(caches.open(CACHE).then((c) => c.put(request, copy)))
|
|
64
|
+
}
|
|
65
|
+
return res
|
|
66
|
+
}),
|
|
67
|
+
),
|
|
68
|
+
)
|
|
69
|
+
})
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Button } from "@dapplelight/signet-ui/components/button"
|
|
2
|
+
import { useSyncExternalStore } from "react"
|
|
3
|
+
import { canInstall, install, subscribeInstall } from "../lib/pwa"
|
|
4
|
+
|
|
5
|
+
/** "Install app", while the browser offers to install it. */
|
|
6
|
+
export function InstallButton() {
|
|
7
|
+
const available = useSyncExternalStore(subscribeInstall, canInstall)
|
|
8
|
+
if (!available) return null
|
|
9
|
+
return (
|
|
10
|
+
<Button variant="outline" size="sm" onClick={() => void install()}>
|
|
11
|
+
Install app
|
|
12
|
+
</Button>
|
|
13
|
+
)
|
|
14
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// The installable app: registers public/sw.js (the offline app shell) and
|
|
2
|
+
// keeps the browser's install prompt for InstallButton. Chromium browsers fire
|
|
3
|
+
// beforeinstallprompt; Safari installs from its Share menu, so there the
|
|
4
|
+
// button never shows.
|
|
5
|
+
|
|
6
|
+
type InstallPromptEvent = Event & { prompt: () => Promise<void> }
|
|
7
|
+
|
|
8
|
+
let deferred: InstallPromptEvent | null = null
|
|
9
|
+
const listeners = new Set<() => void>()
|
|
10
|
+
const set = (e: InstallPromptEvent | null) => {
|
|
11
|
+
deferred = e
|
|
12
|
+
for (const l of listeners) l()
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Call once, before the app renders: the prompt can fire before React mounts. */
|
|
16
|
+
export function registerPwa(): void {
|
|
17
|
+
window.addEventListener("beforeinstallprompt", (e) => {
|
|
18
|
+
e.preventDefault()
|
|
19
|
+
set(e as InstallPromptEvent)
|
|
20
|
+
})
|
|
21
|
+
window.addEventListener("appinstalled", () => set(null))
|
|
22
|
+
// `dev` has no service worker: it would cache Vite's modules under you.
|
|
23
|
+
if (import.meta.env.PROD && "serviceWorker" in navigator)
|
|
24
|
+
navigator.serviceWorker.register("/sw.js").catch(() => {})
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function subscribeInstall(onChange: () => void): () => void {
|
|
28
|
+
listeners.add(onChange)
|
|
29
|
+
return () => listeners.delete(onChange)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const canInstall = (): boolean => deferred !== null
|
|
33
|
+
|
|
34
|
+
/** Shows the browser's install dialog. It can be shown once per event. */
|
|
35
|
+
export async function install(): Promise<void> {
|
|
36
|
+
const e = deferred
|
|
37
|
+
set(null)
|
|
38
|
+
await e?.prompt()
|
|
39
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createWorkflows, defineWorkflow } from "@dapplelight/signet-db/workflows"
|
|
2
|
+
import { z } from "zod"
|
|
3
|
+
import type { Db } from "./db/index.ts"
|
|
4
|
+
import * as schema from "./db/schema.ts"
|
|
5
|
+
|
|
6
|
+
const request = z.object({
|
|
7
|
+
/** What is being asked, as the approvers see it. */
|
|
8
|
+
summary: z.string().min(1).max(200),
|
|
9
|
+
/** User ids; any one of them decides. */
|
|
10
|
+
approvers: z.array(z.string().min(1)).min(1).max(20),
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The example: someone asks, one of the approvers approves or rejects, and
|
|
15
|
+
* the run ends with the decision (a week without one counts as rejected).
|
|
16
|
+
* Copy it for your own: put each side effect in `step.run`, so a replay after
|
|
17
|
+
* a restart does not repeat it.
|
|
18
|
+
*/
|
|
19
|
+
export const approvalRequest = defineWorkflow("approval-request", async (step, input: unknown) => {
|
|
20
|
+
const { summary, approvers } = request.parse(input)
|
|
21
|
+
const decision = await step.approval({ approvers, summary, timeout: 7 * 86_400_000 })
|
|
22
|
+
return { approved: decision.approved, by: decision.by ?? null, reason: decision.reason ?? null }
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
/** Every workflow the app runs. A run of one not listed here fails. */
|
|
26
|
+
export const WORKFLOWS = [approvalRequest]
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The engine over the workflow tables. services.ts serves it to the routes;
|
|
30
|
+
* server.ts runs another over the same database, ticking every second.
|
|
31
|
+
*/
|
|
32
|
+
export const createAppWorkflows = (db: Db) =>
|
|
33
|
+
createWorkflows(db, { tables: schema, workflows: WORKFLOWS })
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { createAppWorkflows } from "../api/workflows.ts"
|
|
3
|
+
import { app, db, post, signIn } from "./helpers.ts"
|
|
4
|
+
|
|
5
|
+
// server.ts runs the runner; the tests tick it by hand.
|
|
6
|
+
const runner = createAppWorkflows(db)
|
|
7
|
+
const get = (path: string, cookie: string) => app.request(path, { headers: { cookie } })
|
|
8
|
+
const userId = async (cookie: string) =>
|
|
9
|
+
((await (await get("/api/account/me", cookie)).json()) as { user: { id: string } }).user.id
|
|
10
|
+
|
|
11
|
+
test("an approval request: started, waiting on its approver, decided, finished", async () => {
|
|
12
|
+
const asker = await signIn("+919000000061")
|
|
13
|
+
const approver = await signIn("+919000000062")
|
|
14
|
+
const other = await signIn("+919000000063")
|
|
15
|
+
const input = { summary: "Approve this request", approvers: [await userId(approver)] }
|
|
16
|
+
const started = await post("/api/workflows/runs", { workflow: "approval-request", input }, asker)
|
|
17
|
+
expect(started.status).toBe(201)
|
|
18
|
+
const run = (await started.json()) as { id: string }
|
|
19
|
+
await runner.tick()
|
|
20
|
+
|
|
21
|
+
expect(await (await get("/api/workflows/approvals", approver)).json()).toMatchObject([
|
|
22
|
+
{ runId: run.id, stepId: "approval", summary: "Approve this request" },
|
|
23
|
+
])
|
|
24
|
+
// Someone else's run reads as missing; only a listed approver decides.
|
|
25
|
+
expect((await get(`/api/workflows/runs/${run.id}`, other)).status).toBe(404)
|
|
26
|
+
const approve = `/api/workflows/runs/${run.id}/steps/approval/approve`
|
|
27
|
+
expect((await post(approve, {}, asker)).status).toBe(403)
|
|
28
|
+
expect((await post(approve, { reason: "Looks right" }, approver)).status).toBe(200)
|
|
29
|
+
await runner.tick()
|
|
30
|
+
|
|
31
|
+
const done = (await (await get(`/api/workflows/runs/${run.id}`, asker)).json()) as {
|
|
32
|
+
run: { status: string; output: unknown }
|
|
33
|
+
}
|
|
34
|
+
expect(done.run).toMatchObject({
|
|
35
|
+
status: "completed",
|
|
36
|
+
output: { approved: true, reason: "Looks right" },
|
|
37
|
+
})
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
test("over HTTP, people start the example workflow and nothing else", async () => {
|
|
41
|
+
const cookie = await signIn("+919000000064")
|
|
42
|
+
const res = await post("/api/workflows/runs", { workflow: "something-else", input: {} }, cookie)
|
|
43
|
+
expect(res.status).toBe(403)
|
|
44
|
+
})
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { ApprovalInboxCard } from "@dapplelight/signet-ui/screens/workflow-screens"
|
|
2
|
+
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
|
3
|
+
import { createFileRoute } from "@tanstack/react-router"
|
|
4
|
+
import { api } from "../../lib/api"
|
|
5
|
+
|
|
6
|
+
export const Route = createFileRoute("/_app/approvals")({
|
|
7
|
+
component: Approvals,
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
// Workflow approval steps waiting on you (signet-db workflows, /api/workflows),
|
|
11
|
+
// each with Approve and Reject. The run carries on at the runner's next tick.
|
|
12
|
+
function Approvals() {
|
|
13
|
+
const qc = useQueryClient()
|
|
14
|
+
const approvals = useQuery({
|
|
15
|
+
queryKey: ["approvals"],
|
|
16
|
+
queryFn: async () => (await api.workflows.approvals.$get()).json(),
|
|
17
|
+
}).data
|
|
18
|
+
if (!approvals) return null
|
|
19
|
+
const decide = (verb: "approve" | "reject") => async (a: { runId: string; stepId: string }) => {
|
|
20
|
+
await api.workflows.runs[":id"].steps[":step"][verb].$post({
|
|
21
|
+
param: { id: a.runId, step: a.stepId },
|
|
22
|
+
})
|
|
23
|
+
await qc.invalidateQueries({ queryKey: ["approvals"] })
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return (
|
|
27
|
+
<ApprovalInboxCard
|
|
28
|
+
approvals={approvals}
|
|
29
|
+
withReason={false}
|
|
30
|
+
onApprove={decide("approve")}
|
|
31
|
+
onReject={decide("reject")}
|
|
32
|
+
/>
|
|
33
|
+
)
|
|
34
|
+
}
|