@celobus/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 +91 -0
- package/README.md +38 -2
- package/dist/access.d.ts +141 -0
- package/dist/access.js +232 -0
- package/dist/codec.d.ts +29 -0
- package/dist/codec.js +361 -0
- package/dist/cron.d.ts +2 -0
- package/dist/cron.js +113 -0
- package/dist/ctx.d.ts +644 -0
- package/dist/ctx.js +657 -0
- package/dist/db.d.ts +234 -0
- package/dist/db.js +495 -0
- package/dist/decimal.d.ts +39 -0
- package/dist/decimal.js +158 -0
- package/dist/declare.d.ts +311 -0
- package/dist/declare.js +78 -0
- package/dist/descriptor.d.ts +229 -0
- package/dist/descriptor.js +899 -0
- package/dist/errors.d.ts +65 -0
- package/dist/errors.js +114 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +34 -0
- package/dist/log.d.ts +39 -0
- package/dist/log.js +101 -0
- package/dist/names.d.ts +12 -0
- package/dist/names.js +41 -0
- package/dist/notify.d.ts +185 -0
- package/dist/notify.js +234 -0
- package/dist/platform.d.ts +61 -0
- package/dist/platform.js +47 -0
- package/dist/plugin.d.ts +43 -0
- package/dist/plugin.js +117 -0
- package/dist/query.d.ts +326 -0
- package/dist/query.js +794 -0
- package/dist/remote.d.ts +8 -0
- package/dist/remote.js +19 -0
- package/dist/schema.d.ts +487 -0
- package/dist/schema.js +405 -0
- package/dist/serve.d.ts +63 -0
- package/dist/serve.js +411 -0
- package/dist/sql.d.ts +13 -0
- package/dist/sql.js +33 -0
- package/dist/ui.d.ts +1867 -0
- package/dist/ui.js +3964 -0
- package/dist/viz-kinds.d.ts +12 -0
- package/dist/viz-kinds.js +14 -0
- package/package.json +33 -4
- package/proto/plugin.proto +994 -0
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { type AnyField } from "./schema.js";
|
|
2
|
+
export type ErrorDetails = Record<string, unknown>;
|
|
3
|
+
/** An error with a status, a stable code and details: what the caller receives. */
|
|
4
|
+
export declare class RpcError extends Error {
|
|
5
|
+
readonly status: number;
|
|
6
|
+
readonly code: string;
|
|
7
|
+
readonly details: ErrorDetails;
|
|
8
|
+
private marked;
|
|
9
|
+
constructor(status: number, code: string, message: string, details?: ErrorDetails, options?: {
|
|
10
|
+
cause?: unknown;
|
|
11
|
+
});
|
|
12
|
+
/** The same error, marked permanent: a job's run that fails with it is not retried. */
|
|
13
|
+
asPermanent(): this;
|
|
14
|
+
/**
|
|
15
|
+
* Whether a job's run that fails with this error is not retried: marked permanent, or an input-class error
|
|
16
|
+
* (`invalid`, `not_found`, `permission_denied`, `payload_invalid`).
|
|
17
|
+
*/
|
|
18
|
+
get permanent(): boolean;
|
|
19
|
+
/** The response body. */
|
|
20
|
+
toJSON(): {
|
|
21
|
+
code: string;
|
|
22
|
+
message: string;
|
|
23
|
+
details: ErrorDetails;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/** 400 `invalid`, with the offending fields in `details.fields` (`{ "<path>": "<message>" }`). */
|
|
27
|
+
export declare class InvalidError extends RpcError {
|
|
28
|
+
readonly fields: Record<string, string>;
|
|
29
|
+
constructor(message: string);
|
|
30
|
+
/** Names a field: a path (`lines[0].quantity`) or a message's field handle (`placeOrderRequest.fields.lines`). */
|
|
31
|
+
field(path: string | AnyField, message: string): this;
|
|
32
|
+
}
|
|
33
|
+
export declare function invalid(message?: string): InvalidError;
|
|
34
|
+
export declare function unauthenticated(message?: string): RpcError;
|
|
35
|
+
export declare function forbidden(message?: string, reason?: string): RpcError;
|
|
36
|
+
export declare function notFound(message?: string, field?: string): RpcError;
|
|
37
|
+
export declare function conflict(message?: string): RpcError;
|
|
38
|
+
/** 503 `unavailable`: a feature the platform does not offer, or an outside failure the plugin wraps. */
|
|
39
|
+
export declare function unavailable(cause?: unknown): RpcError;
|
|
40
|
+
/** 422 `permanent`: in a job, the attempt fails and the run is not retried (bad input that a retry cannot fix). */
|
|
41
|
+
export declare function permanent(message: string): RpcError;
|
|
42
|
+
/** @internal 500 `internal`; the message the caller sees is fixed. */
|
|
43
|
+
export declare function internal(cause?: unknown): RpcError;
|
|
44
|
+
declare const KINDS: {
|
|
45
|
+
readonly invalid: 400;
|
|
46
|
+
readonly forbidden: 403;
|
|
47
|
+
readonly not_found: 404;
|
|
48
|
+
readonly conflict: 409;
|
|
49
|
+
readonly unprocessable: 422;
|
|
50
|
+
};
|
|
51
|
+
export type DomainErrorKind = keyof typeof KINDS;
|
|
52
|
+
/** A domain error of the plugin: a code of its own and a status in 400–422. */
|
|
53
|
+
export declare class DomainError {
|
|
54
|
+
readonly code: string;
|
|
55
|
+
readonly description: string;
|
|
56
|
+
readonly status: number;
|
|
57
|
+
constructor(code: string, status: number | DomainErrorKind, description?: string);
|
|
58
|
+
/** The error to throw: `throw notCancellable.error(\`order ${n} is shipped\`)`. */
|
|
59
|
+
error(message?: string, details?: ErrorDetails): RpcError;
|
|
60
|
+
}
|
|
61
|
+
/** `domainError('not_cancellable', 409)` or `domainError('not_cancellable', 'conflict', 'The order is no longer placed.')`. */
|
|
62
|
+
export declare function domainError(code: string, status?: number | DomainErrorKind, description?: string): DomainError;
|
|
63
|
+
/** The body and status of any thrown value. */
|
|
64
|
+
export declare function toRpcError(e: unknown): RpcError;
|
|
65
|
+
export {};
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Runtime errors of a handler, mapped to an HTTP status and the platform error body
|
|
2
|
+
// `{ "code": "...", "message": "...", "details": {...} }`. Anything else a handler throws is 500 `internal`,
|
|
3
|
+
// with its message hidden from the caller and written to the log. In a job's handler an error fails the attempt, and
|
|
4
|
+
// the run is retried unless the error is permanent (`permanent(..)`, `.asPermanent()`, or an input-class code).
|
|
5
|
+
import { fieldKeys } from "./schema.js";
|
|
6
|
+
/** The codes of input-class errors: a job's attempt failing with one of them is not retried. */
|
|
7
|
+
const PERMANENT_CODES = new Set(["invalid", "not_found", "permission_denied", "payload_invalid"]);
|
|
8
|
+
/** An error with a status, a stable code and details: what the caller receives. */
|
|
9
|
+
export class RpcError extends Error {
|
|
10
|
+
status;
|
|
11
|
+
code;
|
|
12
|
+
details;
|
|
13
|
+
marked = false;
|
|
14
|
+
constructor(status, code, message, details = {}, options) {
|
|
15
|
+
super(message, options);
|
|
16
|
+
this.status = status;
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.details = details;
|
|
19
|
+
this.name = "RpcError";
|
|
20
|
+
}
|
|
21
|
+
/** The same error, marked permanent: a job's run that fails with it is not retried. */
|
|
22
|
+
asPermanent() {
|
|
23
|
+
this.marked = true;
|
|
24
|
+
return this;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Whether a job's run that fails with this error is not retried: marked permanent, or an input-class error
|
|
28
|
+
* (`invalid`, `not_found`, `permission_denied`, `payload_invalid`).
|
|
29
|
+
*/
|
|
30
|
+
get permanent() {
|
|
31
|
+
return this.marked || PERMANENT_CODES.has(this.code);
|
|
32
|
+
}
|
|
33
|
+
/** The response body. */
|
|
34
|
+
toJSON() {
|
|
35
|
+
return { code: this.code, message: this.message, details: this.details };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** 400 `invalid`, with the offending fields in `details.fields` (`{ "<path>": "<message>" }`). */
|
|
39
|
+
export class InvalidError extends RpcError {
|
|
40
|
+
fields = {};
|
|
41
|
+
constructor(message) {
|
|
42
|
+
super(400, "invalid", message);
|
|
43
|
+
this.details.fields = this.fields;
|
|
44
|
+
}
|
|
45
|
+
/** Names a field: a path (`lines[0].quantity`) or a message's field handle (`placeOrderRequest.fields.lines`). */
|
|
46
|
+
field(path, message) {
|
|
47
|
+
const key = typeof path === "string" ? path : fieldKeys.get(path);
|
|
48
|
+
if (key === undefined)
|
|
49
|
+
throw new TypeError("invalid(..).field: not a field of a message");
|
|
50
|
+
this.fields[key] = message;
|
|
51
|
+
return this;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export function invalid(message = "the request is invalid") {
|
|
55
|
+
return new InvalidError(message);
|
|
56
|
+
}
|
|
57
|
+
export function unauthenticated(message = "the request has no user") {
|
|
58
|
+
return new RpcError(401, "unauthenticated", message);
|
|
59
|
+
}
|
|
60
|
+
export function forbidden(message = "forbidden", reason) {
|
|
61
|
+
return new RpcError(403, "forbidden", message, reason ? { reason } : {});
|
|
62
|
+
}
|
|
63
|
+
export function notFound(message = "not found", field) {
|
|
64
|
+
return new RpcError(404, "not_found", message, field ? { field } : {});
|
|
65
|
+
}
|
|
66
|
+
export function conflict(message = "conflict") {
|
|
67
|
+
return new RpcError(409, "conflict", message);
|
|
68
|
+
}
|
|
69
|
+
/** 503 `unavailable`: a feature the platform does not offer, or an outside failure the plugin wraps. */
|
|
70
|
+
export function unavailable(cause) {
|
|
71
|
+
const message = cause === undefined ? "unavailable" : typeof cause === "string" ? cause : cause?.message ?? String(cause);
|
|
72
|
+
return new RpcError(503, "unavailable", message, {}, { cause });
|
|
73
|
+
}
|
|
74
|
+
/** 422 `permanent`: in a job, the attempt fails and the run is not retried (bad input that a retry cannot fix). */
|
|
75
|
+
export function permanent(message) {
|
|
76
|
+
return new RpcError(422, "permanent", message).asPermanent();
|
|
77
|
+
}
|
|
78
|
+
/** @internal 500 `internal`; the message the caller sees is fixed. */
|
|
79
|
+
export function internal(cause) {
|
|
80
|
+
return new RpcError(500, "internal", "internal error", {}, { cause });
|
|
81
|
+
}
|
|
82
|
+
const KINDS = { invalid: 400, forbidden: 403, not_found: 404, conflict: 409, unprocessable: 422 };
|
|
83
|
+
/** A domain error of the plugin: a code of its own and a status in 400–422. */
|
|
84
|
+
export class DomainError {
|
|
85
|
+
code;
|
|
86
|
+
description;
|
|
87
|
+
status;
|
|
88
|
+
constructor(code, status, description = "") {
|
|
89
|
+
this.code = code;
|
|
90
|
+
this.description = description;
|
|
91
|
+
this.status = typeof status === "number" ? status : KINDS[status];
|
|
92
|
+
if (!/^[a-z][a-z0-9_]*$/.test(code))
|
|
93
|
+
throw new TypeError(`domain error code ${JSON.stringify(code)}: use snake_case`);
|
|
94
|
+
if (!Number.isInteger(this.status) || this.status < 400 || this.status > 422) {
|
|
95
|
+
throw new TypeError(`domain error ${code}: status ${status} is not in 400–422`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** The error to throw: `throw notCancellable.error(\`order ${n} is shipped\`)`. */
|
|
99
|
+
error(message, details = {}) {
|
|
100
|
+
return new RpcError(this.status, this.code, message ?? (this.description || this.code), details);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** `domainError('not_cancellable', 409)` or `domainError('not_cancellable', 'conflict', 'The order is no longer placed.')`. */
|
|
104
|
+
export function domainError(code, status = 400, description = "") {
|
|
105
|
+
return new DomainError(code, status, description);
|
|
106
|
+
}
|
|
107
|
+
/** The body and status of any thrown value. */
|
|
108
|
+
export function toRpcError(e) {
|
|
109
|
+
if (e instanceof RpcError)
|
|
110
|
+
return e;
|
|
111
|
+
if (e instanceof DomainError)
|
|
112
|
+
return e.error();
|
|
113
|
+
return internal(e);
|
|
114
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { Decimal, type DecimalLike } from "./decimal.js";
|
|
2
|
+
export { EntityDef, EnumDef, Field, FieldRef, Filter, MessageDef, Order, and, not, or, PlatformEntity, ColCmp, entity, t, type AnyField, type EntityOptions, type ForeignEntityOptions, type FieldRefs, type Infer, type IoType, type Insert, type IoValue, type KeyType, type Patch, type RefTarget, type Row, type ScalarType, type Shape, type Stored, type ValueOf, type Included, type IncludedRow, type RefOptions, type OnDelete, type ColumnOf, type PlatformRow, type TargetOf, type UntypedRef, } from "./schema.js";
|
|
3
|
+
export { Delete, Find, ReadRepository, Repository, TxFind, TxRepository, Update, type AggregateQuery, type ColumnKey, type GetOptions, type GroupKey, type LockStrength, type LockWait, type Page, type SumOf, type TxGetOptions, } from "./db.js";
|
|
4
|
+
export type { SqlRow } from "./sql.js";
|
|
5
|
+
export { Agg, Alias, AliasCol, LabelItem, QCond, QOrder, Query, Selected, type CondLike, type ItemValue, type JoinRefOf, type Label, type Queryable, type QueryPage, type RowOf, type SelectItem, } from "./query.js";
|
|
6
|
+
export { AccessBuilder, Grant, Guard, Relation, RowsRel, WhenTest, type GrantLike, type Rel } from "./access.js";
|
|
7
|
+
export { EndpointDef, JobDef, RoleDef, endpoint, job, role, workspace, type AgentEngine, type AgentOptions, type AgentTimeout, type Auth, type BypassScope, type ConnectionOptions, type DefaultFor, type Dependency, type DependencyRead, type EndpointOptions, type Duration, type Idempotency, type JobOptions, type JobPayload, type JobPayloadType, type JobRetry, type PluginOptions, type RoleOptions, type ScopeOptions, type Timeout, } from "./declare.js";
|
|
8
|
+
export { DomainError, InvalidError, RpcError, conflict, domainError, forbidden, invalid, notFound, permanent, unauthenticated, unavailable, type DomainErrorKind, type ErrorDetails, } from "./errors.js";
|
|
9
|
+
export { Caller, Ctx, TxCtx, type AgentEvent, type AgentEvents, type AgentRun, type AgentRunOptions, type AgentRunStatus, type Agents, type AvailableAgent, type CallerKind, type Enqueued, type EnqueueOptions, type JobInfo, type Jobs, type RunState, type Group, type Member, type PluginInfo, type RequestInfo, type RunChange, type RunChangeHandler, type TransactionOptions, type RoleLike, } from "./ctx.js";
|
|
10
|
+
export { NotificationKind, Notifications, NotifyButton, NotifyKey, NotifyLink, notification, notify, type Ask, type Follow, type FollowReason, type Notice, type NotificationOptions, type NotificationTab, type NotifySource, } from "./notify.js";
|
|
11
|
+
export { DescribeErrors, formatError, type DescribeError, type Descriptor } from "./descriptor.js";
|
|
12
|
+
export { type LogFields, type Logger, type LogLevel } from "./log.js";
|
|
13
|
+
export { Plugin, plugin } from "./plugin.js";
|
|
14
|
+
export { ActionRef, AgentRunB, ConversationB, ChatB, Chain, ChartB, BoardB, CommandB, Cond, ConfirmB, EntryB, FollowKey, FormB, FormVals, HomeB, InputB, Invalidation, ItemB, ListB, MenuItemB, N, NavB, Node, OverlayDef, OverlayKey, ParamRef, Q, QueryDef, RecordHeaderB, RowForm, RowRef, RowViewB, ScreenBuilder, ScreenDef, ScreenKey, SearchB, StateRef, TabB, TableB, TextKey, TimelineB, TopicDecl, TopicDef, UiDoc, Val, VizB, WidgetBuilder, CardB, ComposerB, HeaderB, HeaderTabB, MentionsB, PathOf, PickB, PostB, PostEntryB, ProcessB, SegB, StreamB, StripB, StripButtonB, Via, topic, ui, type ArgsOf, type ComposerTool, type Elem, type RowPathLike, type FollowLike, type Gap, type InvalidationLike, type NoticeTone, type OverlayKind, type ScreenBuild, type Size, type Tone, type Tones, type TopicLike, type Txt, type UiOptions, type ValueLike, type VizAs, type VizCatalogue, type VizFamily, type VizKind, type VizSource, } from "./ui.js";
|
|
15
|
+
export { VIZ_KINDS } from "./viz-kinds.js";
|
|
16
|
+
export { remote, type Remote } from "./remote.js";
|
|
17
|
+
export { type ServeOptions } from "./serve.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// @celobus/sdk: the celobus plugin SDK for Node.js (TypeScript).
|
|
2
|
+
//
|
|
3
|
+
// import { endpoint, plugin, role, t } from '@celobus/sdk';
|
|
4
|
+
// const clerk = role({ title: 'Order clerk' });
|
|
5
|
+
// export default plugin({
|
|
6
|
+
// id: 'hello', title: 'Hello', roles: { clerk },
|
|
7
|
+
// endpoints: {
|
|
8
|
+
// hello: endpoint({
|
|
9
|
+
// input: t.message('HelloRequest', { name: t.text() }),
|
|
10
|
+
// output: t.message('HelloReply', { text: t.text() }),
|
|
11
|
+
// roles: [clerk],
|
|
12
|
+
// async handler(ctx, { name }) { return { text: `Hello, ${name}!` }; },
|
|
13
|
+
// }),
|
|
14
|
+
// },
|
|
15
|
+
// });
|
|
16
|
+
// // src/main.ts: import plugin from './index.js'; await plugin.serve();
|
|
17
|
+
//
|
|
18
|
+
// A background job: `export const remindUnpaid = job({ payload: { olderThanDays: t.int() }, cron: '0 9 * * 1-5',
|
|
19
|
+
// async handler(ctx, p) { .. } })`, listed in `plugin({ jobs: { remindUnpaid } })`, started with
|
|
20
|
+
// `ctx.jobs.enqueue(remindUnpaid, { olderThanDays: 7 })`.
|
|
21
|
+
export { Decimal } from "./decimal.js";
|
|
22
|
+
export { EntityDef, EnumDef, Field, FieldRef, Filter, MessageDef, Order, and, not, or, PlatformEntity, ColCmp, entity, t, } from "./schema.js";
|
|
23
|
+
export { Delete, Find, ReadRepository, Repository, TxFind, TxRepository, Update, } from "./db.js";
|
|
24
|
+
export { Agg, Alias, AliasCol, LabelItem, QCond, QOrder, Query, Selected, } from "./query.js";
|
|
25
|
+
export { AccessBuilder, Grant, Guard, Relation, RowsRel, WhenTest } from "./access.js";
|
|
26
|
+
export { EndpointDef, JobDef, RoleDef, endpoint, job, role, workspace, } from "./declare.js";
|
|
27
|
+
export { DomainError, InvalidError, RpcError, conflict, domainError, forbidden, invalid, notFound, permanent, unauthenticated, unavailable, } from "./errors.js";
|
|
28
|
+
export { Caller, Ctx, TxCtx, } from "./ctx.js";
|
|
29
|
+
export { NotificationKind, Notifications, NotifyButton, NotifyKey, NotifyLink, notification, notify, } from "./notify.js";
|
|
30
|
+
export { DescribeErrors, formatError } from "./descriptor.js";
|
|
31
|
+
export { Plugin, plugin } from "./plugin.js";
|
|
32
|
+
export { ActionRef, AgentRunB, ConversationB, ChatB, Chain, ChartB, BoardB, CommandB, Cond, ConfirmB, EntryB, FollowKey, FormB, FormVals, HomeB, InputB, Invalidation, ItemB, ListB, MenuItemB, N, NavB, Node, OverlayDef, OverlayKey, ParamRef, Q, QueryDef, RecordHeaderB, RowForm, RowRef, RowViewB, ScreenBuilder, ScreenDef, ScreenKey, SearchB, StateRef, TabB, TableB, TextKey, TimelineB, TopicDecl, TopicDef, UiDoc, Val, VizB, WidgetBuilder, CardB, ComposerB, HeaderB, HeaderTabB, MentionsB, PathOf, PickB, PostB, PostEntryB, ProcessB, SegB, StreamB, StripB, StripButtonB, Via, topic, ui, } from "./ui.js";
|
|
33
|
+
export { VIZ_KINDS } from "./viz-kinds.js";
|
|
34
|
+
export { remote } from "./remote.js";
|
package/dist/log.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export type LogLevel = "debug" | "info" | "warn" | "error";
|
|
2
|
+
export type LogFields = Record<string, unknown>;
|
|
3
|
+
export interface Logger {
|
|
4
|
+
debug(message: string, fields?: LogFields): void;
|
|
5
|
+
info(message: string, fields?: LogFields): void;
|
|
6
|
+
warn(message: string, fields?: LogFields): void;
|
|
7
|
+
error(message: string, fields?: LogFields): void;
|
|
8
|
+
/** A logger that adds these fields to every line. */
|
|
9
|
+
with(fields: LogFields): Logger;
|
|
10
|
+
}
|
|
11
|
+
/** @internal Where log lines go; tests replace it. */
|
|
12
|
+
export declare const sink: {
|
|
13
|
+
write: (line: string) => undefined;
|
|
14
|
+
};
|
|
15
|
+
export declare function createLogger(base?: LogFields): Logger;
|
|
16
|
+
/** The longest run log line, in UTF-8 bytes. */
|
|
17
|
+
export declare const MAX_LINE = 2048;
|
|
18
|
+
/** Run log lines and bytes a process sends a second. */
|
|
19
|
+
export declare const LINES_PER_SECOND = 1000;
|
|
20
|
+
export declare const BYTES_PER_SECOND: number;
|
|
21
|
+
/** @internal At most `max` UTF-8 bytes of `s`, cut at a character boundary. */
|
|
22
|
+
export declare function cutUtf8(s: string, max: number): string;
|
|
23
|
+
/** @internal A fixed one-second window of lines and bytes. */
|
|
24
|
+
export declare class Limiter {
|
|
25
|
+
private window;
|
|
26
|
+
private lines;
|
|
27
|
+
private bytes;
|
|
28
|
+
/** Whether a line of `bytes` may go at `now` (ms). */
|
|
29
|
+
admit(now: number, bytes: number): boolean;
|
|
30
|
+
}
|
|
31
|
+
/** @internal The process's run log limit. */
|
|
32
|
+
export declare const runLogLimit: Limiter;
|
|
33
|
+
/** @internal A run log line: the message, then the fields as `key=value`, cut at 2 KiB. */
|
|
34
|
+
export declare function runLine(message: string, fields?: LogFields): string;
|
|
35
|
+
/**
|
|
36
|
+
* @internal A run's logger: every line goes to `inner` (stderr) and, within the process's limit, to `send` as a run log
|
|
37
|
+
* line with the fields of the call and of `.with(..)` made on it (not the fields `inner` adds).
|
|
38
|
+
*/
|
|
39
|
+
export declare function runLogger(inner: Logger, send: (level: LogLevel, message: string) => void, fields?: LogFields): Logger;
|
package/dist/log.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Structured logs: one JSON object per line on stderr. What a job's handler logs with `ctx.log` while it runs is also
|
|
2
|
+
// kept with the run, by attempt, and shown with it (the run log): its message, then its fields as `key=value`. Lines
|
|
3
|
+
// are cut at 2 KiB; a process sends at most 1,000 lines and 1 MiB a second, and drops the rest. Lines logged while
|
|
4
|
+
// handling a request are not kept this way.
|
|
5
|
+
function plain(value) {
|
|
6
|
+
if (typeof value === "bigint")
|
|
7
|
+
return value.toString();
|
|
8
|
+
if (value instanceof Error)
|
|
9
|
+
return { name: value.name, message: value.message, stack: value.stack };
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
/** @internal Where log lines go; tests replace it. */
|
|
13
|
+
export const sink = { write: (line) => void process.stderr.write(line) };
|
|
14
|
+
export function createLogger(base = {}) {
|
|
15
|
+
const write = (level, msg, fields) => {
|
|
16
|
+
const line = { ts: new Date().toISOString(), level, msg, ...base, ...fields };
|
|
17
|
+
sink.write(JSON.stringify(line, (_k, v) => plain(v)) + "\n");
|
|
18
|
+
};
|
|
19
|
+
return {
|
|
20
|
+
debug: (m, f) => write("debug", m, f),
|
|
21
|
+
info: (m, f) => write("info", m, f),
|
|
22
|
+
warn: (m, f) => write("warn", m, f),
|
|
23
|
+
error: (m, f) => write("error", m, f),
|
|
24
|
+
with: (fields) => createLogger({ ...base, ...fields }),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** The longest run log line, in UTF-8 bytes. */
|
|
28
|
+
export const MAX_LINE = 2048;
|
|
29
|
+
/** Run log lines and bytes a process sends a second. */
|
|
30
|
+
export const LINES_PER_SECOND = 1_000;
|
|
31
|
+
export const BYTES_PER_SECOND = 1 << 20;
|
|
32
|
+
/** @internal At most `max` UTF-8 bytes of `s`, cut at a character boundary. */
|
|
33
|
+
export function cutUtf8(s, max) {
|
|
34
|
+
const bytes = Buffer.from(s, "utf8");
|
|
35
|
+
if (bytes.length <= max)
|
|
36
|
+
return s;
|
|
37
|
+
let end = max;
|
|
38
|
+
while (end > 0 && (bytes[end] & 0xc0) === 0x80)
|
|
39
|
+
end--;
|
|
40
|
+
return bytes.subarray(0, end).toString("utf8");
|
|
41
|
+
}
|
|
42
|
+
/** @internal A fixed one-second window of lines and bytes. */
|
|
43
|
+
export class Limiter {
|
|
44
|
+
window;
|
|
45
|
+
lines = 0;
|
|
46
|
+
bytes = 0;
|
|
47
|
+
/** Whether a line of `bytes` may go at `now` (ms). */
|
|
48
|
+
admit(now, bytes) {
|
|
49
|
+
if (this.window === undefined || now - this.window >= 1000 || now < this.window) {
|
|
50
|
+
this.window = now;
|
|
51
|
+
this.lines = 0;
|
|
52
|
+
this.bytes = 0;
|
|
53
|
+
}
|
|
54
|
+
if (this.lines >= LINES_PER_SECOND || this.bytes + bytes > BYTES_PER_SECOND)
|
|
55
|
+
return false;
|
|
56
|
+
this.lines += 1;
|
|
57
|
+
this.bytes += bytes;
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** @internal The process's run log limit. */
|
|
62
|
+
export const runLogLimit = new Limiter();
|
|
63
|
+
function fieldValue(v) {
|
|
64
|
+
if (typeof v === "string")
|
|
65
|
+
return JSON.stringify(v);
|
|
66
|
+
if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" || v === undefined)
|
|
67
|
+
return String(v);
|
|
68
|
+
if (v instanceof Error)
|
|
69
|
+
return JSON.stringify(v.message);
|
|
70
|
+
try {
|
|
71
|
+
return JSON.stringify(v, (_k, x) => (typeof x === "bigint" ? x.toString() : x)) ?? String(v);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return String(v);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** @internal A run log line: the message, then the fields as `key=value`, cut at 2 KiB. */
|
|
78
|
+
export function runLine(message, fields = {}) {
|
|
79
|
+
const parts = Object.entries(fields).map(([k, v]) => `${k}=${fieldValue(v)}`);
|
|
80
|
+
const out = parts.length === 0 ? message : message ? `${message} ${parts.join(" ")}` : parts.join(" ");
|
|
81
|
+
return cutUtf8(out, MAX_LINE);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* @internal A run's logger: every line goes to `inner` (stderr) and, within the process's limit, to `send` as a run log
|
|
85
|
+
* line with the fields of the call and of `.with(..)` made on it (not the fields `inner` adds).
|
|
86
|
+
*/
|
|
87
|
+
export function runLogger(inner, send, fields = {}) {
|
|
88
|
+
const write = (level) => (msg, f) => {
|
|
89
|
+
inner[level](msg, f);
|
|
90
|
+
const line = runLine(msg, { ...fields, ...f });
|
|
91
|
+
if (runLogLimit.admit(Date.now(), Buffer.byteLength(line, "utf8")))
|
|
92
|
+
send(level, line);
|
|
93
|
+
};
|
|
94
|
+
return {
|
|
95
|
+
debug: write("debug"),
|
|
96
|
+
info: write("info"),
|
|
97
|
+
warn: write("warn"),
|
|
98
|
+
error: write("error"),
|
|
99
|
+
with: (extra) => runLogger(inner.with(extra), send, { ...fields, ...extra }),
|
|
100
|
+
};
|
|
101
|
+
}
|
package/dist/names.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** `ownerId` → `owner_id`. */
|
|
2
|
+
export declare function snake(key: string): string;
|
|
3
|
+
/** The protobuf JSON name of a field: `owner_id` → `ownerId`. */
|
|
4
|
+
export declare function jsonName(name: string): string;
|
|
5
|
+
/** `getNote` (or `get_note`) → `GetNote`. */
|
|
6
|
+
export declare function pascal(key: string): string;
|
|
7
|
+
/** `hello` → `Hello`: the default title of a plugin. */
|
|
8
|
+
export declare function humanize(id: string): string;
|
|
9
|
+
/** The service of a plugin: its id in PascalCase (`orders` → `Orders`). */
|
|
10
|
+
export declare function serviceName(pluginId: string): string;
|
|
11
|
+
/** The request path of an endpoint: `/<id>.v1.<Service>/<Name>`. */
|
|
12
|
+
export declare function endpointPath(pluginId: string, endpoint: string): string;
|
package/dist/names.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Name conversions between TypeScript keys and descriptor names.
|
|
2
|
+
//
|
|
3
|
+
// TypeScript declares fields, roles, scopes and entities with camelCase keys; the descriptor names them in
|
|
4
|
+
// snake_case. The wire uses the protobuf JSON name of a field (lowerCamelCase), which for a well-formed key is
|
|
5
|
+
// the key itself.
|
|
6
|
+
/** `ownerId` → `owner_id`. */
|
|
7
|
+
export function snake(key) {
|
|
8
|
+
return key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
|
|
9
|
+
}
|
|
10
|
+
/** The protobuf JSON name of a field: `owner_id` → `ownerId`. */
|
|
11
|
+
export function jsonName(name) {
|
|
12
|
+
let out = "";
|
|
13
|
+
let upper = false;
|
|
14
|
+
for (const c of name) {
|
|
15
|
+
if (c === "_") {
|
|
16
|
+
upper = true;
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
out += upper ? c.toUpperCase() : c;
|
|
20
|
+
upper = false;
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
/** `getNote` (or `get_note`) → `GetNote`. */
|
|
25
|
+
export function pascal(key) {
|
|
26
|
+
const camel = jsonName(key);
|
|
27
|
+
return camel.charAt(0).toUpperCase() + camel.slice(1);
|
|
28
|
+
}
|
|
29
|
+
/** `hello` → `Hello`: the default title of a plugin. */
|
|
30
|
+
export function humanize(id) {
|
|
31
|
+
const words = snake(id).split("_").filter(Boolean).join(" ");
|
|
32
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
33
|
+
}
|
|
34
|
+
/** The service of a plugin: its id in PascalCase (`orders` → `Orders`). */
|
|
35
|
+
export function serviceName(pluginId) {
|
|
36
|
+
return pascal(pluginId);
|
|
37
|
+
}
|
|
38
|
+
/** The request path of an endpoint: `/<id>.v1.<Service>/<Name>`. */
|
|
39
|
+
export function endpointPath(pluginId, endpoint) {
|
|
40
|
+
return `/${pluginId}.v1.${serviceName(pluginId)}/${endpoint}`;
|
|
41
|
+
}
|
package/dist/notify.d.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { type EndpointDef } from "./declare.js";
|
|
2
|
+
import { type EntityDef, type IoType, type IoValue } from "./schema.js";
|
|
3
|
+
import type { OverlayKey, ScreenKey } from "./ui.js";
|
|
4
|
+
/** The inbox tab a kind arrives in: addressed to the member, or about something they follow. */
|
|
5
|
+
export type NotificationTab = "for_you" | "watching";
|
|
6
|
+
export interface NotificationOptions {
|
|
7
|
+
/** The settings row's title ("Mentions"), 1 to 40 characters. */
|
|
8
|
+
title: string;
|
|
9
|
+
/** The settings row's second line, at most 120 characters. */
|
|
10
|
+
description?: string;
|
|
11
|
+
/** Default `for_you`; `watching`: about something the member follows (a reply in a thread). */
|
|
12
|
+
tab?: NotificationTab;
|
|
13
|
+
/** The daily digest includes it unless the member turns that off (default: not). */
|
|
14
|
+
digest?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A kind of notification the plugin declares (`plugin({ notifications: [mention] })`): what a member turns on or off
|
|
18
|
+
* in their settings. Its name is snake_case, at most 32 characters.
|
|
19
|
+
*/
|
|
20
|
+
export declare class NotificationKind {
|
|
21
|
+
readonly name: string;
|
|
22
|
+
readonly options: NotificationOptions;
|
|
23
|
+
constructor(name: string, options: NotificationOptions);
|
|
24
|
+
}
|
|
25
|
+
/** `export const mention = notification('mention', { title: 'Mentions', digest: true })`. */
|
|
26
|
+
export declare function notification(name: string, options: NotificationOptions): NotificationKind;
|
|
27
|
+
/**
|
|
28
|
+
* What a notification is about: the plugin's name for it (`post:0193…`, at most 200 bytes), optionally one of its
|
|
29
|
+
* entity rows (the subject, `<entity>/<id>`). Unread notifications of one kind and key group into one row
|
|
30
|
+
* ("3 replies"); members follow keys; an ask's key is its identity. A member who can no longer read the subject no
|
|
31
|
+
* longer sees it.
|
|
32
|
+
*/
|
|
33
|
+
export declare class NotifyKey {
|
|
34
|
+
readonly key: string;
|
|
35
|
+
readonly subject: string;
|
|
36
|
+
constructor(key: string, subject?: string);
|
|
37
|
+
/** The same key tied to one of the plugin's entity rows. */
|
|
38
|
+
withSubject<E extends EntityDef<any>>(entity: E, id: string | bigint): NotifyKey;
|
|
39
|
+
toString(): string;
|
|
40
|
+
}
|
|
41
|
+
/** Where a notification opens: one of the plugin's screens or document-level overlays, with its params. */
|
|
42
|
+
export declare class NotifyLink {
|
|
43
|
+
readonly screen: string;
|
|
44
|
+
readonly overlay: string;
|
|
45
|
+
readonly args: Record<string, unknown>;
|
|
46
|
+
/** @internal */
|
|
47
|
+
constructor(screen: string, overlay: string, args: Record<string, unknown>);
|
|
48
|
+
}
|
|
49
|
+
/** Where a notification happened: a label ("#fulfilment") and an icon of the kit ("hash"). */
|
|
50
|
+
export interface NotifySource {
|
|
51
|
+
label: string;
|
|
52
|
+
icon: string;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* A button of an ask: it calls one of the plugin's `ui` endpoints with this request, as the member who presses it.
|
|
56
|
+
* The endpoint checks the member and resolves the ask. Made with `notify.button(..)`.
|
|
57
|
+
*/
|
|
58
|
+
export declare class NotifyButton {
|
|
59
|
+
readonly label: string;
|
|
60
|
+
readonly endpoint: EndpointDef<any, any>;
|
|
61
|
+
readonly request: unknown;
|
|
62
|
+
readonly primary: boolean;
|
|
63
|
+
readonly icon: string;
|
|
64
|
+
/** @internal */
|
|
65
|
+
constructor(label: string, endpoint: EndpointDef<any, any>, request: unknown, primary: boolean, icon: string);
|
|
66
|
+
}
|
|
67
|
+
/** The actor a notification shows: the caller (default), one of the plugin's agents, or nobody (the plugin's mark). */
|
|
68
|
+
interface Actor {
|
|
69
|
+
/** Shown as one of the plugin's agents, by name, instead of the caller. */
|
|
70
|
+
agent?: string;
|
|
71
|
+
/** Shown as the plugin itself, without an actor. */
|
|
72
|
+
noActor?: boolean;
|
|
73
|
+
}
|
|
74
|
+
/** A notification of one of the plugin's kinds: to members (`to`), to the followers of a key (`followers`), or both. */
|
|
75
|
+
export interface Notice extends Actor {
|
|
76
|
+
/** User ids, at most 100. */
|
|
77
|
+
to?: readonly string[];
|
|
78
|
+
/** Also to the active followers of this key (its key too, unless `key` names another). */
|
|
79
|
+
followers?: NotifyKey;
|
|
80
|
+
/** Not to these members (those already told in this request). */
|
|
81
|
+
except?: readonly string[];
|
|
82
|
+
/** What it is about: unread notifications of its kind and key group into one row. */
|
|
83
|
+
key?: NotifyKey;
|
|
84
|
+
/** The phrase after the actor ("mentioned you in #fulfilment"), at most 140 characters. */
|
|
85
|
+
title?: string;
|
|
86
|
+
/** A snippet, at most 500 characters of plain text. */
|
|
87
|
+
body?: string;
|
|
88
|
+
source?: NotifySource;
|
|
89
|
+
link?: NotifyLink;
|
|
90
|
+
/** A member gets at most one notification of the plugin with this value (at most 120 bytes); never grouped. */
|
|
91
|
+
once?: string;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* An approval or a decision a member answers in their inbox (NEEDS YOU): 1 to 3 buttons that call the plugin's own
|
|
95
|
+
* endpoints, and a review link. It stays until it is resolved (`resolve`) or the member marks it done; asking again
|
|
96
|
+
* refreshes the open one of its key.
|
|
97
|
+
*/
|
|
98
|
+
export interface Ask extends Actor {
|
|
99
|
+
kind: "approval" | "decision";
|
|
100
|
+
/** Its identity. */
|
|
101
|
+
key: NotifyKey;
|
|
102
|
+
/** User ids, at most 100. */
|
|
103
|
+
to: readonly string[];
|
|
104
|
+
title?: string;
|
|
105
|
+
body?: string;
|
|
106
|
+
source?: NotifySource;
|
|
107
|
+
/** What the review link opens. */
|
|
108
|
+
link?: NotifyLink;
|
|
109
|
+
/** The review link's label ("Review 5 changes"). */
|
|
110
|
+
review?: string;
|
|
111
|
+
buttons: readonly NotifyButton[];
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* How members come to follow a key. `manual` (default): the member asked to (a Follow button), and it resumes a follow
|
|
115
|
+
* they stopped; `replied` / `edited`: only members whose setting ("follow threads I reply in", "follow records I
|
|
116
|
+
* edit") is on and who never stopped following the key.
|
|
117
|
+
*/
|
|
118
|
+
export type FollowReason = "manual" | "replied" | "edited";
|
|
119
|
+
export interface Follow {
|
|
120
|
+
reason?: FollowReason;
|
|
121
|
+
/** What the inbox calls the key ("thread": "Stop following this thread"), at most 24 characters. */
|
|
122
|
+
noun?: string;
|
|
123
|
+
/** These members (user ids, at most 100) instead of the caller: with `replied` or `edited` only (a manual follow is
|
|
124
|
+
* the caller's own; naming anyone else is `invalid`). */
|
|
125
|
+
users?: readonly string[];
|
|
126
|
+
}
|
|
127
|
+
/** Keys, links and buttons of notifications. */
|
|
128
|
+
export declare const notify: {
|
|
129
|
+
/** A key of the plugin's own (no subject). */
|
|
130
|
+
key(key: string): NotifyKey;
|
|
131
|
+
/** The key of one of the plugin's entity rows, `<entity>:<id>`, with the row as its subject. */
|
|
132
|
+
row<E extends EntityDef<any>>(entity: E, id: string | bigint): NotifyKey;
|
|
133
|
+
/** Opens one of the plugin's screens with these params. */
|
|
134
|
+
screen<P>(screen: ScreenKey<P>, params: P): NotifyLink;
|
|
135
|
+
/** Opens one of the plugin's document-level overlays (a side panel, shown beside the inbox's list). */
|
|
136
|
+
overlay<P>(overlay: OverlayKey<P>, params: P): NotifyLink;
|
|
137
|
+
/** A button of an ask that calls `endpoint` (a `ui` endpoint of the plugin) with `request`. */
|
|
138
|
+
button<I extends IoType>(label: string, endpoint: EndpointDef<I, any>, request: IoValue<I>, options?: {
|
|
139
|
+
primary?: boolean;
|
|
140
|
+
icon?: string;
|
|
141
|
+
}): NotifyButton;
|
|
142
|
+
};
|
|
143
|
+
/** @internal What a `Notifications` sends its syscalls through. */
|
|
144
|
+
export interface NotifyLinkage {
|
|
145
|
+
syscall(call: Record<string, unknown>): Promise<{
|
|
146
|
+
notifyFollowState?: {
|
|
147
|
+
following: boolean;
|
|
148
|
+
} | null;
|
|
149
|
+
}>;
|
|
150
|
+
requestId: string;
|
|
151
|
+
tx: string;
|
|
152
|
+
}
|
|
153
|
+
/** @internal A link as the wire carries it (a notification's, an agent run's `notifyLink`). */
|
|
154
|
+
export declare function linkWire(l: NotifyLink | undefined): Record<string, unknown> | undefined;
|
|
155
|
+
/**
|
|
156
|
+
* The plugin's notifications (`ctx.notifications`; `tx.notifications` writes in the transaction, and its members hear
|
|
157
|
+
* of it when it commits). A notification never undoes the transaction: a call the database or a limit refuses in it
|
|
158
|
+
* is let go (logged) and resolves normally. Send late in a transaction: a send holds the unread groups it grew until
|
|
159
|
+
* the commit. Needs the capability `push:send` (403 `capability_missing`); a send the platform refuses is 400
|
|
160
|
+
* `invalid`; sends over 50 a second are let go; a manual follow of a key with 2,000 followers, outside a
|
|
161
|
+
* transaction, is 409 `follow_limit`. A send answers nothing about who received it.
|
|
162
|
+
*/
|
|
163
|
+
export declare class Notifications {
|
|
164
|
+
private readonly link;
|
|
165
|
+
/** @internal */
|
|
166
|
+
constructor(link: NotifyLinkage);
|
|
167
|
+
private sendWire;
|
|
168
|
+
/** Sends a notification of one of the plugin's kinds. */
|
|
169
|
+
send(kind: NotificationKind, notice: Notice): Promise<void>;
|
|
170
|
+
/** Asks members for an approval or a decision. */
|
|
171
|
+
ask(ask: Ask): Promise<void>;
|
|
172
|
+
/**
|
|
173
|
+
* Resolves every open ask of `key`, for every member it asked: `outcome` ("Approved by Sarah Bennett", at most 80
|
|
174
|
+
* characters) is what the inbox shows.
|
|
175
|
+
*/
|
|
176
|
+
resolve(key: NotifyKey, outcome: string): Promise<void>;
|
|
177
|
+
private followWire;
|
|
178
|
+
/** Makes the caller (or, for `replied` and `edited`, `follow.users`) follow `key`. */
|
|
179
|
+
follow(key: NotifyKey, follow?: Follow): Promise<void>;
|
|
180
|
+
/** The caller stops following `key`; an automatic follow does not resume it. */
|
|
181
|
+
unfollow(key: NotifyKey): Promise<void>;
|
|
182
|
+
/** Whether the caller follows `key` (for a "Following" button): the one thing a plugin may read of notifications. */
|
|
183
|
+
following(key: NotifyKey): Promise<boolean>;
|
|
184
|
+
}
|
|
185
|
+
export {};
|