@protobase/schema 0.8.2 → 0.10.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.
@@ -18,6 +18,7 @@ export type ResolveOptions = {
18
18
  */
19
19
  roles?: {
20
20
  can: (capability: any) => Rule;
21
+ definitions?: Record<string, unknown>;
21
22
  };
22
23
  /**
23
24
  * Overrides what an operation without a rule does. Without `roles` the default is `allow`,
@@ -0,0 +1,14 @@
1
+ import { BottomBarModel } from "./model.js";
2
+ //#region src/bottom-bar-errors.d.ts
3
+ /** What the bottom bars may name. Without `roles` (an app whose roles are not declared) any role is accepted. */
4
+ export type BottomBarNames = {
5
+ resources: readonly string[];
6
+ pages: readonly string[];
7
+ roles?: readonly string[];
8
+ };
9
+ /**
10
+ * Why the bottom bars do not fit the app, as messages; empty when they do. Pure, so it can run wherever the config is
11
+ * known: at startup today, when a bundle is built later.
12
+ */
13
+ export declare const bottomBarErrors: (bars: BottomBarModel[], names: BottomBarNames) => string[];
14
+ //#endregion
@@ -0,0 +1,33 @@
1
+ import "./bottom-bar.js";
2
+ //#region src/bottom-bar-errors.ts
3
+ const itemErrors = (item, names) => {
4
+ if (item.kind === "resource" && !names.resources.includes(item.resource)) return [`resource "${item.resource}" does not exist`];
5
+ if (item.kind === "page" && !names.pages.includes(item.page)) return [`page "${item.page}" does not exist`];
6
+ return [];
7
+ };
8
+ const barErrors = (bar, names) => {
9
+ const unknownRoles = names.roles ? bar.roles.filter((role) => !names.roles.includes(role)) : [];
10
+ return [
11
+ ...bar.roles.length === 0 ? ["needs at least one role"] : [],
12
+ ...unknownRoles.map((role) => `role "${role}" is not one of the roles: ${names.roles.join(", ")}`),
13
+ ...bar.items.length === 0 ? ["needs at least one item"] : [],
14
+ ...bar.items.length > 4 ? [`has ${bar.items.length} items; at most 4 fit beside "More"`] : [],
15
+ ...bar.items.flatMap((item) => itemErrors(item, names))
16
+ ].map((error) => `Bottom bar "${bar.label}": ${error}`);
17
+ };
18
+ const overlapErrors = (bars) => bars.flatMap((bar, index) => {
19
+ const earlier = bars.slice(0, index);
20
+ const sameLabel = earlier.some((other) => other.label === bar.label) ? [`Two bottom bars are labelled "${bar.label}"; give each its own label`] : [];
21
+ const shared = bar.roles.flatMap((role) => {
22
+ const other = earlier.find((candidate) => candidate.roles.includes(role));
23
+ return other ? [`Bottom bars "${other.label}" and "${bar.label}" both name role "${role}"; a role belongs to one bottom bar`] : [];
24
+ });
25
+ return [...sameLabel, ...shared];
26
+ });
27
+ /**
28
+ * Why the bottom bars do not fit the app, as messages; empty when they do. Pure, so it can run wherever the config is
29
+ * known: at startup today, when a bundle is built later.
30
+ */
31
+ const bottomBarErrors = (bars, names) => [...bars.flatMap((bar) => barErrors(bar, names)), ...overlapErrors(bars)];
32
+ //#endregion
33
+ export { bottomBarErrors };
@@ -0,0 +1,35 @@
1
+ import { BottomBarItemModel, BottomBarModel } from "./model.js";
2
+ //#region src/bottom-bar.d.ts
3
+ /** The tabs beside the last one, "More", which opens the sidebar: five tabs in all, as on iOS. */
4
+ export declare const maxBottomBarItems = 4;
5
+ declare const items: {
6
+ /** Opens the resource's list. */
7
+ resource: (resource: string, options: {
8
+ label: string;
9
+ icon?: string;
10
+ }) => BottomBarItemModel;
11
+ /** Opens a composed page (`page()` from @protobase/layout). */
12
+ page: (page: string, options: {
13
+ label: string;
14
+ icon?: string;
15
+ }) => BottomBarItemModel;
16
+ /** An address outside the admin, opened in a new tab: `https:`, `http:` or `mailto:`. */
17
+ link: (label: string, href: string, options?: {
18
+ icon?: string;
19
+ }) => BottomBarItemModel;
20
+ };
21
+ /** What the server needs from a `bottomBar(...)` export of the config module. */
22
+ export type BottomBarSource = {
23
+ toBottomBarModel(): BottomBarModel;
24
+ };
25
+ /**
26
+ * Tabs at the bottom of the screen on phones, for the users holding one of `roles`. Export one per group of roles; a
27
+ * role belongs to one bottom bar. `label` names the bar where someone with several switches between them.
28
+ */
29
+ export declare const bottomBar: (options: {
30
+ label: string;
31
+ roles: string[];
32
+ }, build: (m: typeof items) => BottomBarItemModel[]) => BottomBarSource;
33
+ /** The bottom bar of someone working as `role`: the one that names it, since a role belongs to one bar. */
34
+ export declare const bottomBarFor: (bars: readonly BottomBarModel[], role: string | undefined) => BottomBarModel | undefined;
35
+ //#endregion
@@ -0,0 +1,44 @@
1
+ import { isMenuHref } from "./menu-href.js";
2
+ //#region src/bottom-bar.ts
3
+ /** The tabs beside the last one, "More", which opens the sidebar: five tabs in all, as on iOS. */
4
+ const maxBottomBarItems = 4;
5
+ const items = {
6
+ /** Opens the resource's list. */
7
+ resource: (resource, options) => ({
8
+ kind: "resource",
9
+ resource,
10
+ ...options
11
+ }),
12
+ /** Opens a composed page (`page()` from @protobase/layout). */
13
+ page: (page, options) => ({
14
+ kind: "page",
15
+ page,
16
+ ...options
17
+ }),
18
+ /** An address outside the admin, opened in a new tab: `https:`, `http:` or `mailto:`. */
19
+ link: (label, href, options = {}) => {
20
+ if (!isMenuHref(href)) throw new Error(`Bottom bar link "${label}": href must start with https://, http:// or mailto:`);
21
+ return {
22
+ kind: "link",
23
+ label,
24
+ href,
25
+ ...options
26
+ };
27
+ }
28
+ };
29
+ /**
30
+ * Tabs at the bottom of the screen on phones, for the users holding one of `roles`. Export one per group of roles; a
31
+ * role belongs to one bottom bar. `label` names the bar where someone with several switches between them.
32
+ */
33
+ const bottomBar = (options, build) => {
34
+ const model = {
35
+ label: options.label,
36
+ roles: [...options.roles],
37
+ items: build(items)
38
+ };
39
+ return { toBottomBarModel: () => structuredClone(model) };
40
+ };
41
+ /** The bottom bar of someone working as `role`: the one that names it, since a role belongs to one bar. */
42
+ const bottomBarFor = (bars, role) => role === void 0 ? void 0 : bars.find((bar) => bar.roles.includes(role));
43
+ //#endregion
44
+ export { bottomBar, bottomBarFor, maxBottomBarItems };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ActionModel, ActionRun, ChartGranularity, ChartModel, ChartRange, CheckedFilter, CompareOp, DatePreset, DurationLiteral, DurationUnit, EventModel, EventOperation, FieldFormat, FieldModel, FieldPath, FieldType, FieldViewModel, FileFieldModel, FilterError, FilterErrorCode, FilterExpr, FilterOf, FilterValue, FilterWidgetModel, KeyValue, LayoutItemModel, ListModel, ListQuery, Literal, NavModel, NavRecentModel, NowValue, OrderByItem, RelatedModel, ResourceModel, SaveFeedback, SearchMatch, SearchResultModel, SortSpec, Span, StatusTone, UserMenuItemModel, UserMenuModel, ViewModel } from "./model.js";
1
+ import { ActionModel, ActionRun, BottomBarItemModel, BottomBarModel, ChartGranularity, ChartModel, ChartRange, CheckedFilter, CompareOp, DatePreset, DurationLiteral, DurationUnit, EventModel, EventOperation, FieldFormat, FieldModel, FieldPath, FieldType, FieldViewModel, FileFieldModel, FilterError, FilterErrorCode, FilterExpr, FilterOf, FilterValue, FilterWidgetModel, KeyValue, LayoutItemModel, ListModel, ListQuery, Literal, NavModel, NavRecentModel, NowValue, OrderByItem, RelatedModel, ResourceModel, SaveFeedback, SearchMatch, SearchResultModel, SortSpec, Span, StatusTone, UserMenuItemModel, UserMenuModel, ViewModel } from "./model.js";
2
2
  import { AccessAction, AccessContext, AccessFn, AccessResult, AccessUser, FieldAccess, FieldRule } from "./access/types.js";
