@pet-adopt/plugin-sdk 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/LICENSE +21 -0
- package/README.md +96 -2
- package/dist/index.d.ts +631 -0
- package/dist/index.js +243 -0
- package/package.json +51 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 muhammadarifftaha
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,97 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pet-adopt/plugin-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> **Not published yet:** this package is not on npm yet. It is published with the first release of Pet Adopt.
|
|
4
|
+
|
|
5
|
+
Types and helpers for writing plugins for [Pet Adopt](https://github.com/muhammadarifftaha/pet-adopt), an open-source storefront for adoptable pets.
|
|
6
|
+
|
|
7
|
+
A plugin can add admin screens, dashboard cards, page builder blocks, its own database tables, default email templates and an email sender. This package is everything a plugin imports: it contains no part of the site itself.
|
|
8
|
+
|
|
9
|
+
**The full guide to writing a plugin is [in the docs](https://github.com/muhammadarifftaha/pet-adopt/blob/main/apps/docs/content/docs/developers/plugins/index.mdx).**
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
List it as a **peer dependency**, so your plugin uses the same copy as the site it is added to, and as a dev dependency to build against:
|
|
14
|
+
|
|
15
|
+
```json
|
|
16
|
+
{
|
|
17
|
+
"peerDependencies": {
|
|
18
|
+
"@pet-adopt/plugin-sdk": "^0.1.0"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@pet-adopt/plugin-sdk": "^0.1.0"
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
A plugin that bundles its own copy would have its errors go unrecognised by the site, because they are matched by class.
|
|
27
|
+
|
|
28
|
+
`react` and `react-icons` are peer dependencies. `drizzle-orm` is one too, and is only needed by a plugin with its own tables.
|
|
29
|
+
|
|
30
|
+
## A small plugin
|
|
31
|
+
|
|
32
|
+
```tsx
|
|
33
|
+
import { definePlugin } from '@pet-adopt/plugin-sdk'
|
|
34
|
+
|
|
35
|
+
export const hello = definePlugin(() => ({
|
|
36
|
+
name: 'hello',
|
|
37
|
+
title: 'Hello',
|
|
38
|
+
description: 'Adds one screen to the admin.',
|
|
39
|
+
screens: [
|
|
40
|
+
{
|
|
41
|
+
path: '',
|
|
42
|
+
title: 'Hello',
|
|
43
|
+
nav: { label: 'Hello', Icon: { viewBox: '0 0 24 24', paths: ['M12 2 2 22h20z'], outline: true } },
|
|
44
|
+
component: ({ user }) => <p>Hello {user.name}.</p>,
|
|
45
|
+
},
|
|
46
|
+
],
|
|
47
|
+
}))
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The site lists it in `apps/web/pet-adopt.config.ts`:
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { defineConfig } from '@pet-adopt/plugin-sdk'
|
|
54
|
+
import { hello } from 'pet-adopt-plugin-hello'
|
|
55
|
+
|
|
56
|
+
export default defineConfig({ plugins: [hello()] })
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Page builder blocks
|
|
60
|
+
|
|
61
|
+
A block has two halves. The block itself (`definePluginBlock`: its name, options and how it is drawn) is loaded by the browser, so it lives in a module of its own that imports nothing server-only, and a site lists it in `apps/web/pet-adopt.blocks.ts`:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { defineBlocks } from '@pet-adopt/plugin-sdk'
|
|
65
|
+
import { helloBlock } from 'pet-adopt-plugin-hello/block'
|
|
66
|
+
|
|
67
|
+
export default defineBlocks([helloBlock])
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Its loader (`blockLoaders` on the plugin) runs on the server and returns what the block shows. Blocks are styled with plain CSS on the site's theme variables (`var(--primary)`, `var(--surface)`, `var(--radius)`...), because the public site does not load Tailwind; start every selector with a class of your own.
|
|
71
|
+
|
|
72
|
+
## What is in it
|
|
73
|
+
|
|
74
|
+
- **`definePlugin`, `defineConfig`:** declare a plugin and a site's list of plugins.
|
|
75
|
+
- **`definePluginBlock`, `defineBlocks`:** page builder blocks and a site's list of them.
|
|
76
|
+
- **`definePluginStorage`:** a plugin's own tables and migrations, for SQLite and PostgreSQL. Table names start with the plugin's prefix (`pluginTablePrefix`).
|
|
77
|
+
- **`host()`:** the site's services: permission checks, rate limits, templated email, the activity log, encrypted secrets, the privacy policy, the site's address and time zone.
|
|
78
|
+
- **Roles and permissions:** `ROLES`, `can`, `accessPermission`.
|
|
79
|
+
- **Errors and results:** `UserError`, `ValidationError`, `ActionResult`.
|
|
80
|
+
- **Helpers:** `formatWhen` and the time zone functions, `foldText` for search, `csvCell` for safe CSV.
|
|
81
|
+
|
|
82
|
+
## Rules for plugins
|
|
83
|
+
|
|
84
|
+
- **Depend only on this package** (and the site's UI package, `@pet-adopt/ui`, for admin screens). Never import the site.
|
|
85
|
+
- **Check permissions in every server action** with `host().requirePermission(...)`, wrapped in `host().run(...)`.
|
|
86
|
+
- **Log errors with `host().logError`,** never the error object: a database error can carry the values it was given.
|
|
87
|
+
- **Ship compiled JavaScript** when you publish a plugin to npm, and keep `'use client'` and `'use server'` as the first line of the files that have them (plain `tsc`, file by file, does). The guide says how.
|
|
88
|
+
|
|
89
|
+
Two plugins published from the repository show a full plugin: [`@pet-adopt/plugin-form-builder`](https://github.com/muhammadarifftaha/pet-adopt/tree/main/plugins/form-builder) and [`@pet-adopt/plugin-instagram-feed`](https://github.com/muhammadarifftaha/pet-adopt/tree/main/plugins/instagram-feed). [`adoption-tips`](https://github.com/muhammadarifftaha/pet-adopt/tree/main/plugins/adoption-tips) is a small example to copy (not on npm).
|
|
90
|
+
|
|
91
|
+
## Versions
|
|
92
|
+
|
|
93
|
+
The package is below 1.0, so a minor version may change the API. Pin the minor version you built against.
|
|
94
|
+
|
|
95
|
+
## Licence
|
|
96
|
+
|
|
97
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,631 @@
|
|
|
1
|
+
import type React from 'react';
|
|
2
|
+
import type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
|
|
3
|
+
import type { IconType } from 'react-icons';
|
|
4
|
+
/** Who can sign in to the admin. */
|
|
5
|
+
export declare const ROLES: readonly ["admin", "editor", "developer", "audit"];
|
|
6
|
+
export type Role = (typeof ROLES)[number];
|
|
7
|
+
export declare const ROLE_INFO: Record<Role, {
|
|
8
|
+
label: string;
|
|
9
|
+
description: string;
|
|
10
|
+
}>;
|
|
11
|
+
/**
|
|
12
|
+
* What a permission covers. `pluginContent`, `plugins` and `personalData` are the three levels a
|
|
13
|
+
* plugin screen can ask for (see PluginAccess); the rest are the site's own areas.
|
|
14
|
+
*/
|
|
15
|
+
export declare const AREAS: readonly ["pets", "pages", "media", "theme", "settings", "plugins", "users", "pluginContent", "personalData"];
|
|
16
|
+
export type Area = (typeof AREAS)[number];
|
|
17
|
+
/**
|
|
18
|
+
* `area:view` or `area:edit`, plus downloading personal data (form responses as CSV) and the
|
|
19
|
+
* activity log: everyone reads their own entries (`activity:own`); admins and audit read everyone's
|
|
20
|
+
* (`activity:view`) and download it (`activity:export`).
|
|
21
|
+
*/
|
|
22
|
+
export type Permission = `${Area}:${'view' | 'edit'}` | 'personalData:export' | 'activity:own' | 'activity:view' | 'activity:export';
|
|
23
|
+
/** Whether `role` has `permission`. An unknown role has none. */
|
|
24
|
+
export declare function can(role: Role | null | undefined, permission: Permission): boolean;
|
|
25
|
+
/** A stored role string as a Role. Anything unknown becomes `audit`, which changes nothing. */
|
|
26
|
+
export declare function asRole(value: unknown): Role;
|
|
27
|
+
/**
|
|
28
|
+
* Who a plugin screen or widget is for:
|
|
29
|
+
* - `all`: the whole team (admins, editors, developers; audit can view). The default.
|
|
30
|
+
* - `admin`: admins and developers (audit can view): setup, integrations.
|
|
31
|
+
* - `personalData`: what visitors sent (form responses, sign-ups): admins and editors (audit can
|
|
32
|
+
* view, developers cannot).
|
|
33
|
+
*/
|
|
34
|
+
export type PluginAccess = 'all' | 'admin' | 'personalData';
|
|
35
|
+
/** The permission a plugin screen or action needs: `accessPermission('personalData', 'edit')`. */
|
|
36
|
+
export declare function accessPermission(access: PluginAccess, level: 'view' | 'edit'): Permission;
|
|
37
|
+
/** A screen's or widget's access, reading the older `adminOnly` flag too. */
|
|
38
|
+
export declare function accessOf(item: {
|
|
39
|
+
access?: PluginAccess;
|
|
40
|
+
adminOnly?: boolean;
|
|
41
|
+
}): PluginAccess;
|
|
42
|
+
/** The signed-in person a screen or widget is shown to. The app's session user has this shape. */
|
|
43
|
+
export type PluginUser = {
|
|
44
|
+
id: string;
|
|
45
|
+
email: string;
|
|
46
|
+
name: string;
|
|
47
|
+
role: Role;
|
|
48
|
+
};
|
|
49
|
+
/** What a plugin screen or dashboard widget receives. Both are server components by default. */
|
|
50
|
+
export type PluginScreenProps = {
|
|
51
|
+
user: PluginUser;
|
|
52
|
+
/** Values of `:name` segments in the screen's path (`items/:id` gives `{ id: '3' }`). */
|
|
53
|
+
params: Record<string, string>;
|
|
54
|
+
searchParams: Record<string, string | string[] | undefined>;
|
|
55
|
+
};
|
|
56
|
+
export type PluginWidgetProps = {
|
|
57
|
+
user: PluginUser;
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* An SVG drawn from path data: the `d` of each <path>, in a `viewBox` (default "0 0 24 24"). Filled
|
|
61
|
+
* with the text colour, or drawn as a 2px outline when `outline` is set. Raw markup is not accepted.
|
|
62
|
+
*/
|
|
63
|
+
export type SvgIcon = {
|
|
64
|
+
viewBox?: string;
|
|
65
|
+
paths: string[];
|
|
66
|
+
outline?: boolean;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* What a plugin can use as a menu icon, and nothing else: a react-icons icon (`FiStar` from
|
|
70
|
+
* "react-icons/fi") or an `SvgIcon`. Anything else is rejected when the config loads.
|
|
71
|
+
*/
|
|
72
|
+
export type PluginIcon = IconType | SvgIcon;
|
|
73
|
+
export type PluginScreen = {
|
|
74
|
+
/**
|
|
75
|
+
* Path under `/admin/plugins/<plugin name>/`. `''` is the plugin's home screen. Segments that
|
|
76
|
+
* start with `:` are parameters (`items/:id`). Screens with parameters never appear in the menu.
|
|
77
|
+
*/
|
|
78
|
+
path: string;
|
|
79
|
+
/** Page title, and the menu label unless `nav.label` is set. */
|
|
80
|
+
title: string;
|
|
81
|
+
component: (props: PluginScreenProps) => React.ReactNode | Promise<React.ReactNode>;
|
|
82
|
+
/** Menu label. Defaults to `title`. */
|
|
83
|
+
/**
|
|
84
|
+
* How the screen looks in the menu: `nav: { label: 'Reports', Icon: FiBarChart2 }`. `label`
|
|
85
|
+
* defaults to `title`; `Icon` is a react-icons icon or an `SvgIcon` (a package icon if left out).
|
|
86
|
+
*/
|
|
87
|
+
nav?: {
|
|
88
|
+
label?: string;
|
|
89
|
+
Icon?: PluginIcon;
|
|
90
|
+
};
|
|
91
|
+
/** Leave the screen out of the menu (it is still reachable by URL). */
|
|
92
|
+
hidden?: boolean;
|
|
93
|
+
/**
|
|
94
|
+
* Who can open it (see PluginAccess; default `all`). People without access get no menu entry and
|
|
95
|
+
* are sent to the dashboard. The screen's server actions must still check the same level with
|
|
96
|
+
* `host().requirePermission(accessPermission(access, 'view' | 'edit'))`.
|
|
97
|
+
*/
|
|
98
|
+
access?: PluginAccess;
|
|
99
|
+
/** @deprecated Use `access: 'admin'`. */
|
|
100
|
+
adminOnly?: boolean;
|
|
101
|
+
};
|
|
102
|
+
export type PluginWidget = {
|
|
103
|
+
/** Unique within the plugin. */
|
|
104
|
+
id: string;
|
|
105
|
+
title: string;
|
|
106
|
+
component: (props: PluginWidgetProps) => React.ReactNode | Promise<React.ReactNode>;
|
|
107
|
+
/** Who sees it on the dashboard (see PluginAccess; default `all`). */
|
|
108
|
+
access?: PluginAccess;
|
|
109
|
+
/** @deprecated Use `access: 'admin'`. */
|
|
110
|
+
adminOnly?: boolean;
|
|
111
|
+
};
|
|
112
|
+
/** One email. `text` is always sent; `html` is the formatted version, when the sender supports it. */
|
|
113
|
+
export type EmailMessage = {
|
|
114
|
+
to: string;
|
|
115
|
+
subject: string;
|
|
116
|
+
text: string;
|
|
117
|
+
html?: string;
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* How an email plugin reports its setup on its admin page. Never put a secret in `details`: say
|
|
121
|
+
* whether it is set ("Set" / "Not set"), not what it is.
|
|
122
|
+
*/
|
|
123
|
+
export type EmailStatus = {
|
|
124
|
+
/** The service, e.g. "Postmark API". */
|
|
125
|
+
provider: string;
|
|
126
|
+
/** Everything it needs is set. While false the site falls back to its built-in SMTP sender, if that is set up. */
|
|
127
|
+
ready: boolean;
|
|
128
|
+
/** Non-secret settings to show, e.g. `{ label: 'Sender', value: 'Pet Adopt <no-reply@…>' }`. */
|
|
129
|
+
details?: Array<{
|
|
130
|
+
label: string;
|
|
131
|
+
value: string;
|
|
132
|
+
}>;
|
|
133
|
+
/** How to finish the setup, shown while `ready` is false. */
|
|
134
|
+
setup?: string;
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* How the site sends email (password reset links). At most one plugin may provide it. `send` runs on
|
|
138
|
+
* the server and should throw when the message was not accepted, so the failure is logged.
|
|
139
|
+
* `status`, when given, is shown on the plugin's admin page; a sender that reports `ready: false`
|
|
140
|
+
* is treated as missing, so the site never offers email it cannot send.
|
|
141
|
+
*/
|
|
142
|
+
export type EmailSender = {
|
|
143
|
+
send: (message: EmailMessage) => Promise<void>;
|
|
144
|
+
status?: () => EmailStatus;
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* One change to a plugin's tables, written once for each database. Generate them from the plugin's
|
|
148
|
+
* schema with `pnpm plugin:generate <plugin folder>` rather than by hand.
|
|
149
|
+
*/
|
|
150
|
+
export type PluginMigration = {
|
|
151
|
+
/** Runs in id order: "0000_init", "0001_notes". Never rename, edit or remove one that has shipped. */
|
|
152
|
+
id: string;
|
|
153
|
+
/** The SQL. Several statements are separated by `--> statement-breakpoint` lines (drizzle-kit's output). */
|
|
154
|
+
sqlite: string;
|
|
155
|
+
pg: string;
|
|
156
|
+
};
|
|
157
|
+
/**
|
|
158
|
+
* Tables a plugin owns. Every table (and index) name starts with `pluginTablePrefix(name)`, so two
|
|
159
|
+
* plugins, or a plugin and the site, can never claim the same table. Plugin tables do not reference
|
|
160
|
+
* the site's own tables. `pnpm migrate` applies the migrations (SQLite also applies them on start);
|
|
161
|
+
* until it has, the plugin's screens show a notice instead and its widgets are left out.
|
|
162
|
+
*/
|
|
163
|
+
export type PluginStorage = {
|
|
164
|
+
/** The Drizzle tables, as twins (same tables and columns) for each database. */
|
|
165
|
+
tables: {
|
|
166
|
+
sqlite: Record<string, unknown>;
|
|
167
|
+
pg: Record<string, unknown>;
|
|
168
|
+
};
|
|
169
|
+
migrations: readonly PluginMigration[];
|
|
170
|
+
};
|
|
171
|
+
/** "form-builder" -> "plugin_form_builder_": what every table and index of that plugin starts with. */
|
|
172
|
+
export declare const pluginTablePrefix: (pluginName: string) => string;
|
|
173
|
+
/** The query builder plugins get: Drizzle's async SQLite API, whichever SQLite driver the site uses. */
|
|
174
|
+
export type PluginDb = BaseSQLiteDatabase<'async', unknown, Record<string, unknown>>;
|
|
175
|
+
/**
|
|
176
|
+
* A plugin's tables, opened on the site's database. Write queries once against `t` (typed as the
|
|
177
|
+
* SQLite tables); on PostgreSQL `t` holds the Postgres twins, so the same code runs on both.
|
|
178
|
+
*/
|
|
179
|
+
export type PluginDatabase<Tables> = {
|
|
180
|
+
dialect: 'sqlite' | 'pg';
|
|
181
|
+
db: PluginDb;
|
|
182
|
+
t: Tables;
|
|
183
|
+
/** Runs `fn` atomically. `lock` serialises transactions that use the same name (PostgreSQL). */
|
|
184
|
+
withTransaction<T>(fn: (tx: PluginDb) => Promise<T>, options?: {
|
|
185
|
+
lock?: string;
|
|
186
|
+
}): Promise<T>;
|
|
187
|
+
};
|
|
188
|
+
/** What `definePluginStorage` returns: pass it as the plugin's `storage`, and `open()` it in server code. */
|
|
189
|
+
export type PluginStorageHandle<SqliteTables extends Record<string, unknown>, PgTables extends Record<string, unknown>> = PluginStorage & {
|
|
190
|
+
tables: {
|
|
191
|
+
sqlite: SqliteTables;
|
|
192
|
+
pg: PgTables;
|
|
193
|
+
};
|
|
194
|
+
/**
|
|
195
|
+
* Opens the plugin's tables. Throws, with a message an owner can act on, until `pnpm migrate`
|
|
196
|
+
* has set them up. Server-only.
|
|
197
|
+
*/
|
|
198
|
+
open(): Promise<PluginDatabase<SqliteTables>>;
|
|
199
|
+
};
|
|
200
|
+
type StorageProvider = (storage: PluginStorage) => Promise<PluginDatabase<unknown>>;
|
|
201
|
+
/**
|
|
202
|
+
* A plugin's tables and migrations, plus a way to open them. The app does the opening: a plugin
|
|
203
|
+
* never imports the app's database, only this package and drizzle-orm (for its table definitions).
|
|
204
|
+
*
|
|
205
|
+
* export const storage = definePluginStorage({ tables: { sqlite, pg }, migrations })
|
|
206
|
+
* definePlugin({ name: 'my-plugin', storage, ... })
|
|
207
|
+
* const { db, t } = await storage.open()
|
|
208
|
+
*/
|
|
209
|
+
export declare function definePluginStorage<SqliteTables extends Record<string, unknown>, PgTables extends Record<string, unknown>>(storage: {
|
|
210
|
+
tables: {
|
|
211
|
+
sqlite: SqliteTables;
|
|
212
|
+
pg: PgTables;
|
|
213
|
+
};
|
|
214
|
+
migrations: readonly PluginMigration[];
|
|
215
|
+
}): PluginStorageHandle<SqliteTables, PgTables>;
|
|
216
|
+
/** For the app only: how plugin storage is opened. Plugins never call this. */
|
|
217
|
+
export declare function provideStorage(provider: StorageProvider): void;
|
|
218
|
+
export type Plugin = {
|
|
219
|
+
/** Lowercase letters, digits and dashes. Used in the URL, so renaming it moves the screens. */
|
|
220
|
+
name: string;
|
|
221
|
+
/** Shown in the admin (menu, plugin list, its page). Defaults to the name, humanised. */
|
|
222
|
+
title?: string;
|
|
223
|
+
/** One or two sentences on what it does, shown on its page and in the plugin list. */
|
|
224
|
+
description?: string;
|
|
225
|
+
/** Screens that get their own page and menu entry. */
|
|
226
|
+
screens?: PluginScreen[];
|
|
227
|
+
/** Cards shown under the dashboard's numbers. */
|
|
228
|
+
dashboardWidgets?: PluginWidget[];
|
|
229
|
+
/**
|
|
230
|
+
* Sends the site's email through a service of its own (an HTTP API, for hosts that block SMTP
|
|
231
|
+
* ports) instead of the built-in SMTP settings (Email > Sending). At most one plugin may provide
|
|
232
|
+
* it; while it reports ready (or has no `status`) it is used instead of SMTP. Without one, the site uses SMTP.
|
|
233
|
+
*/
|
|
234
|
+
email?: EmailSender;
|
|
235
|
+
/** Its own tables and the migrations that create them. */
|
|
236
|
+
storage?: PluginStorage;
|
|
237
|
+
/**
|
|
238
|
+
* Which of the site's email templates it uses, for the "Used by" column of Email > Sending
|
|
239
|
+
* templates and the warning before one is deleted. Server-only; a failure leaves the column empty.
|
|
240
|
+
*/
|
|
241
|
+
emailTemplateUsage?: () => Promise<EmailTemplateUse[]>;
|
|
242
|
+
/**
|
|
243
|
+
* Default templates this plugin ships. Each is created in Email > Templates at server
|
|
244
|
+
* start if missing (as `<plugin name>:<key>`), can be edited and restored but not deleted, and is
|
|
245
|
+
* what `sendTemplatedEmail({ fallback })` uses when no other template is picked, so the plugin's
|
|
246
|
+
* emails always have a template.
|
|
247
|
+
*/
|
|
248
|
+
emailTemplates?: PluginEmailTemplate[];
|
|
249
|
+
/**
|
|
250
|
+
* The server half of the page builder blocks this plugin adds: for each block's `name`, the
|
|
251
|
+
* function that loads what it shows (see `PluginBlock`). Server-only. It runs for visitors and
|
|
252
|
+
* for the page builder's preview, so it must return only what any visitor may see.
|
|
253
|
+
*/
|
|
254
|
+
blockLoaders?: Record<string, PluginBlockLoader>;
|
|
255
|
+
/** Other plugins this one is built from (flattened, in order, before this one). */
|
|
256
|
+
plugins?: Plugin[];
|
|
257
|
+
};
|
|
258
|
+
/**
|
|
259
|
+
* One place an email template is used: `Form “Adopt” (notification)`, with a link to it. Either the
|
|
260
|
+
* template picked (`templateId`) or, when none is, the plugin's default (`seedKey`, `<plugin>:<key>`).
|
|
261
|
+
*/
|
|
262
|
+
export type EmailTemplateUse = {
|
|
263
|
+
templateId?: number;
|
|
264
|
+
seedKey?: string;
|
|
265
|
+
label: string;
|
|
266
|
+
href?: string;
|
|
267
|
+
};
|
|
268
|
+
/**
|
|
269
|
+
* A default template a plugin ships. `key`: lowercase letters, digits and dashes, unique in the
|
|
270
|
+
* plugin. `data`: a layout in the site's template format (Puck data of the email builder's blocks);
|
|
271
|
+
* left out, or not valid, the site's built-in email of that purpose is used.
|
|
272
|
+
*/
|
|
273
|
+
export type PluginEmailTemplate = {
|
|
274
|
+
key: string;
|
|
275
|
+
name: string;
|
|
276
|
+
purpose: PluginEmailPurpose;
|
|
277
|
+
data?: unknown;
|
|
278
|
+
};
|
|
279
|
+
export type Config = {
|
|
280
|
+
plugins?: Plugin[];
|
|
281
|
+
};
|
|
282
|
+
/** Wrap the project's configuration for type checking: `export default defineConfig({ plugins: [...] })`. */
|
|
283
|
+
export declare function defineConfig(config: Config): Config;
|
|
284
|
+
/**
|
|
285
|
+
* Build a plugin. Pass a function to take options, as Sanity does:
|
|
286
|
+
*
|
|
287
|
+
* export const shelterMap = definePlugin<{ apiKey: string }>((options) => ({
|
|
288
|
+
* name: 'shelter-map',
|
|
289
|
+
* screens: [...],
|
|
290
|
+
* }))
|
|
291
|
+
* // pet-adopt.config.ts: plugins: [shelterMap({ apiKey: '...' })]
|
|
292
|
+
*
|
|
293
|
+
* Or pass the plugin object itself when there are no options.
|
|
294
|
+
*/
|
|
295
|
+
export declare function definePlugin<Options = void>(factory: Plugin | ((options: Options) => Plugin)): (options: Options) => Plugin;
|
|
296
|
+
/** One entry of a `choice` option's list: `value` is what is saved (an id), `label` what people see. */
|
|
297
|
+
export type PluginBlockChoice = {
|
|
298
|
+
label: string;
|
|
299
|
+
value: string | number;
|
|
300
|
+
note?: string;
|
|
301
|
+
};
|
|
302
|
+
/** One option of a block, shown in the page builder's sidebar. A missing value means the default look. */
|
|
303
|
+
export type PluginBlockField = {
|
|
304
|
+
type: 'text' | 'textarea';
|
|
305
|
+
label: string;
|
|
306
|
+
} | {
|
|
307
|
+
type: 'number';
|
|
308
|
+
label: string;
|
|
309
|
+
min?: number;
|
|
310
|
+
max?: number;
|
|
311
|
+
step?: number;
|
|
312
|
+
} | {
|
|
313
|
+
type: 'select' | 'radio';
|
|
314
|
+
label: string;
|
|
315
|
+
options: ReadonlyArray<{
|
|
316
|
+
label: string;
|
|
317
|
+
value: string | number | boolean;
|
|
318
|
+
}>;
|
|
319
|
+
} | {
|
|
320
|
+
/**
|
|
321
|
+
* A dropdown whose choices come from the database when the page builder shows it (one of the
|
|
322
|
+
* plugin's own records, such as a form). The saved value is the picked entry's `value` (text
|
|
323
|
+
* of at most 200 characters, or a number), or null for none; the site refuses anything else.
|
|
324
|
+
* The page builder lists the choices when it opens and keeps what a block loaded until one of
|
|
325
|
+
* its `dataOptions` changes, so a record edited elsewhere shows on the next reload. Choose it with care: a
|
|
326
|
+
* value that no longer exists (a deleted record) still reaches `render` and the loader, which
|
|
327
|
+
* must cope with it.
|
|
328
|
+
*/
|
|
329
|
+
type: 'choice';
|
|
330
|
+
label: string;
|
|
331
|
+
/**
|
|
332
|
+
* A server action (exported from your plugin's `'use server'` file) that lists the choices.
|
|
333
|
+
* The browser calls it, so it must check a permission itself, first:
|
|
334
|
+
* `host().requirePermission('pages:view')` lets everyone who can open the page builder see
|
|
335
|
+
* the list. Read-only: it records no activity. Return `host().run(...)`'s result. `note` is
|
|
336
|
+
* shown after the label in brackets ("closed").
|
|
337
|
+
*/
|
|
338
|
+
load: () => Promise<ActionResult<PluginBlockChoice[]>>;
|
|
339
|
+
/** The first entry's text when nothing is picked ("Choose a form"). */
|
|
340
|
+
empty?: string;
|
|
341
|
+
};
|
|
342
|
+
/** What a block's `render` receives besides its own options. */
|
|
343
|
+
export type PluginBlockContext<Data = unknown> = {
|
|
344
|
+
/**
|
|
345
|
+
* What the block's loader returned; null when there is no loader, it returned nothing, it failed,
|
|
346
|
+
* its result was larger than 1 MB, or it was not a JSON object or array.
|
|
347
|
+
*/
|
|
348
|
+
data: Data | null;
|
|
349
|
+
/** True inside the page builder, where a block with nothing to show should say why instead of vanishing. */
|
|
350
|
+
editing: boolean;
|
|
351
|
+
/** The tag for the block's main heading (`heading` option), worked out per page. Unset in the editor. */
|
|
352
|
+
headingLevel?: 1 | 2;
|
|
353
|
+
};
|
|
354
|
+
export type PluginBlock<Props extends Record<string, unknown> = Record<string, unknown>, Data = unknown> = {
|
|
355
|
+
/**
|
|
356
|
+
* The block's type in saved pages: letters and digits, starting with a capital (`AcmeGallery`).
|
|
357
|
+
* It must be unique on the site (built-in blocks and other plugins' included, so start it with
|
|
358
|
+
* something of your own) and never change, or saved pages lose the block.
|
|
359
|
+
*/
|
|
360
|
+
name: string;
|
|
361
|
+
/** The name shown in the page builder's list of blocks. */
|
|
362
|
+
label: string;
|
|
363
|
+
/** The plugin it belongs to (`Plugin.name`), which holds its loader. */
|
|
364
|
+
plugin: string;
|
|
365
|
+
/**
|
|
366
|
+
* Its options. A text option named `heading` is drawn as the block's main heading by convention.
|
|
367
|
+
* Reserved names: `id`, `puck`, `editMode`, `padding`, `spacing`, `headingLevel`, `data`,
|
|
368
|
+
* `editing`, `pluginData`.
|
|
369
|
+
*/
|
|
370
|
+
fields: {
|
|
371
|
+
[Key in keyof Props]?: PluginBlockField;
|
|
372
|
+
};
|
|
373
|
+
defaultProps: Props;
|
|
374
|
+
/**
|
|
375
|
+
* Set when the block draws nothing on the site without data from its loader. Its `heading` is
|
|
376
|
+
* then not counted as a heading of the page while there is no data, so a page whose only
|
|
377
|
+
* heading would be in an empty block still gets a main heading.
|
|
378
|
+
*/
|
|
379
|
+
needsData?: boolean;
|
|
380
|
+
/**
|
|
381
|
+
* Set when the block draws a heading whenever it has data, even with a blank `heading` option
|
|
382
|
+
* (the Form block falls back to the form's name). The page then counts it as a heading while
|
|
383
|
+
* there is data, so the first such block can be the page's main heading. Draw that heading with
|
|
384
|
+
* the tag `headingLevel` asks for.
|
|
385
|
+
*/
|
|
386
|
+
headingFromData?: boolean;
|
|
387
|
+
/**
|
|
388
|
+
* Set to offer the block in the Pet page template too (the layout of every pet's page), under
|
|
389
|
+
* "Plugins". Without it the block is only offered on ordinary pages. Only blocks that make sense
|
|
390
|
+
* on every pet's page should set it: the loader is not told which pet is shown.
|
|
391
|
+
*/
|
|
392
|
+
petPage?: boolean;
|
|
393
|
+
/**
|
|
394
|
+
* The options the loader reads. When given, the page builder runs the loader again only when one
|
|
395
|
+
* of them changes (and when the block is first shown), and redraws the block with what it has
|
|
396
|
+
* for any other change. Without it the loader runs after every change to the block, each
|
|
397
|
+
* keystroke in a text option included. The public site always runs the loader.
|
|
398
|
+
*/
|
|
399
|
+
dataOptions?: ReadonlyArray<keyof Props & string>;
|
|
400
|
+
/**
|
|
401
|
+
* Plain CSS for the block, added to the page as written with each instance of the block that
|
|
402
|
+
* draws something. It is not scoped: start every selector with a class of your own.
|
|
403
|
+
*/
|
|
404
|
+
css?: string;
|
|
405
|
+
render: (props: Props & PluginBlockContext<Data>) => React.ReactElement | null;
|
|
406
|
+
};
|
|
407
|
+
/**
|
|
408
|
+
* Loads what a block shows. `props` are the block's saved options, already checked against its
|
|
409
|
+
* `fields` (the right kinds, numbers inside min/max, select and radio values that are offered,
|
|
410
|
+
* `choice` values plain ids; anything else is replaced by its default). A `choice` may still name a
|
|
411
|
+
* record that no longer exists, so look it up and return null when it is gone. Return a plain JSON
|
|
412
|
+
* object or array, at most 1 MB (it crosses to the browser in the editor), or null for nothing:
|
|
413
|
+
* any other value, or a larger result, reaches `render` as `data: null`. A loader that throws is
|
|
414
|
+
* logged and also gives null.
|
|
415
|
+
*
|
|
416
|
+
* A later version of the SDK may call it with a second argument (what the site knows about the
|
|
417
|
+
* page being drawn). Declare one parameter, or ignore the rest: do not pass a function that
|
|
418
|
+
* gives a second parameter another meaning.
|
|
419
|
+
*/
|
|
420
|
+
export type PluginBlockLoader = (props: Record<string, unknown>) => Promise<unknown>;
|
|
421
|
+
/** Wrap a block for type checking. Keep it in a module the browser can load (see the notes above). */
|
|
422
|
+
export declare function definePluginBlock<Props extends Record<string, unknown>, Data = unknown>(block: PluginBlock<Props, Data>): PluginBlock<Props, Data>;
|
|
423
|
+
/** Any block, as a site's list of blocks holds them. */
|
|
424
|
+
export type AnyPluginBlock = PluginBlock<any, any>;
|
|
425
|
+
/** Wrap a site's list of plugin blocks (`apps/web/pet-adopt.blocks.ts`) for type checking. */
|
|
426
|
+
export declare function defineBlocks(blocks: AnyPluginBlock[]): AnyPluginBlock[];
|
|
427
|
+
export type FieldErrors = Record<string, string>;
|
|
428
|
+
export type ActionResult<T = void> = {
|
|
429
|
+
ok: true;
|
|
430
|
+
data: T;
|
|
431
|
+
} | {
|
|
432
|
+
ok: false;
|
|
433
|
+
error: string;
|
|
434
|
+
fieldErrors?: FieldErrors;
|
|
435
|
+
};
|
|
436
|
+
/** One or more fields are invalid. Safe to show to the user. */
|
|
437
|
+
export declare class ValidationError extends Error {
|
|
438
|
+
fieldErrors: FieldErrors;
|
|
439
|
+
constructor(fieldErrors: FieldErrors, message?: string);
|
|
440
|
+
}
|
|
441
|
+
/** A rule was broken (not found, still in use, not allowed). The message is safe to show. */
|
|
442
|
+
export declare class UserError extends Error {
|
|
443
|
+
constructor(message: string);
|
|
444
|
+
}
|
|
445
|
+
export type RateRule = {
|
|
446
|
+
max: number;
|
|
447
|
+
windowMs: number;
|
|
448
|
+
};
|
|
449
|
+
/** Lists of site data a plugin can offer as choices (a form's "Which pet?" question). */
|
|
450
|
+
export declare const CHOICE_SOURCES: readonly ["pets"];
|
|
451
|
+
export type ChoiceSource = (typeof CHOICE_SOURCES)[number];
|
|
452
|
+
/** One choice: `value` is stable (an id), `label` is what people see. */
|
|
453
|
+
export type Choice = {
|
|
454
|
+
value: string;
|
|
455
|
+
label: string;
|
|
456
|
+
};
|
|
457
|
+
/**
|
|
458
|
+
* What the app does for plugins, so a plugin never imports the app. Server-only; get it with
|
|
459
|
+
* `host()` inside a server action or server component (not at module load).
|
|
460
|
+
*/
|
|
461
|
+
export type PluginHost = {
|
|
462
|
+
/**
|
|
463
|
+
* The signed-in person, if they have `permission`; throws a UserError otherwise. Check the level
|
|
464
|
+
* of the screen the action belongs to: `requirePermission(accessPermission('all', 'edit'))` to
|
|
465
|
+
* change, `'view'` to read.
|
|
466
|
+
*/
|
|
467
|
+
requirePermission(permission: Permission): Promise<PluginUser>;
|
|
468
|
+
/**
|
|
469
|
+
* Someone who can change the team's plugin content (`pluginContent:edit`: not audit). Use
|
|
470
|
+
* requirePermission with a `view` permission for reads, so audit can see them.
|
|
471
|
+
*/
|
|
472
|
+
requireUser(): Promise<PluginUser>;
|
|
473
|
+
/** Someone who can change admin-level plugin settings (`plugins:edit`: admins and developers). */
|
|
474
|
+
requireAdmin(): Promise<PluginUser>;
|
|
475
|
+
/** Runs `fn` and turns what it throws into an ActionResult (wrap every server action in it). */
|
|
476
|
+
run<T>(fn: () => Promise<T>): Promise<ActionResult<T>>;
|
|
477
|
+
/** The visitor's address as the site's proxy reports it, or null when it cannot tell. */
|
|
478
|
+
clientAddress(): Promise<string | null>;
|
|
479
|
+
/**
|
|
480
|
+
* Counts one attempt on `key` and throws a UserError ("Too many attempts...") on the attempt after
|
|
481
|
+
* the `rule.max`th. It is not a fixed window from the first attempt: the count starts again only
|
|
482
|
+
* once `rule.windowMs` passes with no attempt below the limit (each attempt under the limit moves
|
|
483
|
+
* the window to start from it). Once over the limit, the key stays refused until `rule.windowMs`
|
|
484
|
+
* after the attempt that reached it, however often it is tried meanwhile. So `{ max: 3, windowMs:
|
|
485
|
+
* one hour }` refuses a 4th attempt made within an hour of the 3rd. Keys are stored as
|
|
486
|
+
* `plugin:<key>`; start yours with the plugin name.
|
|
487
|
+
*/
|
|
488
|
+
consumeAttempt(key: string, rule: RateRule): Promise<void>;
|
|
489
|
+
phone: {
|
|
490
|
+
/** True, or why the number cannot be used. Numbers without "+code" use the site's country. */
|
|
491
|
+
validate(raw: string): true | string;
|
|
492
|
+
/** The number as E.164 ("+60123456789"), or null when it is not valid. */
|
|
493
|
+
toE164(raw: string): string | null;
|
|
494
|
+
};
|
|
495
|
+
/**
|
|
496
|
+
* The current choices from a list of site data, as visitors may see them. `pets`: listed pets that
|
|
497
|
+
* are not adopted, by name (pending ones say so); `value` is the pet's id.
|
|
498
|
+
*/
|
|
499
|
+
choices(source: ChoiceSource): Promise<Choice[]>;
|
|
500
|
+
/** The site's email sender (a ready email plugin, else the built-in SMTP sender), or null while neither is set up. */
|
|
501
|
+
emailSender(): Promise<EmailSender | null>;
|
|
502
|
+
/** Logs an error without the values a failed database query carries. Never log error objects yourself. */
|
|
503
|
+
logError(error: unknown, context?: string): void;
|
|
504
|
+
/**
|
|
505
|
+
* Sends an email through the site's templates (Email > Templates): a team notification
|
|
506
|
+
* or a message to a visitor. Uses the template `templateId` when it exists and has that purpose,
|
|
507
|
+
* else the built-in one. `details` are only used for team notifications (a message to a visitor
|
|
508
|
+
* never repeats what someone typed). Resolves false when the site cannot send email; rejects when
|
|
509
|
+
* sending fails.
|
|
510
|
+
*/
|
|
511
|
+
sendTemplatedEmail(message: PluginEmail): Promise<boolean>;
|
|
512
|
+
/**
|
|
513
|
+
* The templates for a purpose, for a "which template" choice. `seedKey` marks plugin defaults
|
|
514
|
+
* (`<plugin>:<key>`); pre-select yours when nothing is chosen.
|
|
515
|
+
*/
|
|
516
|
+
emailTemplates(purpose: PluginEmailPurpose): Promise<Array<{
|
|
517
|
+
id: number;
|
|
518
|
+
name: string;
|
|
519
|
+
seedKey: string | null;
|
|
520
|
+
}>>;
|
|
521
|
+
/**
|
|
522
|
+
* Adds an entry to the site's activity log, as the signed-in person, after a change succeeded.
|
|
523
|
+
* Never throws (a failure is logged). See PluginActivity.
|
|
524
|
+
*/
|
|
525
|
+
recordActivity(entry: PluginActivity): Promise<void>;
|
|
526
|
+
/**
|
|
527
|
+
* The site's privacy policy while it is live (`href` is a site path), or null when none is chosen
|
|
528
|
+
* or its page is not published. A plugin that collects personal data should warn while it is null
|
|
529
|
+
* and link to it where visitors type. `settingsHref` is where an admin chooses it.
|
|
530
|
+
*/
|
|
531
|
+
privacyPolicy(): Promise<{
|
|
532
|
+
policy: {
|
|
533
|
+
title: string;
|
|
534
|
+
href: string;
|
|
535
|
+
} | null;
|
|
536
|
+
settingsHref: string;
|
|
537
|
+
}>;
|
|
538
|
+
/**
|
|
539
|
+
* The time zone chosen in Site settings, or null when none is. Pass it to `formatWhen` wherever a
|
|
540
|
+
* screen shows a time, so every screen agrees.
|
|
541
|
+
*/
|
|
542
|
+
timeZone(): Promise<string | null>;
|
|
543
|
+
/** The site's public address, without a trailing slash (`https://adopt.example.com`). */
|
|
544
|
+
siteUrl(): string;
|
|
545
|
+
/**
|
|
546
|
+
* Asks the site to redraw its public pages, after a change that affects what visitors see (what
|
|
547
|
+
* a block's loader returns, for one). Without it a page may show the old state for up to a
|
|
548
|
+
* minute. Safe to call anywhere and never throws; outside a request it does nothing.
|
|
549
|
+
*/
|
|
550
|
+
revalidateSite(): void;
|
|
551
|
+
/**
|
|
552
|
+
* Encrypts a secret (an API key) for storage, with a key derived from the site's secret, the same
|
|
553
|
+
* way the SMTP password is kept. `purpose` names what it is (`form-builder:captcha`): a value only
|
|
554
|
+
* opens with the purpose it was sealed for. `open` returns null when it cannot be opened (another
|
|
555
|
+
* purpose or site secret, or a changed byte): ask for the secret again then. Never send a secret
|
|
556
|
+
* to a browser.
|
|
557
|
+
*/
|
|
558
|
+
secrets: {
|
|
559
|
+
seal(plain: string, purpose: string): string;
|
|
560
|
+
open(sealed: string | null, purpose: string): string | null;
|
|
561
|
+
};
|
|
562
|
+
};
|
|
563
|
+
/** Kinds of email a plugin may send through the site's templates (see `sendTemplatedEmail`). */
|
|
564
|
+
export type PluginEmailPurpose = 'team-notification' | 'visitor-message';
|
|
565
|
+
export type PluginEmail = {
|
|
566
|
+
purpose: PluginEmailPurpose;
|
|
567
|
+
templateId?: number | null;
|
|
568
|
+
/** Your default template (`<plugin name>:<key>` from `emailTemplates`), used when `templateId` is missing or deleted. */
|
|
569
|
+
fallback?: string;
|
|
570
|
+
to: string;
|
|
571
|
+
/** Placeholders: `{ title }` (what it is about, such as a form's name). The site's name and address are added. */
|
|
572
|
+
values?: Record<string, string>;
|
|
573
|
+
/** Label and value pairs for the Details block (team notifications only), such as a form's answers. */
|
|
574
|
+
details?: Array<{
|
|
575
|
+
label: string;
|
|
576
|
+
value: string;
|
|
577
|
+
}>;
|
|
578
|
+
};
|
|
579
|
+
/**
|
|
580
|
+
* One line of the activity log, written by a plugin. Record changes (and downloads of personal
|
|
581
|
+
* data), not reads. Never put personal data in it: name the fields that changed, not their values.
|
|
582
|
+
*/
|
|
583
|
+
export type PluginActivity = {
|
|
584
|
+
/** `<plugin name>.<thing>.<verb>`, such as `form-builder.form.update`. Used to filter. */
|
|
585
|
+
action: string;
|
|
586
|
+
/** One sentence, past tense, for people: `Updated the form "Adopt a cat"`. */
|
|
587
|
+
summary: string;
|
|
588
|
+
/** What it was done to: an id, and its name as it is now (kept even if it is deleted later). */
|
|
589
|
+
subject?: {
|
|
590
|
+
id: string | number;
|
|
591
|
+
label?: string | null;
|
|
592
|
+
};
|
|
593
|
+
/** Field names (or labels) that changed. */
|
|
594
|
+
fields?: string[];
|
|
595
|
+
};
|
|
596
|
+
/** One CSV cell. Cells a spreadsheet would run as a formula get an apostrophe in front. */
|
|
597
|
+
export declare function csvCell(value: string): string;
|
|
598
|
+
/** The app's services for plugins. Throws outside the app (a plugin's own tests should stub it). */
|
|
599
|
+
export declare function host(): PluginHost;
|
|
600
|
+
/** For the app only. Plugins never call this. */
|
|
601
|
+
export declare function provideHost(services: PluginHost): void;
|
|
602
|
+
/**
|
|
603
|
+
* The time zone a site shows its times in (Site settings), as an IANA name such as
|
|
604
|
+
* "Asia/Kuala_Lumpur"; null means none was chosen and each person sees their own device's time.
|
|
605
|
+
*/
|
|
606
|
+
export type SiteTimeZone = string | null | undefined;
|
|
607
|
+
/** Whether a string is a time zone this runtime knows ("Asia/Kuala_Lumpur", "UTC"). */
|
|
608
|
+
export declare function isTimeZone(value: string): boolean;
|
|
609
|
+
export type WhenStyle = 'date' | 'dateTime' | 'longDate';
|
|
610
|
+
/**
|
|
611
|
+
* A date as the admin shows it: "27 Nov 2026, 18:46" (`dateTime`, the default), "27 Nov 2026"
|
|
612
|
+
* (`date`) or "27 November 2026" (`longDate`), in the site's time zone. Without one (or with a name
|
|
613
|
+
* this runtime does not know) the runtime's own zone is used: the viewer's in a browser, the
|
|
614
|
+
* server's on the server. One fixed locale, so the server and the browser draw the same text.
|
|
615
|
+
*/
|
|
616
|
+
export declare function formatWhen(value: Date | string | number, timeZone?: SiteTimeZone, style?: WhenStyle): string;
|
|
617
|
+
/** The day (`YYYY-MM-DD`) an instant falls on in the site's time zone (the runtime's without one). */
|
|
618
|
+
export declare function dayInZone(value: Date | string | number, timeZone?: SiteTimeZone): string;
|
|
619
|
+
/**
|
|
620
|
+
* The instant a day (`YYYY-MM-DD`) starts at in the site's time zone (the runtime's without one),
|
|
621
|
+
* or with `addDays` that many days later. Null for anything that is not a real date.
|
|
622
|
+
*/
|
|
623
|
+
export declare function startOfDayInZone(day: string, timeZone?: SiteTimeZone, addDays?: number): Date | null;
|
|
624
|
+
/**
|
|
625
|
+
* Text as searches compare it: Unicode-normalised, accents removed and lower-cased ("Île" -> "ile",
|
|
626
|
+
* "Café" -> "cafe"). Done in JavaScript, not with SQL lower(), because SQLite and libSQL (Turso)
|
|
627
|
+
* only fold A-Z there; searchable text is stored folded and the search term is folded the same way,
|
|
628
|
+
* so every database gives the same results.
|
|
629
|
+
*/
|
|
630
|
+
export declare function foldText(value: string | null | undefined): string;
|
|
631
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// @pet-adopt/plugin-sdk: the public surface for `pet-adopt.config.ts` and for plugin authors.
|
|
2
|
+
// Nothing here touches the database or the browser, and nothing imports the app, so a plugin
|
|
3
|
+
// package (in plugins/ here, or published to npm) depends on this package alone.
|
|
4
|
+
// --- Roles and permissions ---------------------------------------------------------------------
|
|
5
|
+
// One source of truth for what each role may do, shared by the app and plugins. Every server
|
|
6
|
+
// action checks a permission (`can`), and the admin's menus and buttons follow the same table.
|
|
7
|
+
/** Who can sign in to the admin. */
|
|
8
|
+
export const ROLES = ['admin', 'editor', 'developer', 'audit'];
|
|
9
|
+
export const ROLE_INFO = {
|
|
10
|
+
admin: { label: 'Admin', description: 'Everything, including users.' },
|
|
11
|
+
editor: { label: 'Editor', description: 'Pets, pages, media, forms and form responses.' },
|
|
12
|
+
developer: { label: 'Developer', description: 'Pets, pages, media, forms, theme, settings and plugins. No form responses or users.' },
|
|
13
|
+
audit: { label: 'Audit', description: 'Sees everything, changes nothing. Cannot download form responses.' },
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* What a permission covers. `pluginContent`, `plugins` and `personalData` are the three levels a
|
|
17
|
+
* plugin screen can ask for (see PluginAccess); the rest are the site's own areas.
|
|
18
|
+
*/
|
|
19
|
+
export const AREAS = ['pets', 'pages', 'media', 'theme', 'settings', 'plugins', 'users', 'pluginContent', 'personalData'];
|
|
20
|
+
const edit = (...areas) => areas.flatMap((area) => [`${area}:view`, `${area}:edit`]);
|
|
21
|
+
const view = (...areas) => areas.map((area) => `${area}:view`);
|
|
22
|
+
const GRANTS = {
|
|
23
|
+
admin: new Set([...edit(...AREAS), 'personalData:export', 'activity:own', 'activity:view', 'activity:export']),
|
|
24
|
+
editor: new Set([...edit('pets', 'pages', 'media', 'pluginContent', 'personalData'), 'personalData:export', 'activity:own']),
|
|
25
|
+
developer: new Set([...edit('pets', 'pages', 'media', 'pluginContent', 'theme', 'settings', 'plugins'), 'activity:own']),
|
|
26
|
+
audit: new Set([...view(...AREAS), 'activity:own', 'activity:view', 'activity:export']),
|
|
27
|
+
};
|
|
28
|
+
/** Whether `role` has `permission`. An unknown role has none. */
|
|
29
|
+
export function can(role, permission) {
|
|
30
|
+
return Boolean(role && GRANTS[role]?.has(permission));
|
|
31
|
+
}
|
|
32
|
+
/** A stored role string as a Role. Anything unknown becomes `audit`, which changes nothing. */
|
|
33
|
+
export function asRole(value) {
|
|
34
|
+
return ROLES.includes(value) ? value : 'audit';
|
|
35
|
+
}
|
|
36
|
+
const ACCESS_AREA = { all: 'pluginContent', admin: 'plugins', personalData: 'personalData' };
|
|
37
|
+
/** The permission a plugin screen or action needs: `accessPermission('personalData', 'edit')`. */
|
|
38
|
+
export function accessPermission(access, level) {
|
|
39
|
+
return `${ACCESS_AREA[access]}:${level}`;
|
|
40
|
+
}
|
|
41
|
+
/** A screen's or widget's access, reading the older `adminOnly` flag too. */
|
|
42
|
+
export function accessOf(item) {
|
|
43
|
+
return item.access ?? (item.adminOnly ? 'admin' : 'all');
|
|
44
|
+
}
|
|
45
|
+
/** "form-builder" -> "plugin_form_builder_": what every table and index of that plugin starts with. */
|
|
46
|
+
export const pluginTablePrefix = (pluginName) => `plugin_${pluginName.replace(/-/g, '_')}_`;
|
|
47
|
+
// On globalThis, so the app and every plugin find the same provider even when the SDK is bundled
|
|
48
|
+
// more than once (instrumentation, routes and server actions are separate bundles in one process).
|
|
49
|
+
const PROVIDER = Symbol.for('pet-adopt.plugin-storage-provider');
|
|
50
|
+
const slot = globalThis;
|
|
51
|
+
/**
|
|
52
|
+
* A plugin's tables and migrations, plus a way to open them. The app does the opening: a plugin
|
|
53
|
+
* never imports the app's database, only this package and drizzle-orm (for its table definitions).
|
|
54
|
+
*
|
|
55
|
+
* export const storage = definePluginStorage({ tables: { sqlite, pg }, migrations })
|
|
56
|
+
* definePlugin({ name: 'my-plugin', storage, ... })
|
|
57
|
+
* const { db, t } = await storage.open()
|
|
58
|
+
*/
|
|
59
|
+
export function definePluginStorage(storage) {
|
|
60
|
+
const handle = {
|
|
61
|
+
...storage,
|
|
62
|
+
async open() {
|
|
63
|
+
const provider = slot[PROVIDER];
|
|
64
|
+
if (!provider)
|
|
65
|
+
throw new Error('Plugin storage can only be opened inside the Pet Adopt app (no storage provider is registered).');
|
|
66
|
+
return (await provider(handle));
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
return handle;
|
|
70
|
+
}
|
|
71
|
+
/** For the app only: how plugin storage is opened. Plugins never call this. */
|
|
72
|
+
export function provideStorage(provider) {
|
|
73
|
+
slot[PROVIDER] = provider;
|
|
74
|
+
}
|
|
75
|
+
/** Wrap the project's configuration for type checking: `export default defineConfig({ plugins: [...] })`. */
|
|
76
|
+
export function defineConfig(config) {
|
|
77
|
+
return config;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Build a plugin. Pass a function to take options, as Sanity does:
|
|
81
|
+
*
|
|
82
|
+
* export const shelterMap = definePlugin<{ apiKey: string }>((options) => ({
|
|
83
|
+
* name: 'shelter-map',
|
|
84
|
+
* screens: [...],
|
|
85
|
+
* }))
|
|
86
|
+
* // pet-adopt.config.ts: plugins: [shelterMap({ apiKey: '...' })]
|
|
87
|
+
*
|
|
88
|
+
* Or pass the plugin object itself when there are no options.
|
|
89
|
+
*/
|
|
90
|
+
export function definePlugin(factory) {
|
|
91
|
+
return (options) => (typeof factory === 'function' ? factory(options) : factory);
|
|
92
|
+
}
|
|
93
|
+
/** Wrap a block for type checking. Keep it in a module the browser can load (see the notes above). */
|
|
94
|
+
export function definePluginBlock(block) {
|
|
95
|
+
return block;
|
|
96
|
+
}
|
|
97
|
+
/** Wrap a site's list of plugin blocks (`apps/web/pet-adopt.blocks.ts`) for type checking. */
|
|
98
|
+
export function defineBlocks(blocks) {
|
|
99
|
+
return blocks;
|
|
100
|
+
}
|
|
101
|
+
/** One or more fields are invalid. Safe to show to the user. */
|
|
102
|
+
export class ValidationError extends Error {
|
|
103
|
+
fieldErrors;
|
|
104
|
+
constructor(fieldErrors, message = 'Please fix the highlighted fields.') {
|
|
105
|
+
super(message);
|
|
106
|
+
this.fieldErrors = fieldErrors;
|
|
107
|
+
this.name = 'ValidationError';
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** A rule was broken (not found, still in use, not allowed). The message is safe to show. */
|
|
111
|
+
export class UserError extends Error {
|
|
112
|
+
constructor(message) {
|
|
113
|
+
super(message);
|
|
114
|
+
this.name = 'UserError';
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** Lists of site data a plugin can offer as choices (a form's "Which pet?" question). */
|
|
118
|
+
export const CHOICE_SOURCES = ['pets'];
|
|
119
|
+
/** One CSV cell. Cells a spreadsheet would run as a formula get an apostrophe in front. */
|
|
120
|
+
export function csvCell(value) {
|
|
121
|
+
const safe = /^[=+\-@\t\r]/.test(value) ? `'${value}` : value;
|
|
122
|
+
return /[",\r\n]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;
|
|
123
|
+
}
|
|
124
|
+
const HOST = Symbol.for('pet-adopt.plugin-host');
|
|
125
|
+
const hostSlot = globalThis;
|
|
126
|
+
/** The app's services for plugins. Throws outside the app (a plugin's own tests should stub it). */
|
|
127
|
+
export function host() {
|
|
128
|
+
const current = hostSlot[HOST];
|
|
129
|
+
if (!current)
|
|
130
|
+
throw new Error('Plugin host services are only available inside the Pet Adopt app.');
|
|
131
|
+
return current;
|
|
132
|
+
}
|
|
133
|
+
/** For the app only. Plugins never call this. */
|
|
134
|
+
export function provideHost(services) {
|
|
135
|
+
hostSlot[HOST] = services;
|
|
136
|
+
}
|
|
137
|
+
/** Whether a string is a time zone this runtime knows ("Asia/Kuala_Lumpur", "UTC"). */
|
|
138
|
+
export function isTimeZone(value) {
|
|
139
|
+
if (!/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/.test(value))
|
|
140
|
+
return false;
|
|
141
|
+
try {
|
|
142
|
+
new Intl.DateTimeFormat('en-GB', { timeZone: value });
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const usable = (timeZone) => (timeZone && isTimeZone(timeZone) ? timeZone : undefined);
|
|
150
|
+
const whenFormats = new Map();
|
|
151
|
+
/**
|
|
152
|
+
* A date as the admin shows it: "27 Nov 2026, 18:46" (`dateTime`, the default), "27 Nov 2026"
|
|
153
|
+
* (`date`) or "27 November 2026" (`longDate`), in the site's time zone. Without one (or with a name
|
|
154
|
+
* this runtime does not know) the runtime's own zone is used: the viewer's in a browser, the
|
|
155
|
+
* server's on the server. One fixed locale, so the server and the browser draw the same text.
|
|
156
|
+
*/
|
|
157
|
+
export function formatWhen(value, timeZone, style = 'dateTime') {
|
|
158
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
159
|
+
if (Number.isNaN(date.getTime()))
|
|
160
|
+
return '';
|
|
161
|
+
const zone = usable(timeZone);
|
|
162
|
+
const key = `${style}|${zone ?? ''}`;
|
|
163
|
+
let format = whenFormats.get(key);
|
|
164
|
+
if (!format) {
|
|
165
|
+
format = new Intl.DateTimeFormat('en-GB', {
|
|
166
|
+
dateStyle: style === 'longDate' ? 'long' : 'medium',
|
|
167
|
+
...(style === 'dateTime' ? { timeStyle: 'short' } : {}),
|
|
168
|
+
timeZone: zone,
|
|
169
|
+
});
|
|
170
|
+
whenFormats.set(key, format);
|
|
171
|
+
}
|
|
172
|
+
return format.format(date);
|
|
173
|
+
}
|
|
174
|
+
const partFormats = new Map();
|
|
175
|
+
/** The calendar date and clock time an instant has in a time zone. */
|
|
176
|
+
function wallClock(at, timeZone) {
|
|
177
|
+
let format = partFormats.get(timeZone);
|
|
178
|
+
if (!format) {
|
|
179
|
+
format = new Intl.DateTimeFormat('en-GB', {
|
|
180
|
+
timeZone,
|
|
181
|
+
hourCycle: 'h23',
|
|
182
|
+
year: 'numeric',
|
|
183
|
+
month: '2-digit',
|
|
184
|
+
day: '2-digit',
|
|
185
|
+
hour: '2-digit',
|
|
186
|
+
minute: '2-digit',
|
|
187
|
+
second: '2-digit',
|
|
188
|
+
});
|
|
189
|
+
partFormats.set(timeZone, format);
|
|
190
|
+
}
|
|
191
|
+
const parts = {};
|
|
192
|
+
for (const part of format.formatToParts(new Date(at)))
|
|
193
|
+
if (part.type !== 'literal')
|
|
194
|
+
parts[part.type] = Number(part.value);
|
|
195
|
+
return parts;
|
|
196
|
+
}
|
|
197
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
198
|
+
/** The day (`YYYY-MM-DD`) an instant falls on in the site's time zone (the runtime's without one). */
|
|
199
|
+
export function dayInZone(value, timeZone) {
|
|
200
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
201
|
+
if (Number.isNaN(date.getTime()))
|
|
202
|
+
return '';
|
|
203
|
+
const zone = usable(timeZone);
|
|
204
|
+
if (!zone)
|
|
205
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
206
|
+
const clock = wallClock(date.getTime(), zone);
|
|
207
|
+
return `${clock.year}-${pad(clock.month)}-${pad(clock.day)}`;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* The instant a day (`YYYY-MM-DD`) starts at in the site's time zone (the runtime's without one),
|
|
211
|
+
* or with `addDays` that many days later. Null for anything that is not a real date.
|
|
212
|
+
*/
|
|
213
|
+
export function startOfDayInZone(day, timeZone, addDays = 0) {
|
|
214
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day);
|
|
215
|
+
if (!match)
|
|
216
|
+
return null;
|
|
217
|
+
const [year, month, date] = [Number(match[1]), Number(match[2]), Number(match[3])];
|
|
218
|
+
const real = new Date(Date.UTC(year, month - 1, date));
|
|
219
|
+
if (real.getUTCFullYear() !== year || real.getUTCMonth() !== month - 1 || real.getUTCDate() !== date)
|
|
220
|
+
return null;
|
|
221
|
+
const zone = usable(timeZone);
|
|
222
|
+
if (!zone)
|
|
223
|
+
return new Date(year, month - 1, date + addDays);
|
|
224
|
+
// Midnight as if the zone were UTC, then moved by the zone's offset at that moment. The offset is
|
|
225
|
+
// read again at the result, because the first guess can sit on the other side of a clock change.
|
|
226
|
+
const wanted = Date.UTC(year, month - 1, date + addDays);
|
|
227
|
+
const offsetAt = (at) => {
|
|
228
|
+
const clock = wallClock(at, zone);
|
|
229
|
+
return Date.UTC(clock.year, clock.month - 1, clock.day, clock.hour, clock.minute, clock.second) - at;
|
|
230
|
+
};
|
|
231
|
+
const first = wanted - offsetAt(wanted);
|
|
232
|
+
return new Date(wanted - offsetAt(first));
|
|
233
|
+
}
|
|
234
|
+
// --- Search ----------------------------------------------------------------------------------
|
|
235
|
+
/**
|
|
236
|
+
* Text as searches compare it: Unicode-normalised, accents removed and lower-cased ("Île" -> "ile",
|
|
237
|
+
* "Café" -> "cafe"). Done in JavaScript, not with SQL lower(), because SQLite and libSQL (Turso)
|
|
238
|
+
* only fold A-Z there; searchable text is stored folded and the search term is folded the same way,
|
|
239
|
+
* so every database gives the same results.
|
|
240
|
+
*/
|
|
241
|
+
export function foldText(value) {
|
|
242
|
+
return (value ?? '').normalize('NFKD').replace(/\p{M}+/gu, '').toLowerCase();
|
|
243
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pet-adopt/plugin-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Types and helpers for writing Pet Adopt plugins: definePlugin, defineConfig, screens, widgets, email.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/muhammadarifftaha/pet-adopt.git",
|
|
9
|
+
"directory": "packages/plugin-sdk"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/muhammadarifftaha/pet-adopt/tree/main/packages/plugin-sdk#readme",
|
|
12
|
+
"bugs": "https://github.com/muhammadarifftaha/pet-adopt/issues",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"pet-adopt",
|
|
15
|
+
"plugin",
|
|
16
|
+
"sdk"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"default": "./dist/index.js"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist"
|
|
28
|
+
],
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"drizzle-orm": "^0.45.4",
|
|
34
|
+
"react": "^19.2.0",
|
|
35
|
+
"react-icons": "^5.7.0"
|
|
36
|
+
},
|
|
37
|
+
"peerDependenciesMeta": {
|
|
38
|
+
"drizzle-orm": {
|
|
39
|
+
"optional": true
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@libsql/client": "0.18.0",
|
|
44
|
+
"@types/react": "19.2.14",
|
|
45
|
+
"drizzle-orm": "^0.45.4",
|
|
46
|
+
"react": "19.2.6",
|
|
47
|
+
"react-icons": "^5.7.0",
|
|
48
|
+
"typescript": "5.7.3"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"typecheck": "tsc --noEmit",
|
|
52
|
+
"build:package": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json"
|
|
53
|
+
}
|
|
6
54
|
}
|