@weft-framework/server 0.0.0-stage → 0.0.3
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 +4 -2
- package/dist/account.d.ts +124 -0
- package/dist/account.js +344 -0
- package/dist/action.d.ts +43 -0
- package/dist/action.js +135 -0
- package/dist/admin.d.ts +99 -0
- package/dist/admin.js +431 -0
- package/dist/api.d.ts +21 -0
- package/dist/api.js +72 -0
- package/dist/app.d.ts +202 -0
- package/dist/app.js +3692 -0
- package/dist/assets.d.ts +4 -0
- package/dist/assets.js +91 -0
- package/dist/auth.d.ts +150 -0
- package/dist/auth.js +215 -0
- package/dist/backup.d.ts +46 -0
- package/dist/backup.js +345 -0
- package/dist/build.d.ts +33 -0
- package/dist/build.js +274 -0
- package/dist/bun.d.ts +30 -0
- package/dist/bun.js +53 -0
- package/dist/calendar.d.ts +161 -0
- package/dist/calendar.js +690 -0
- package/dist/compiler.d.ts +13 -0
- package/dist/compiler.js +58 -0
- package/dist/compress.d.ts +6 -0
- package/dist/compress.js +78 -0
- package/dist/config.d.ts +26 -0
- package/dist/config.js +317 -0
- package/dist/context.d.ts +9 -0
- package/dist/context.js +1 -0
- package/dist/contract.d.ts +18 -0
- package/dist/contract.js +171 -0
- package/dist/datamap.d.ts +24 -0
- package/dist/datamap.js +365 -0
- package/dist/db-backup.d.ts +27 -0
- package/dist/db-backup.js +115 -0
- package/dist/dev-events.d.ts +14 -0
- package/dist/dev-events.js +135 -0
- package/dist/dev.d.ts +1 -0
- package/dist/dev.js +240 -0
- package/dist/devtools-client.d.ts +1 -0
- package/dist/devtools-client.js +362 -0
- package/dist/devtools.d.ts +87 -0
- package/dist/devtools.js +68 -0
- package/dist/edge.d.ts +3 -0
- package/dist/edge.js +7 -0
- package/dist/email-signin.d.ts +92 -0
- package/dist/email-signin.js +259 -0
- package/dist/env.d.ts +1 -0
- package/dist/env.js +15 -0
- package/dist/explain.d.ts +12 -0
- package/dist/explain.js +217 -0
- package/dist/files.d.ts +6 -0
- package/dist/files.js +170 -0
- package/dist/grants.d.ts +69 -0
- package/dist/grants.js +206 -0
- package/dist/image/bitmap.d.ts +11 -0
- package/dist/image/bitmap.js +172 -0
- package/dist/image/jpeg.d.ts +10 -0
- package/dist/image/jpeg.js +697 -0
- package/dist/image/png.d.ts +8 -0
- package/dist/image/png.js +282 -0
- package/dist/image/transform.d.ts +20 -0
- package/dist/image/transform.js +52 -0
- package/dist/image/worker.d.ts +1 -0
- package/dist/image/worker.js +11 -0
- package/dist/images.d.ts +39 -0
- package/dist/images.js +283 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +31 -0
- package/dist/inspect-hub.d.ts +42 -0
- package/dist/inspect-hub.js +14 -0
- package/dist/inspector.d.ts +51 -0
- package/dist/inspector.js +193 -0
- package/dist/job-admin.d.ts +55 -0
- package/dist/job-admin.js +89 -0
- package/dist/jobs.d.ts +222 -0
- package/dist/jobs.js +789 -0
- package/dist/live.d.ts +72 -0
- package/dist/live.js +481 -0
- package/dist/load-config.d.ts +2 -0
- package/dist/load-config.js +41 -0
- package/dist/log.d.ts +20 -0
- package/dist/log.js +143 -0
- package/dist/mail.d.ts +189 -0
- package/dist/mail.js +999 -0
- package/dist/media.d.ts +129 -0
- package/dist/media.js +470 -0
- package/dist/meta.d.ts +54 -0
- package/dist/meta.js +146 -0
- package/dist/middleware.d.ts +20 -0
- package/dist/middleware.js +101 -0
- package/dist/migrate.d.ts +12 -0
- package/dist/migrate.js +88 -0
- package/dist/node.d.ts +26 -0
- package/dist/node.js +96 -0
- package/dist/notice.d.ts +21 -0
- package/dist/notice.js +48 -0
- package/dist/npm.d.ts +16 -0
- package/dist/npm.js +347 -0
- package/dist/oauth.d.ts +76 -0
- package/dist/oauth.js +408 -0
- package/dist/otel.d.ts +57 -0
- package/dist/otel.js +293 -0
- package/dist/passkey.d.ts +99 -0
- package/dist/passkey.js +572 -0
- package/dist/password.d.ts +8 -0
- package/dist/password.js +65 -0
- package/dist/pdf.d.ts +46 -0
- package/dist/pdf.js +332 -0
- package/dist/personal-data.d.ts +22 -0
- package/dist/personal-data.js +148 -0
- package/dist/pointers.d.ts +9 -0
- package/dist/pointers.js +148 -0
- package/dist/postcss.d.ts +3 -0
- package/dist/postcss.js +89 -0
- package/dist/presence.d.ts +27 -0
- package/dist/presence.js +161 -0
- package/dist/preview.d.ts +25 -0
- package/dist/preview.js +353 -0
- package/dist/production.d.ts +16 -0
- package/dist/production.js +119 -0
- package/dist/project.d.ts +23 -0
- package/dist/project.js +536 -0
- package/dist/regions.d.ts +47 -0
- package/dist/regions.js +511 -0
- package/dist/replay.d.ts +44 -0
- package/dist/replay.js +259 -0
- package/dist/router.d.ts +29 -0
- package/dist/router.js +146 -0
- package/dist/rules-diff.d.ts +18 -0
- package/dist/rules-diff.js +165 -0
- package/dist/rules-test.d.ts +17 -0
- package/dist/rules-test.js +108 -0
- package/dist/saml.d.ts +160 -0
- package/dist/saml.js +959 -0
- package/dist/seal.d.ts +35 -0
- package/dist/seal.js +107 -0
- package/dist/secret.d.ts +14 -0
- package/dist/secret.js +110 -0
- package/dist/security.d.ts +53 -0
- package/dist/security.js +250 -0
- package/dist/seed.d.ts +16 -0
- package/dist/seed.js +94 -0
- package/dist/seo.d.ts +42 -0
- package/dist/seo.js +175 -0
- package/dist/settings.d.ts +79 -0
- package/dist/settings.js +212 -0
- package/dist/shared.d.ts +15 -0
- package/dist/shared.js +283 -0
- package/dist/shell.d.ts +12 -0
- package/dist/shell.js +118 -0
- package/dist/storage.d.ts +13 -0
- package/dist/storage.js +55 -0
- package/dist/support.d.ts +83 -0
- package/dist/support.js +236 -0
- package/dist/sync.d.ts +35 -0
- package/dist/sync.js +167 -0
- package/dist/tailwind.d.ts +14 -0
- package/dist/tailwind.js +117 -0
- package/dist/two-factor.d.ts +103 -0
- package/dist/two-factor.js +435 -0
- package/dist/uploads.d.ts +185 -0
- package/dist/uploads.js +991 -0
- package/dist/webhooks.d.ts +169 -0
- package/dist/webhooks.js +758 -0
- package/dist/webpush.d.ts +97 -0
- package/dist/webpush.js +372 -0
- package/dist/wizard.d.ts +141 -0
- package/dist/wizard.js +410 -0
- package/dist/workflows.d.ts +134 -0
- package/dist/workflows.js +511 -0
- package/package.json +186 -4
package/dist/seo.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Params } from "./router.js";
|
|
2
|
+
type Maybe<T> = T | Promise<T>;
|
|
3
|
+
export type ChangeFrequency = "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
|
|
4
|
+
export interface SitemapEntry {
|
|
5
|
+
url: string;
|
|
6
|
+
lastModified?: Date | number;
|
|
7
|
+
changeFrequency?: ChangeFrequency;
|
|
8
|
+
priority?: number;
|
|
9
|
+
}
|
|
10
|
+
export interface RouteEntry extends Omit<SitemapEntry, "url"> {
|
|
11
|
+
params: Params;
|
|
12
|
+
}
|
|
13
|
+
export interface SitemapOptions {
|
|
14
|
+
exclude?: readonly (string | RegExp)[];
|
|
15
|
+
params?: Record<string, () => Maybe<Iterable<RouteEntry>>>;
|
|
16
|
+
extra?: () => Maybe<Iterable<Omit<SitemapEntry, "url"> & {
|
|
17
|
+
url: string;
|
|
18
|
+
}>>;
|
|
19
|
+
changeFrequency?: ChangeFrequency;
|
|
20
|
+
priority?: number;
|
|
21
|
+
maxAge?: number;
|
|
22
|
+
}
|
|
23
|
+
export interface RobotsRule {
|
|
24
|
+
userAgent: string | readonly string[];
|
|
25
|
+
allow?: readonly string[];
|
|
26
|
+
disallow?: readonly string[];
|
|
27
|
+
crawlDelay?: number;
|
|
28
|
+
}
|
|
29
|
+
export interface RobotsOptions {
|
|
30
|
+
rules: readonly RobotsRule[];
|
|
31
|
+
sitemap?: string | readonly string[];
|
|
32
|
+
}
|
|
33
|
+
export interface SitemapRoute {
|
|
34
|
+
pattern: string;
|
|
35
|
+
meta?: unknown;
|
|
36
|
+
}
|
|
37
|
+
export declare function checkSitemapOptions(o: SitemapOptions): void;
|
|
38
|
+
export declare function fillPattern(pattern: string, params: Params): string | null;
|
|
39
|
+
export declare function sitemapEntries(siteUrl: string, routes: readonly SitemapRoute[], o: SitemapOptions): Promise<SitemapEntry[]>;
|
|
40
|
+
export declare function sitemapXml(entries: readonly SitemapEntry[]): string;
|
|
41
|
+
export declare function robotsTxt(o: RobotsOptions, sitemapUrl?: string): string;
|
|
42
|
+
export {};
|
package/dist/seo.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
const MAX_URLS = 50_000;
|
|
2
|
+
const FREQ = new Set(["always", "hourly", "daily", "weekly", "monthly", "yearly", "never"]);
|
|
3
|
+
const xmlEscape = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
4
|
+
function httpUrl(raw) {
|
|
5
|
+
try {
|
|
6
|
+
const u = new URL(raw);
|
|
7
|
+
return u.protocol === "http:" || u.protocol === "https:" ? u.href : null;
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function checkSitemapOptions(o) {
|
|
14
|
+
if (!o || typeof o !== "object")
|
|
15
|
+
throw new Error("sitemap: options are an object");
|
|
16
|
+
for (const e of o.exclude ?? []) {
|
|
17
|
+
if (typeof e !== "string" && !(e instanceof RegExp))
|
|
18
|
+
throw new Error("sitemap: exclude holds paths or regular expressions");
|
|
19
|
+
}
|
|
20
|
+
for (const [pattern, f] of Object.entries(o.params ?? {})) {
|
|
21
|
+
if (typeof f !== "function")
|
|
22
|
+
throw new Error(`sitemap: params[${JSON.stringify(pattern)}] is a function`);
|
|
23
|
+
}
|
|
24
|
+
if (o.extra !== undefined && typeof o.extra !== "function")
|
|
25
|
+
throw new Error("sitemap: extra is a function");
|
|
26
|
+
if (o.changeFrequency !== undefined && !FREQ.has(o.changeFrequency))
|
|
27
|
+
throw new Error("sitemap: unknown changeFrequency");
|
|
28
|
+
if (o.priority !== undefined && !(o.priority >= 0 && o.priority <= 1))
|
|
29
|
+
throw new Error("sitemap: priority is 0 to 1");
|
|
30
|
+
if (o.maxAge !== undefined && !(Number.isInteger(o.maxAge) && o.maxAge >= 0))
|
|
31
|
+
throw new Error("sitemap: maxAge is whole seconds");
|
|
32
|
+
}
|
|
33
|
+
function noindex(meta) {
|
|
34
|
+
return !!meta && typeof meta === "object" && /\bnoindex\b/i.test(String(meta.robots ?? ""));
|
|
35
|
+
}
|
|
36
|
+
export function fillPattern(pattern, params) {
|
|
37
|
+
const out = [];
|
|
38
|
+
for (const seg of pattern.split("/").filter((s) => s !== "")) {
|
|
39
|
+
const rest = /^\[\[?\.\.\.([A-Za-z_$][\w$]*)\]\]?$/.exec(seg);
|
|
40
|
+
const one = /^\[([A-Za-z_$][\w$]*)\]$/.exec(seg);
|
|
41
|
+
if (rest) {
|
|
42
|
+
const v = params[rest[1]];
|
|
43
|
+
const parts = v === undefined ? [] : Array.isArray(v) ? v : [v];
|
|
44
|
+
if (parts.some((p) => typeof p !== "string" || p === "" || p === "." || p === ".."))
|
|
45
|
+
return null;
|
|
46
|
+
if (parts.length === 0 && !seg.startsWith("[["))
|
|
47
|
+
return null;
|
|
48
|
+
out.push(...parts.map(encodeURIComponent));
|
|
49
|
+
}
|
|
50
|
+
else if (one) {
|
|
51
|
+
const v = params[one[1]];
|
|
52
|
+
if (typeof v !== "string" || v === "" || v === "." || v === "..")
|
|
53
|
+
return null;
|
|
54
|
+
out.push(encodeURIComponent(v));
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
out.push(seg);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return `/${out.join("/")}`;
|
|
61
|
+
}
|
|
62
|
+
export async function sitemapEntries(siteUrl, routes, o) {
|
|
63
|
+
const origin = new URL(siteUrl).origin;
|
|
64
|
+
const excluded = (path) => (o.exclude ?? []).some((e) => (typeof e === "string" ? e === path : (e.lastIndex = 0, e.test(path))));
|
|
65
|
+
const out = [];
|
|
66
|
+
const seen = new Set();
|
|
67
|
+
const add = (path, e) => {
|
|
68
|
+
if (excluded(path))
|
|
69
|
+
return;
|
|
70
|
+
const url = httpUrl(path.startsWith("/") && !path.startsWith("//") ? origin + path : path);
|
|
71
|
+
if (!url || new URL(url).origin !== origin || seen.has(url))
|
|
72
|
+
return;
|
|
73
|
+
seen.add(url);
|
|
74
|
+
if (out.length >= MAX_URLS)
|
|
75
|
+
throw new Error(`sitemap: more than ${MAX_URLS} URLs; split it with \`extra\` and your own index`);
|
|
76
|
+
out.push({ url, ...e });
|
|
77
|
+
};
|
|
78
|
+
const defaults = {
|
|
79
|
+
...(o.changeFrequency ? { changeFrequency: o.changeFrequency } : {}),
|
|
80
|
+
...(o.priority !== undefined ? { priority: o.priority } : {}),
|
|
81
|
+
};
|
|
82
|
+
const patterns = new Set(routes.map((r) => r.pattern));
|
|
83
|
+
for (const p of Object.keys(o.params ?? {})) {
|
|
84
|
+
if (!patterns.has(p))
|
|
85
|
+
throw new Error(`sitemap: params for ${JSON.stringify(p)}, which is not a route`);
|
|
86
|
+
}
|
|
87
|
+
for (const r of [...routes].sort((a, b) => (a.pattern < b.pattern ? -1 : a.pattern > b.pattern ? 1 : 0))) {
|
|
88
|
+
if (noindex(r.meta))
|
|
89
|
+
continue;
|
|
90
|
+
if (!r.pattern.includes("[")) {
|
|
91
|
+
add(r.pattern, defaults);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const list = o.params?.[r.pattern];
|
|
95
|
+
if (!list)
|
|
96
|
+
continue;
|
|
97
|
+
for (const entry of await list()) {
|
|
98
|
+
const path = entry && typeof entry === "object" ? fillPattern(r.pattern, entry.params ?? {}) : null;
|
|
99
|
+
if (path === null)
|
|
100
|
+
throw new Error(`sitemap: an entry for ${r.pattern} lacks its params`);
|
|
101
|
+
const { params: _p, ...rest } = entry;
|
|
102
|
+
add(path, { ...defaults, ...rest });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
for (const e of o.extra ? await o.extra() : []) {
|
|
106
|
+
const { url, ...rest } = e;
|
|
107
|
+
add(url, { ...defaults, ...rest });
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
export function sitemapXml(entries) {
|
|
112
|
+
const lines = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'];
|
|
113
|
+
for (const e of entries) {
|
|
114
|
+
const url = httpUrl(e.url);
|
|
115
|
+
if (!url)
|
|
116
|
+
throw new Error(`sitemap: ${JSON.stringify(String(e.url).slice(0, 80))} is not an absolute http(s) URL`);
|
|
117
|
+
let line = `<url><loc>${xmlEscape(url)}</loc>`;
|
|
118
|
+
if (e.lastModified !== undefined) {
|
|
119
|
+
const d = new Date(e.lastModified);
|
|
120
|
+
if (Number.isNaN(d.getTime()))
|
|
121
|
+
throw new Error(`sitemap: bad lastModified for ${url}`);
|
|
122
|
+
line += `<lastmod>${d.toISOString()}</lastmod>`;
|
|
123
|
+
}
|
|
124
|
+
if (e.changeFrequency !== undefined) {
|
|
125
|
+
if (!FREQ.has(e.changeFrequency))
|
|
126
|
+
throw new Error(`sitemap: bad changeFrequency for ${url}`);
|
|
127
|
+
line += `<changefreq>${e.changeFrequency}</changefreq>`;
|
|
128
|
+
}
|
|
129
|
+
if (e.priority !== undefined) {
|
|
130
|
+
if (!(e.priority >= 0 && e.priority <= 1))
|
|
131
|
+
throw new Error(`sitemap: priority for ${url} is 0 to 1`);
|
|
132
|
+
line += `<priority>${e.priority.toFixed(1)}</priority>`;
|
|
133
|
+
}
|
|
134
|
+
lines.push(`${line}</url>`);
|
|
135
|
+
}
|
|
136
|
+
lines.push("</urlset>", "");
|
|
137
|
+
return lines.join("\n");
|
|
138
|
+
}
|
|
139
|
+
const ROBOTS_VALUE = /^[^\r\n#]*$/;
|
|
140
|
+
export function robotsTxt(o, sitemapUrl) {
|
|
141
|
+
if (!o || !Array.isArray(o.rules))
|
|
142
|
+
throw new Error("robots: rules is an array");
|
|
143
|
+
const value = (v, what) => {
|
|
144
|
+
if (typeof v !== "string" || !ROBOTS_VALUE.test(v))
|
|
145
|
+
throw new Error(`robots: ${what} is one line without #`);
|
|
146
|
+
return v.trim();
|
|
147
|
+
};
|
|
148
|
+
const groups = [];
|
|
149
|
+
for (const r of o.rules) {
|
|
150
|
+
const agents = typeof r.userAgent === "string" ? [r.userAgent] : [...(r.userAgent ?? [])];
|
|
151
|
+
if (agents.length === 0)
|
|
152
|
+
throw new Error("robots: each rule names a userAgent");
|
|
153
|
+
const lines = agents.map((a) => `User-agent: ${value(a, "userAgent")}`);
|
|
154
|
+
for (const p of r.allow ?? [])
|
|
155
|
+
lines.push(`Allow: ${value(p, "allow")}`);
|
|
156
|
+
for (const p of r.disallow ?? [])
|
|
157
|
+
lines.push(`Disallow: ${value(p, "disallow")}`);
|
|
158
|
+
if (!r.allow?.length && !r.disallow?.length)
|
|
159
|
+
lines.push("Disallow:");
|
|
160
|
+
if (r.crawlDelay !== undefined) {
|
|
161
|
+
if (!(Number.isFinite(r.crawlDelay) && r.crawlDelay >= 0))
|
|
162
|
+
throw new Error("robots: crawlDelay is seconds");
|
|
163
|
+
lines.push(`Crawl-delay: ${r.crawlDelay}`);
|
|
164
|
+
}
|
|
165
|
+
groups.push(lines.join("\n"));
|
|
166
|
+
}
|
|
167
|
+
const maps = [...(typeof o.sitemap === "string" ? [o.sitemap] : (o.sitemap ?? [])), ...(sitemapUrl ? [sitemapUrl] : [])];
|
|
168
|
+
const tail = [...new Set(maps)].map((m) => {
|
|
169
|
+
const u = httpUrl(value(m, "sitemap"));
|
|
170
|
+
if (!u)
|
|
171
|
+
throw new Error("robots: sitemap URLs are absolute http(s) URLs");
|
|
172
|
+
return `Sitemap: ${u}`;
|
|
173
|
+
});
|
|
174
|
+
return [...groups, ...(tail.length ? [tail.join("\n")] : [])].join("\n\n") + "\n";
|
|
175
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { PageContext } from "./context.js";
|
|
2
|
+
interface SettingBase {
|
|
3
|
+
label?: string;
|
|
4
|
+
description?: string;
|
|
5
|
+
editable?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export type SettingSpec = (SettingBase & {
|
|
8
|
+
type: "boolean";
|
|
9
|
+
default: boolean;
|
|
10
|
+
}) | (SettingBase & {
|
|
11
|
+
type: "number";
|
|
12
|
+
default: number;
|
|
13
|
+
min?: number;
|
|
14
|
+
max?: number;
|
|
15
|
+
integer?: boolean;
|
|
16
|
+
}) | (SettingBase & {
|
|
17
|
+
type: "string";
|
|
18
|
+
default: string;
|
|
19
|
+
options?: readonly string[];
|
|
20
|
+
maxLength?: number;
|
|
21
|
+
});
|
|
22
|
+
export type SettingsSchema = {
|
|
23
|
+
readonly [key: string]: SettingSpec;
|
|
24
|
+
};
|
|
25
|
+
type Values = Record<string, unknown>;
|
|
26
|
+
export interface SettingsOptions {
|
|
27
|
+
schema: SettingsSchema;
|
|
28
|
+
load(ctx: PageContext): Values | undefined | Promise<Values | undefined>;
|
|
29
|
+
save(ctx: PageContext, patch: Values): unknown;
|
|
30
|
+
canEdit?(ctx: PageContext, key: string): boolean | Promise<boolean>;
|
|
31
|
+
groups?: readonly {
|
|
32
|
+
label: string;
|
|
33
|
+
description?: string;
|
|
34
|
+
keys: readonly string[];
|
|
35
|
+
}[];
|
|
36
|
+
}
|
|
37
|
+
export interface SettingView {
|
|
38
|
+
key: string;
|
|
39
|
+
label: string;
|
|
40
|
+
description: string | null;
|
|
41
|
+
type: SettingSpec["type"];
|
|
42
|
+
value: boolean | number | string;
|
|
43
|
+
editable: boolean;
|
|
44
|
+
fixed: boolean;
|
|
45
|
+
options: readonly string[] | null;
|
|
46
|
+
min: number | null;
|
|
47
|
+
max: number | null;
|
|
48
|
+
integer: boolean;
|
|
49
|
+
maxLength: number | null;
|
|
50
|
+
}
|
|
51
|
+
export interface SettingsView {
|
|
52
|
+
sections: {
|
|
53
|
+
label: string;
|
|
54
|
+
description: string | null;
|
|
55
|
+
settings: SettingView[];
|
|
56
|
+
}[];
|
|
57
|
+
shown: Record<string, boolean | number | string>;
|
|
58
|
+
}
|
|
59
|
+
export type SaveResult = {
|
|
60
|
+
ok: true;
|
|
61
|
+
saved: Values;
|
|
62
|
+
} | {
|
|
63
|
+
ok: false;
|
|
64
|
+
reason: "not found" | "forbidden";
|
|
65
|
+
error: string;
|
|
66
|
+
} | {
|
|
67
|
+
ok: false;
|
|
68
|
+
reason: "invalid";
|
|
69
|
+
key: string | null;
|
|
70
|
+
error: string;
|
|
71
|
+
};
|
|
72
|
+
export interface Settings {
|
|
73
|
+
view(ctx: PageContext): Promise<SettingsView | null>;
|
|
74
|
+
save(ctx: PageContext, input: Readonly<Record<string, unknown>>, shown?: Readonly<Record<string, unknown>> | null): Promise<SaveResult>;
|
|
75
|
+
schema: SettingsSchema;
|
|
76
|
+
}
|
|
77
|
+
export declare function settingProblem(spec: SettingSpec, value: unknown): string | null;
|
|
78
|
+
export declare function defineSettings(opts: SettingsOptions): Settings;
|
|
79
|
+
export {};
|
package/dist/settings.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
const KEY_RE = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/;
|
|
2
|
+
const MAX_TEXT = 1000;
|
|
3
|
+
export function settingProblem(spec, value) {
|
|
4
|
+
switch (spec.type) {
|
|
5
|
+
case "boolean":
|
|
6
|
+
return typeof value === "boolean" ? null : "is yes or no";
|
|
7
|
+
case "number":
|
|
8
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
9
|
+
return "is a number";
|
|
10
|
+
if (spec.integer && !Number.isInteger(value))
|
|
11
|
+
return "is a whole number";
|
|
12
|
+
if (spec.min !== undefined && value < spec.min)
|
|
13
|
+
return `is at least ${spec.min}`;
|
|
14
|
+
if (spec.max !== undefined && value > spec.max)
|
|
15
|
+
return `is at most ${spec.max}`;
|
|
16
|
+
return null;
|
|
17
|
+
case "string":
|
|
18
|
+
if (typeof value !== "string")
|
|
19
|
+
return "is text";
|
|
20
|
+
if (spec.options && !spec.options.includes(value))
|
|
21
|
+
return `is one of ${spec.options.join(", ")}`;
|
|
22
|
+
return value.length <= (spec.maxLength ?? MAX_TEXT) ? null : `is at most ${spec.maxLength ?? MAX_TEXT} characters`;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function humanize(key) {
|
|
26
|
+
const s = key.replace(/[._]+/g, " ").trim();
|
|
27
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
28
|
+
}
|
|
29
|
+
function numberToken(t) {
|
|
30
|
+
let i = 0;
|
|
31
|
+
if (t[i] === "-")
|
|
32
|
+
i++;
|
|
33
|
+
let digits = false;
|
|
34
|
+
while (i < t.length && t.charCodeAt(i) >= 48 && t.charCodeAt(i) <= 57) {
|
|
35
|
+
i++;
|
|
36
|
+
digits = true;
|
|
37
|
+
}
|
|
38
|
+
if (t[i] === ".") {
|
|
39
|
+
i++;
|
|
40
|
+
while (i < t.length && t.charCodeAt(i) >= 48 && t.charCodeAt(i) <= 57) {
|
|
41
|
+
i++;
|
|
42
|
+
digits = true;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (!digits)
|
|
46
|
+
return false;
|
|
47
|
+
if (t[i] === "e" || t[i] === "E") {
|
|
48
|
+
i++;
|
|
49
|
+
if (t[i] === "+" || t[i] === "-")
|
|
50
|
+
i++;
|
|
51
|
+
const exp = i;
|
|
52
|
+
while (i < t.length && t.charCodeAt(i) >= 48 && t.charCodeAt(i) <= 57)
|
|
53
|
+
i++;
|
|
54
|
+
if (i === exp)
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
return i === t.length;
|
|
58
|
+
}
|
|
59
|
+
function parse(spec, raw) {
|
|
60
|
+
if (typeof raw !== "string")
|
|
61
|
+
return raw;
|
|
62
|
+
if (spec.type === "boolean")
|
|
63
|
+
return raw === "true" ? true : raw === "false" ? false : raw;
|
|
64
|
+
if (spec.type === "number") {
|
|
65
|
+
const t = raw.trim();
|
|
66
|
+
return t === "" || !numberToken(t) ? Number.NaN : Number(t);
|
|
67
|
+
}
|
|
68
|
+
return raw;
|
|
69
|
+
}
|
|
70
|
+
export function defineSettings(opts) {
|
|
71
|
+
const fail = (msg) => {
|
|
72
|
+
throw new Error(`defineSettings: ${msg}`);
|
|
73
|
+
};
|
|
74
|
+
if (!opts || typeof opts.load !== "function" || typeof opts.save !== "function")
|
|
75
|
+
fail("`load(ctx)` and `save(ctx, patch)` are required");
|
|
76
|
+
if (opts.canEdit !== undefined && typeof opts.canEdit !== "function")
|
|
77
|
+
fail("canEdit is a function");
|
|
78
|
+
const specs = new Map();
|
|
79
|
+
for (const [key, spec] of Object.entries(opts.schema ?? {})) {
|
|
80
|
+
if (!KEY_RE.test(key) || key.length > 100)
|
|
81
|
+
fail(`setting \`${key}\`: keys are lower case, dot-separated`);
|
|
82
|
+
if (!spec || !["boolean", "number", "string"].includes(spec.type))
|
|
83
|
+
fail(`setting \`${key}\`: type is boolean, number or string`);
|
|
84
|
+
if (spec.type === "string" && spec.options !== undefined && (!Array.isArray(spec.options) || spec.options.length === 0)) {
|
|
85
|
+
fail(`setting \`${key}\`: options lists the allowed values`);
|
|
86
|
+
}
|
|
87
|
+
if (spec.type === "number" && spec.min !== undefined && spec.max !== undefined && spec.min > spec.max)
|
|
88
|
+
fail(`setting \`${key}\`: min is above max`);
|
|
89
|
+
const p = settingProblem(spec, spec.default);
|
|
90
|
+
if (p !== null)
|
|
91
|
+
fail(`setting \`${key}\`: the default ${p}`);
|
|
92
|
+
specs.set(key, spec);
|
|
93
|
+
}
|
|
94
|
+
if (specs.size === 0)
|
|
95
|
+
fail("the schema has no settings");
|
|
96
|
+
const sections = [];
|
|
97
|
+
const placed = new Set();
|
|
98
|
+
for (const g of opts.groups ?? []) {
|
|
99
|
+
if (!g || typeof g.label !== "string" || g.label === "")
|
|
100
|
+
fail("each group has a label");
|
|
101
|
+
for (const k of g.keys) {
|
|
102
|
+
if (!specs.has(k))
|
|
103
|
+
fail(`group \`${g.label}\`: no setting \`${k}\``);
|
|
104
|
+
if (placed.has(k))
|
|
105
|
+
fail(`setting \`${k}\` is in two groups`);
|
|
106
|
+
placed.add(k);
|
|
107
|
+
}
|
|
108
|
+
sections.push({ label: g.label, description: g.description ?? null, keys: [...g.keys] });
|
|
109
|
+
}
|
|
110
|
+
const rest = [...specs.keys()].filter((k) => !placed.has(k));
|
|
111
|
+
if (rest.length)
|
|
112
|
+
sections.push({ label: "", description: null, keys: rest });
|
|
113
|
+
async function editableKeys(ctx) {
|
|
114
|
+
const out = new Set();
|
|
115
|
+
for (const [k, spec] of specs) {
|
|
116
|
+
if (spec.editable !== true)
|
|
117
|
+
continue;
|
|
118
|
+
let ok = true;
|
|
119
|
+
if (opts.canEdit) {
|
|
120
|
+
try {
|
|
121
|
+
ok = (await opts.canEdit(ctx, k)) === true;
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
ok = false;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (ok)
|
|
128
|
+
out.add(k);
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
async function current(ctx) {
|
|
133
|
+
const v = await opts.load(ctx);
|
|
134
|
+
if (v === undefined || v === null)
|
|
135
|
+
return undefined;
|
|
136
|
+
const out = {};
|
|
137
|
+
for (const [k, spec] of specs)
|
|
138
|
+
out[k] = Object.hasOwn(v, k) && settingProblem(spec, v[k]) === null ? v[k] : spec.default;
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
schema: Object.freeze(Object.fromEntries(specs)),
|
|
143
|
+
async view(ctx) {
|
|
144
|
+
const values = await current(ctx);
|
|
145
|
+
if (values === undefined)
|
|
146
|
+
return null;
|
|
147
|
+
const can = await editableKeys(ctx);
|
|
148
|
+
const shown = {};
|
|
149
|
+
for (const k of can)
|
|
150
|
+
shown[k] = values[k];
|
|
151
|
+
return {
|
|
152
|
+
shown,
|
|
153
|
+
sections: sections.map((s) => ({
|
|
154
|
+
label: s.label,
|
|
155
|
+
description: s.description,
|
|
156
|
+
settings: s.keys.map((key) => {
|
|
157
|
+
const spec = specs.get(key);
|
|
158
|
+
return {
|
|
159
|
+
key,
|
|
160
|
+
label: spec.label ?? humanize(key),
|
|
161
|
+
description: spec.description ?? null,
|
|
162
|
+
type: spec.type,
|
|
163
|
+
value: values[key],
|
|
164
|
+
editable: can.has(key),
|
|
165
|
+
fixed: spec.editable !== true,
|
|
166
|
+
options: spec.type === "string" ? (spec.options ?? null) : null,
|
|
167
|
+
min: spec.type === "number" ? (spec.min ?? null) : null,
|
|
168
|
+
max: spec.type === "number" ? (spec.max ?? null) : null,
|
|
169
|
+
integer: spec.type === "number" && spec.integer === true,
|
|
170
|
+
maxLength: spec.type === "string" ? (spec.maxLength ?? MAX_TEXT) : null,
|
|
171
|
+
};
|
|
172
|
+
}),
|
|
173
|
+
})),
|
|
174
|
+
};
|
|
175
|
+
},
|
|
176
|
+
async save(ctx, input, shown = null) {
|
|
177
|
+
const now = await current(ctx);
|
|
178
|
+
if (now === undefined)
|
|
179
|
+
return { ok: false, reason: "not found", error: "Not found" };
|
|
180
|
+
if (!input || typeof input !== "object")
|
|
181
|
+
return { ok: false, reason: "invalid", key: null, error: "No settings given" };
|
|
182
|
+
const editable = await editableKeys(ctx);
|
|
183
|
+
const patch = {};
|
|
184
|
+
for (const key of editable) {
|
|
185
|
+
if (!Object.hasOwn(input, key))
|
|
186
|
+
continue;
|
|
187
|
+
const spec = specs.get(key);
|
|
188
|
+
const v = parse(spec, input[key]);
|
|
189
|
+
const p = settingProblem(spec, v);
|
|
190
|
+
if (p !== null)
|
|
191
|
+
return { ok: false, reason: "invalid", key, error: `${spec.label ?? humanize(key)}: ${p}` };
|
|
192
|
+
const before = shown && Object.hasOwn(shown, key) ? parse(spec, shown[key]) : now[key];
|
|
193
|
+
if (v !== before && v !== now[key])
|
|
194
|
+
patch[key] = v;
|
|
195
|
+
}
|
|
196
|
+
if (Object.keys(patch).length > 0) {
|
|
197
|
+
try {
|
|
198
|
+
await opts.save(ctx, patch);
|
|
199
|
+
}
|
|
200
|
+
catch (err) {
|
|
201
|
+
const code = err?.code;
|
|
202
|
+
if (code === "invalid")
|
|
203
|
+
return { ok: false, reason: "invalid", key: null, error: err.message };
|
|
204
|
+
if (code === "forbidden" || code === "not-found")
|
|
205
|
+
return { ok: false, reason: "forbidden", error: "You may not change these settings" };
|
|
206
|
+
throw err;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return { ok: true, saved: patch };
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
package/dist/shared.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type Change } from "@weft-framework/data";
|
|
2
|
+
import { type ServerMessage, type TextMessage } from "@weft-framework/runtime";
|
|
3
|
+
export interface SharedFieldOptions {
|
|
4
|
+
label?: (actor: unknown) => string | null | undefined;
|
|
5
|
+
saveMs?: number;
|
|
6
|
+
maxLength?: number;
|
|
7
|
+
}
|
|
8
|
+
type Send = (msg: ServerMessage) => void;
|
|
9
|
+
export declare function sharedMessage(entry: object, actor: unknown, msg: TextMessage, send: Send, opts: SharedFieldOptions & {
|
|
10
|
+
onError: (err: unknown) => void;
|
|
11
|
+
}): void;
|
|
12
|
+
export declare function sharedLeave(entry: object): void;
|
|
13
|
+
export declare function sharedChange(change: Change): void;
|
|
14
|
+
export declare function resetShared(): void;
|
|
15
|
+
export {};
|