3
3
  import { FileProcessor, FileProcessorInput, checkedAccept, checkedProvider, parseSize } from "./files/file-options.js";
4
4
  import { Field } from "./field.js";
@@ -9,10 +9,13 @@ import { InferRecord, RecordKey } from "./resource-types.js";
9
9
  import { resource } from "./resource.js";
10
10
  import { checkEventFilter } from "./events/event-models.js";
11
11
  import { view } from "./view.js";
12
+ import { webhookResources } from "./webhooks/webhook-resources.js";
12
13
  import { enumLabel } from "./enum-label.js";
13
14
  import { SearchTerm, matchedSearchField, matchesSearch, searchTerms, termMatches } from "./search-match.js";
14
15
  import { defaultRecentLimit, navRecentErrors, statusTones } from "./nav-recent.js";
15
16
  import { UserMenuSource, userMenu } from "./user-menu.js";
17
+ import { BottomBarSource, bottomBar, bottomBarFor, maxBottomBarItems } from "./bottom-bar.js";
18
+ import { BottomBarNames, bottomBarErrors } from "./bottom-bar-errors.js";
16
19
  import { layout } from "./layout.js";
17
20
  import { KeyType, decodeKey, encodeKey, keyTypes } from "./keys.js";
18
21
  import { FilterLimits, FilterParse, parseFilter } from "./filter/parse.js";
@@ -32,4 +35,4 @@ import "./access/index.js";
32
35
  import { AssistantAction, AssistantActionRequest, AssistantCardPart, AssistantDiff, AssistantEvent, AssistantMessage, AssistantMessageRequest, AssistantPart, AssistantState, AssistantStep, AssistantStepState, AssistantTablePart, AssistantTextPart, AssistantTone, AssistantWidgetPart } from "./assistant/protocol.js";
33
36
  import { applyAssistantEvent, emptyAssistantState } from "./assistant/apply-event.js";
34
37
  import { readEventStream } from "./assistant/event-stream.js";
35
- export { type AccessAction, type AccessContext, type AccessFn, type AccessResult, type AccessSource, type AccessUser, type ActionModel, type ActionRun, type AssistantAction, type AssistantActionRequest, type AssistantCardPart, type AssistantDiff, type AssistantEvent, type AssistantMessage, type AssistantMessageRequest, type AssistantPart, type AssistantState, type AssistantStep, type AssistantStepState, type AssistantTablePart, type AssistantTextPart, type AssistantTone, type AssistantWidgetPart, type Capability, type CapabilityAction, type CapabilityScope, type ChartGranularity, type ChartModel, type ChartRange, type CheckResult, type CheckedFilter, type CompareOp, type DatePreset, type DurationLiteral, type DurationUnit, type EvaluateOptions, type EventActor, type EventContext, type EventHelpers, type EventMatch, type EventModel, type EventOperation, type EventSpec, type Field, type FieldAccess, type FieldFormat, type FieldModel, type FieldPath, type FieldRule, type FieldType, type FieldViewModel, type FileField, type FileFieldModel, type FileProcessor, type FileProcessorInput, type FilterError, type FilterErrorCode, type FilterExpr, type FilterLimits, type FilterOf, type FilterParse, type FilterValue, type FilterWidgetModel, type InferRecord, type KeyType, type KeyValue, type LayoutItemModel, type ListModel, type ListQuery, type Literal, type NavModel, type NavRecentModel, type NowValue, type OrderByCheck, type OrderByItem, type OrderByParse, type RecordKey, type RelatedModel, type ResolveOptions, type ResolvedAccess, type ResourceModel, type Roles, type RolesOptions, type RowFilterOperation, type Rule, type SaveFeedback, type SearchMatch, type SearchResultModel, type SearchTerm, type SortSpec, type Span, type StatusTone, type UserMenuItemModel, type UserMenuModel, type UserMenuSource, type ViewModel, accessWarnings, applyAssistantEvent, checkEventFilter, checkFilter, checkOrderBy, checkRecord, checkedAccept, checkedProvider, createWhere, decodeKey, defaultRecentLimit, defineRoles, emptyAssistantState, encodeKey, enumLabel, evaluateFilter, f, fieldsUsedBy, keyTypes, layout as l, matchedSearchField, matchesSearch, navRecentErrors, parseFilter, parseOrderBy, parseSize, pickView, printFilter, printOrderBy, readEventStream, resolveAccess, resource, restrictModel, rule, searchTerms, statusTones, termMatches, userMenu, view, where };
38
+ export { type AccessAction, type AccessContext, type AccessFn, type AccessResult, type AccessSource, type AccessUser, type ActionModel, type ActionRun, type AssistantAction, type AssistantActionRequest, type AssistantCardPart, type AssistantDiff, type AssistantEvent, type AssistantMessage, type AssistantMessageRequest, type AssistantPart, type AssistantState, type AssistantStep, type AssistantStepState, type AssistantTablePart, type AssistantTextPart, type AssistantTone, type AssistantWidgetPart, type BottomBarItemModel, type BottomBarModel, type BottomBarNames, type BottomBarSource, type Capability, type CapabilityAction, type CapabilityScope, type ChartGranularity, type ChartModel, type ChartRange, type CheckResult, type CheckedFilter, type CompareOp, type DatePreset, type DurationLiteral, type DurationUnit, type EvaluateOptions, type EventActor, type EventContext, type EventHelpers, type EventMatch, type EventModel, type EventOperation, type EventSpec, type Field, type FieldAccess, type FieldFormat, type FieldModel, type FieldPath, type FieldRule, type FieldType, type FieldViewModel, type FileField, type FileFieldModel, type FileProcessor, type FileProcessorInput, type FilterError, type FilterErrorCode, type FilterExpr, type FilterLimits, type FilterOf, type FilterParse, type FilterValue, type FilterWidgetModel, type InferRecord, type KeyType, type KeyValue, type LayoutItemModel, type ListModel, type ListQuery, type Literal, type NavModel, type NavRecentModel, type NowValue, type OrderByCheck, type OrderByItem, type OrderByParse, type RecordKey, type RelatedModel, type ResolveOptions, type ResolvedAccess, type ResourceModel, type Roles, type RolesOptions, type RowFilterOperation, type Rule, type SaveFeedback, type SearchMatch, type SearchResultModel, type SearchTerm, type SortSpec, type Span, type StatusTone, type UserMenuItemModel, type UserMenuModel, type UserMenuSource, type ViewModel, accessWarnings, applyAssistantEvent, bottomBar, bottomBarErrors, bottomBarFor, checkEventFilter, checkFilter, checkOrderBy, checkRecord, checkedAccept, checkedProvider, createWhere, decodeKey, defaultRecentLimit, defineRoles, emptyAssistantState, encodeKey, enumLabel, evaluateFilter, f, fieldsUsedBy, keyTypes, layout as l, matchedSearchField, matchesSearch, maxBottomBarItems, navRecentErrors, parseFilter, parseOrderBy, parseSize, pickView, printFilter, printOrderBy, readEventStream, resolveAccess, resource, restrictModel, rule, searchTerms, statusTones, termMatches, userMenu, view, webhookResources, where };
package/dist/index.js CHANGED
@@ -9,12 +9,15 @@ import { createWhere, where } from "./filter/where.js";
9
9
  import { accessWarnings, checkRecord, fieldsUsedBy, resolveAccess } from "./access/resolve.js";
10
10
  import { checkEventFilter } from "./events/event-models.js";
11
11
  import { resource } from "./resource.js";
12
+ import { layout } from "./layout.js";
12
13
  import { defaultRecentLimit, navRecentErrors, statusTones } from "./nav-recent.js";
13
14
  import { view } from "./view.js";
15
+ import { webhookResources } from "./webhooks/webhook-resources.js";
14
16
  import { enumLabel } from "./enum-label.js";
15
17
  import { matchedSearchField, matchesSearch, searchTerms, termMatches } from "./search-match.js";
16
18
  import { userMenu } from "./user-menu.js";
17
- import { layout } from "./layout.js";
19
+ import { bottomBar, bottomBarFor, maxBottomBarItems } from "./bottom-bar.js";
20
+ import { bottomBarErrors } from "./bottom-bar-errors.js";
18
21
  import { decodeKey, encodeKey, keyTypes } from "./keys.js";
19
22
  import { rule } from "./access/rule.js";
20
23
  import { defineRoles } from "./access/roles.js";
@@ -22,4 +25,4 @@ import { pickView } from "./access/pick-view.js";
22
25
  import { restrictModel } from "./access/restrict.js";
23
26
  import { applyAssistantEvent, emptyAssistantState } from "./assistant/apply-event.js";
24
27
  import { readEventStream } from "./assistant/event-stream.js";
25
- export { accessWarnings, applyAssistantEvent, checkEventFilter, checkFilter, checkOrderBy, checkRecord, checkedAccept, checkedProvider, createWhere, decodeKey, defaultRecentLimit, defineRoles, emptyAssistantState, encodeKey, enumLabel, evaluateFilter, f, fieldsUsedBy, keyTypes, layout as l, matchedSearchField, matchesSearch, navRecentErrors, parseFilter, parseOrderBy, parseSize, pickView, printFilter, printOrderBy, readEventStream, resolveAccess, resource, restrictModel, rule, searchTerms, statusTones, termMatches, userMenu, view, where };
28
+ export { accessWarnings, applyAssistantEvent, bottomBar, bottomBarErrors, bottomBarFor, checkEventFilter, checkFilter, checkOrderBy, checkRecord, checkedAccept, checkedProvider, createWhere, decodeKey, defaultRecentLimit, defineRoles, emptyAssistantState, encodeKey, enumLabel, evaluateFilter, f, fieldsUsedBy, keyTypes, layout as l, matchedSearchField, matchesSearch, maxBottomBarItems, navRecentErrors, parseFilter, parseOrderBy, parseSize, pickView, printFilter, printOrderBy, readEventStream, resolveAccess, resource, restrictModel, rule, searchTerms, statusTones, termMatches, userMenu, view, webhookResources, where };
@@ -0,0 +1,5 @@
1
+ //#region src/menu-href.ts
2
+ /** Where a menu link may point: a web or mail address outside the admin, never `javascript:` or a path inside it. */
3
+ const isMenuHref = (href) => /^(https?:\/\/|mailto:)/i.test(href);
4
+ //#endregion
5
+ export { isMenuHref };
package/dist/model.d.ts CHANGED
@@ -218,6 +218,29 @@ export type UserMenuItemModel = {
218
218
  export type UserMenuModel = {
219
219
  items: UserMenuItemModel[];
220
220
  };
221
+ /** A tab of a bottom bar on phones: icon above an explicit label. */
222
+ export type BottomBarItemModel = {
223
+ kind: 'resource';
224
+ resource: string;
225
+ label: string;
226
+ icon?: string;
227
+ } | {
228
+ kind: 'page';
229
+ page: string;
230
+ label: string;
231
+ icon?: string;
232
+ } | {
233
+ kind: 'link';
234
+ label: string;
235
+ href: string;
236
+ icon?: string;
237
+ };
238
+ /** A bottom bar for the users holding one of `roles`; `label` names it in the role view switcher. */
239
+ export type BottomBarModel = {
240
+ label: string;
241
+ roles: string[];
242
+ items: BottomBarItemModel[];
243
+ };
221
244
  /**
222
245
  * The title replaces `title` in search results; `subtitle` is the second line unless the search matched another search
223
246
  * field, which then shows instead. Without a subtitle, the first search field not in the title is the default.
package/dist/user-menu.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { isMenuHref } from "./menu-href.js";
1
2
  //#region src/user-menu.ts
2
3
  const items = {
3
4
  /** Opens the resource's list. A resource in the user menu is left out of the sidebar. */
@@ -14,7 +15,7 @@ const items = {
14
15
  }),
15
16
  /** An address outside the admin, opened in a new tab: `https:`, `http:` or `mailto:`. */
16
17
  link: (label, href, options = {}) => {
17
- if (!/^(https?:\/\/|mailto:)/i.test(href)) throw new Error(`User menu link "${label}": href must start with https://, http:// or mailto:`);
18
+ if (!isMenuHref(href)) throw new Error(`User menu link "${label}": href must start with https://, http:// or mailto:`);
18
19
  return {
19
20
  kind: "link",
20
21
  label,
@@ -0,0 +1,113 @@
1
+ import { Field } from "../field.js";
2
+ import { Ref } from "../refs.js";
3
+ import { ResourceBuilder } from "../resource.js";
4
+ import { ViewBuilder } from "../view.js";
5
+ import "../index.js";
6
+ //#region src/webhooks/webhook-resources.d.ts
7
+ /**
8
+ * The resources and views `webhooks()` adds to an app, over the tables and the view of `schema`: Webhook subscriptions,
9
+ * Webhook deliveries and, with `deliveryLog`, Webhook delivery log. Config only; the server delivers.
10
+ */
11
+ export declare const webhookResources: (schema: string, { deliveryLog }?: {
12
+ deliveryLog?: boolean;
13
+ }) => {
14
+ webhookDeliveryLog?: ResourceBuilder<{
15
+ readonly id: Field<string>;
16
+ readonly subscription_id: Field<string | number>;
17
+ readonly tenant_id: Field<string | null>;
18
+ readonly event_id: Field<string>;
19
+ readonly event_type: Field<string>;
20
+ readonly status: Field<"failed" | "delivered">;
21
+ readonly attempt: Field<number>;
22
+ readonly status_code: Field<number | null>;
23
+ readonly response: Field<string | null>;
24
+ readonly duration_ms: Field<number>;
25
+ readonly at: Field<string>;
26
+ }, Ref<"id", string>> | undefined;
27
+ webhookDeliveryLogView?: ViewBuilder<ResourceBuilder<{
28
+ readonly id: Field<string>;
29
+ readonly subscription_id: Field<string | number>;
30
+ readonly tenant_id: Field<string | null>;
31
+ readonly event_id: Field<string>;
32
+ readonly event_type: Field<string>;
33
+ readonly status: Field<"failed" | "delivered">;
34
+ readonly attempt: Field<number>;
35
+ readonly status_code: Field<number | null>;
36
+ readonly response: Field<string | null>;
37
+ readonly duration_ms: Field<number>;
38
+ readonly at: Field<string>;
39
+ }, Ref<"id", string>>> | undefined;
40
+ webhookSubscriptions: ResourceBuilder<{
41
+ readonly id: Field<string>;
42
+ readonly name: Field<string>;
43
+ readonly events: Field<string>;
44
+ readonly url: Field<string>;
45
+ readonly filter: Field<string | null>;
46
+ readonly headers: Field<import("zod").JSONType>;
47
+ readonly payload: Field<"full" | "thin">;
48
+ readonly enabled: Field<boolean>;
49
+ readonly secret: Field<string>;
50
+ readonly previous_secret: null;
51
+ readonly previous_secret_until: null;
52
+ readonly tenant_id: Field<string | null>;
53
+ readonly owner_id: Field<string | null>;
54
+ readonly disabled_reason: Field<string | null>;
55
+ readonly last_success_at: Field<string | null>;
56
+ readonly failing_since: Field<string | null>;
57
+ readonly created_at: Field<string>;
58
+ readonly updated_at: Field<string>;
59
+ readonly rotate_secret: Field<boolean>;
60
+ readonly send_test: Field<boolean>;
61
+ readonly resend_failed: Field<boolean>;
62
+ }, Ref<"id", string>>;
63
+ webhookSubscriptionsView: ViewBuilder<ResourceBuilder<{
64
+ readonly id: Field<string>;
65
+ readonly name: Field<string>;
66
+ readonly events: Field<string>;
67
+ readonly url: Field<string>;
68
+ readonly filter: Field<string | null>;
69
+ readonly headers: Field<import("zod").JSONType>;
70
+ readonly payload: Field<"full" | "thin">;
71
+ readonly enabled: Field<boolean>;
72
+ readonly secret: Field<string>;
73
+ readonly previous_secret: null;
74
+ readonly previous_secret_until: null;
75
+ readonly tenant_id: Field<string | null>;
76
+ readonly owner_id: Field<string | null>;
77
+ readonly disabled_reason: Field<string | null>;
78
+ readonly last_success_at: Field<string | null>;
79
+ readonly failing_since: Field<string | null>;
80
+ readonly created_at: Field<string>;
81
+ readonly updated_at: Field<string>;
82
+ readonly rotate_secret: Field<boolean>;
83
+ readonly send_test: Field<boolean>;
84
+ readonly resend_failed: Field<boolean>;
85
+ }, Ref<"id", string>>>;
86
+ webhookDeliveries: ResourceBuilder<{
87
+ readonly id: Field<string>;
88
+ readonly subscription_id: Field<string | number>;
89
+ readonly tenant_id: Field<string | null>;
90
+ readonly event_type: Field<string>;
91
+ readonly event_id: Field<string>;
92
+ readonly status: Field<"waiting" | "failed">;
93
+ readonly attempt: Field<number>;
94
+ readonly next_attempt: Field<string | null>;
95
+ readonly last_error: Field<string | null>;
96
+ readonly created_at: Field<string>;
97
+ readonly resend: Field<boolean>;
98
+ }, Ref<"id", string>>;
99
+ webhookDeliveriesView: ViewBuilder<ResourceBuilder<{
100
+ readonly id: Field<string>;
101
+ readonly subscription_id: Field<string | number>;
102
+ readonly tenant_id: Field<string | null>;
103
+ readonly event_type: Field<string>;
104
+ readonly event_id: Field<string>;
105
+ readonly status: Field<"waiting" | "failed">;
106
+ readonly attempt: Field<number>;
107
+ readonly next_attempt: Field<string | null>;
108
+ readonly last_error: Field<string | null>;
109
+ readonly created_at: Field<string>;
110
+ readonly resend: Field<boolean>;
111
+ }, Ref<"id", string>>>;
112
+ };
113
+ //#endregion
@@ -0,0 +1,211 @@
1
+ import { f } from "../fields.js";
2
+ import { resource } from "../resource.js";
3
+ import { layout } from "../layout.js";
4
+ import { view } from "../view.js";
5
+ //#region src/webhooks/webhook-resources.ts
6
+ /** Webhook subscriptions: a row per subscription someone made in the admin app, scoped to their tenant. */
7
+ const subscriptionsResource = (schema) => resource("webhook_subscriptions").table(`${schema}.subscriptions`).fields({
8
+ id: f.uuid().readOnly().dbDefault(),
9
+ name: f.text().min(1).max(100).filterable().sortable(),
10
+ events: f.text().min(1).max(2e3),
11
+ url: f.text().max(2e3).regex(/^https?:\/\/[^\s/]+/, "Use an http:// or https:// URL"),
12
+ filter: f.text().optional().max(2e3),
13
+ headers: f.json().optional(),
14
+ payload: f.enum(["full", "thin"]).default("full"),
15
+ enabled: f.boolean().default(true).filterable(),
16
+ secret: f.text().sensitive().readOnly().dbDefault(),
17
+ previous_secret: null,
18
+ previous_secret_until: null,
19
+ tenant_id: f.text().optional().readOnly(),
20
+ owner_id: f.text().optional().readOnly().dbDefault(),
21
+ disabled_reason: f.text().optional().readOnly(),
22
+ last_success_at: f.timestamp().optional().readOnly().sortable(),
23
+ failing_since: f.timestamp().optional().readOnly(),
24
+ created_at: f.timestamp().readOnly().dbDefault().sortable(),
25
+ updated_at: f.timestamp().readOnly().dbDefault(),
26
+ rotate_secret: f.boolean().default(false),
27
+ send_test: f.boolean().default(false),
28
+ resend_failed: f.boolean().default(false)
29
+ }).primaryKey((r) => r.id).tenant((r) => r.tenant_id).owner((r) => r.owner_id).search((r) => [r.name, r.url]);
30
+ const subscriptionsView = view("webhook_subscriptions").names({
31
+ singular: "Webhook subscription",
32
+ plural: "Webhook subscriptions"
33
+ }).icon("webhook").title((r) => r.name).help("Sends the app's events to a URL as they happen, signed with Standard Webhooks. It delivers as its owner: only the records and fields they may read.").fields((r) => ({
34
+ events: r.events.help("Event names separated by spaces, such as orders.created, or orders.* for every event of a resource"),
35
+ url: r.url.label("URL"),
36
+ filter: r.filter.help("Only records that match, in the language of filters: status = \"paid\""),
37
+ headers: r.headers.help("Extra request headers, as a JSON object"),
38
+ payload: r.payload.help("Thin leaves the records out: the receiver reads them through the API").valueLabels({
39
+ full: "Full",
40
+ thin: "Thin"
41
+ }),
42
+ secret: r.secret.help("Receivers check the webhook-signature header with it"),
43
+ disabled_reason: r.disabled_reason.label("Disabled because"),
44
+ last_success_at: r.last_success_at.label("Last success"),
45
+ failing_since: r.failing_since.label("Failing since")
46
+ })).list((r) => ({
47
+ columns: [
48
+ r.name,
49
+ r.events,
50
+ r.url,
51
+ r.enabled,
52
+ r.last_success_at
53
+ ],
54
+ sort: [[r.created_at, "desc"]]
55
+ })).layout((r) => [
56
+ layout.section("Subscription", [
57
+ r.name,
58
+ r.events,
59
+ r.url,
60
+ r.filter,
61
+ r.payload,
62
+ r.headers,
63
+ r.enabled
64
+ ]),
65
+ layout.section("Signing", [r.secret]),
66
+ layout.sidebar([
67
+ r.last_success_at,
68
+ r.failing_since,
69
+ r.disabled_reason,
70
+ r.created_at
71
+ ]),
72
+ layout.related("Waiting and failed deliveries", {
73
+ resource: "webhook_deliveries",
74
+ field: "subscription_id",
75
+ columns: [
76
+ "event_type",
77
+ "status",
78
+ "attempt",
79
+ "next_attempt",
80
+ "last_error"
81
+ ]
82
+ })
83
+ ]).actions((a) => [
84
+ a.update("send_test", {
85
+ label: "Send test event",
86
+ icon: "send",
87
+ set: { send_test: true }
88
+ }),
89
+ a.update("resend_failed", {
90
+ label: "Resend failed",
91
+ icon: "rotate-ccw",
92
+ set: { resend_failed: true },
93
+ confirm: "Try every failed delivery of this subscription once more?"
94
+ }),
95
+ a.update("rotate_secret", {
96
+ label: "Rotate secret",
97
+ icon: "key-round",
98
+ set: { rotate_secret: true },
99
+ confirm: "Make a new secret? The old one keeps signing too for 24 hours."
100
+ }),
101
+ a.update("disable", {
102
+ label: "Disable",
103
+ icon: "pause",
104
+ set: { enabled: false }
105
+ })
106
+ ]);
107
+ /** The deliveries of webhook subscriptions that wait for a retry or failed for good: delivery jobs, not a table. */
108
+ const deliveriesResource = (schema) => resource("webhook_deliveries").table(`${schema}.deliveries`).fields({
109
+ id: f.uuid().readOnly(),
110
+ subscription_id: f.relation("webhook_subscriptions").readOnly().filterable(),
111
+ tenant_id: f.text().optional().readOnly(),
112
+ event_type: f.text().readOnly().filterable().sortable(),
113
+ event_id: f.text().readOnly().filterable(),
114
+ status: f.enum(["waiting", "failed"]).readOnly().filterable(),
115
+ attempt: f.integer().readOnly(),
116
+ next_attempt: f.timestamp().optional().readOnly().sortable(),
117
+ last_error: f.text().optional().readOnly(),
118
+ created_at: f.timestamp().readOnly().sortable(),
119
+ resend: f.boolean()
120
+ }).primaryKey((r) => r.id).tenant((r) => r.tenant_id).access({
121
+ create: () => false,
122
+ delete: () => false
123
+ });
124
+ const deliveriesView = view("webhook_deliveries").names({
125
+ singular: "Webhook delivery",
126
+ plural: "Webhook deliveries"
127
+ }).icon("send").title((r) => r.event_type).help("Deliveries that wait for their next try or failed for good. A delivery leaves the list once it succeeds.").fields((r) => ({
128
+ event_type: r.event_type.label("Event"),
129
+ event_id: r.event_id.label("Event id").format("code"),
130
+ next_attempt: r.next_attempt.label("Next try"),
131
+ last_error: r.last_error.label("Last error"),
132
+ attempt: r.attempt.label("Tries")
133
+ })).list((r) => ({
134
+ columns: [
135
+ r.event_type,
136
+ r.subscription_id,
137
+ r.status,
138
+ r.attempt,
139
+ r.next_attempt,
140
+ r.last_error
141
+ ],
142
+ sort: [[r.created_at, "desc"]]
143
+ })).layout((r) => [layout.section("Delivery", [
144
+ r.subscription_id,
145
+ r.event_type,
146
+ r.event_id,
147
+ r.last_error
148
+ ]), layout.sidebar([
149
+ r.status,
150
+ r.attempt,
151
+ r.next_attempt,
152
+ r.created_at
153
+ ])]).actions((a) => [a.update("resend", {
154
+ label: "Resend",
155
+ icon: "rotate-ccw",
156
+ set: { resend: true },
157
+ confirm: "Try this delivery once more, from now?"
158
+ })]);
159
+ /** Every try of every webhook subscription's deliveries, for 30 days (`deliveryLog: true`). */
160
+ const deliveryLogResource = (schema) => resource("webhook_delivery_log").table(`${schema}.delivery_log`).fields({
161
+ id: f.bigint().readOnly(),
162
+ subscription_id: f.relation("webhook_subscriptions").readOnly().filterable(),
163
+ tenant_id: f.text().optional().readOnly(),
164
+ event_id: f.text().readOnly().filterable(),
165
+ event_type: f.text().readOnly().filterable().sortable(),
166
+ status: f.enum(["delivered", "failed"]).readOnly().filterable(),
167
+ attempt: f.integer().readOnly(),
168
+ status_code: f.integer().optional().readOnly().filterable(),
169
+ response: f.text().optional().readOnly(),
170
+ duration_ms: f.integer().readOnly(),
171
+ at: f.timestamp().readOnly().filterable().sortable()
172
+ }).primaryKey((r) => r.id).tenant((r) => r.tenant_id).access({
173
+ create: () => false,
174
+ update: () => false,
175
+ delete: () => false
176
+ });
177
+ const deliveryLogView = view("webhook_delivery_log").names({
178
+ singular: "Webhook delivery log entry",
179
+ plural: "Webhook delivery log"
180
+ }).icon("scroll-text").title((r) => r.event_type).fields((r) => ({
181
+ event_type: r.event_type.label("Event"),
182
+ status_code: r.status_code.label("Status code"),
183
+ duration_ms: r.duration_ms.label("Duration (ms)"),
184
+ at: r.at.label("When")
185
+ })).list((r) => ({
186
+ columns: [
187
+ r.at,
188
+ r.event_type,
189
+ r.subscription_id,
190
+ r.status,
191
+ r.status_code,
192
+ r.duration_ms
193
+ ],
194
+ sort: [[r.at, "desc"]]
195
+ }));
196
+ /**
197
+ * The resources and views `webhooks()` adds to an app, over the tables and the view of `schema`: Webhook subscriptions,
198
+ * Webhook deliveries and, with `deliveryLog`, Webhook delivery log. Config only; the server delivers.
199
+ */
200
+ const webhookResources = (schema, { deliveryLog = false } = {}) => ({
201
+ webhookSubscriptions: subscriptionsResource(schema),
202
+ webhookSubscriptionsView: subscriptionsView,
203
+ webhookDeliveries: deliveriesResource(schema),
204
+ webhookDeliveriesView: deliveriesView,
205
+ ...deliveryLog && {
206
+ webhookDeliveryLog: deliveryLogResource(schema),
207
+ webhookDeliveryLogView: deliveryLogView
208
+ }
209
+ });
210
+ //#endregion
211
+ export { webhookResources };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/schema",
3
- "version": "0.8.2",
3
+ "version": "0.10.0",
4
4
  "description": "Resource, field, view and access definitions for Protobase configs.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {