@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.
Files changed (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -2
  3. package/dist/account.d.ts +124 -0
  4. package/dist/account.js +344 -0
  5. package/dist/action.d.ts +43 -0
  6. package/dist/action.js +135 -0
  7. package/dist/admin.d.ts +99 -0
  8. package/dist/admin.js +431 -0
  9. package/dist/api.d.ts +21 -0
  10. package/dist/api.js +72 -0
  11. package/dist/app.d.ts +202 -0
  12. package/dist/app.js +3692 -0
  13. package/dist/assets.d.ts +4 -0
  14. package/dist/assets.js +91 -0
  15. package/dist/auth.d.ts +150 -0
  16. package/dist/auth.js +215 -0
  17. package/dist/backup.d.ts +46 -0
  18. package/dist/backup.js +345 -0
  19. package/dist/build.d.ts +33 -0
  20. package/dist/build.js +274 -0
  21. package/dist/bun.d.ts +30 -0
  22. package/dist/bun.js +53 -0
  23. package/dist/calendar.d.ts +161 -0
  24. package/dist/calendar.js +690 -0
  25. package/dist/compiler.d.ts +13 -0
  26. package/dist/compiler.js +58 -0
  27. package/dist/compress.d.ts +6 -0
  28. package/dist/compress.js +78 -0
  29. package/dist/config.d.ts +26 -0
  30. package/dist/config.js +317 -0
  31. package/dist/context.d.ts +9 -0
  32. package/dist/context.js +1 -0
  33. package/dist/contract.d.ts +18 -0
  34. package/dist/contract.js +171 -0
  35. package/dist/datamap.d.ts +24 -0
  36. package/dist/datamap.js +365 -0
  37. package/dist/db-backup.d.ts +27 -0
  38. package/dist/db-backup.js +115 -0
  39. package/dist/dev-events.d.ts +14 -0
  40. package/dist/dev-events.js +135 -0
  41. package/dist/dev.d.ts +1 -0
  42. package/dist/dev.js +240 -0
  43. package/dist/devtools-client.d.ts +1 -0
  44. package/dist/devtools-client.js +362 -0
  45. package/dist/devtools.d.ts +87 -0
  46. package/dist/devtools.js +68 -0
  47. package/dist/edge.d.ts +3 -0
  48. package/dist/edge.js +7 -0
  49. package/dist/email-signin.d.ts +92 -0
  50. package/dist/email-signin.js +259 -0
  51. package/dist/env.d.ts +1 -0
  52. package/dist/env.js +15 -0
  53. package/dist/explain.d.ts +12 -0
  54. package/dist/explain.js +217 -0
  55. package/dist/files.d.ts +6 -0
  56. package/dist/files.js +170 -0
  57. package/dist/grants.d.ts +69 -0
  58. package/dist/grants.js +206 -0
  59. package/dist/image/bitmap.d.ts +11 -0
  60. package/dist/image/bitmap.js +172 -0
  61. package/dist/image/jpeg.d.ts +10 -0
  62. package/dist/image/jpeg.js +697 -0
  63. package/dist/image/png.d.ts +8 -0
  64. package/dist/image/png.js +282 -0
  65. package/dist/image/transform.d.ts +20 -0
  66. package/dist/image/transform.js +52 -0
  67. package/dist/image/worker.d.ts +1 -0
  68. package/dist/image/worker.js +11 -0
  69. package/dist/images.d.ts +39 -0
  70. package/dist/images.js +283 -0
  71. package/dist/index.d.ts +64 -0
  72. package/dist/index.js +31 -0
  73. package/dist/inspect-hub.d.ts +42 -0
  74. package/dist/inspect-hub.js +14 -0
  75. package/dist/inspector.d.ts +51 -0
  76. package/dist/inspector.js +193 -0
  77. package/dist/job-admin.d.ts +55 -0
  78. package/dist/job-admin.js +89 -0
  79. package/dist/jobs.d.ts +222 -0
  80. package/dist/jobs.js +789 -0
  81. package/dist/live.d.ts +72 -0
  82. package/dist/live.js +481 -0
  83. package/dist/load-config.d.ts +2 -0
  84. package/dist/load-config.js +41 -0
  85. package/dist/log.d.ts +20 -0
  86. package/dist/log.js +143 -0
  87. package/dist/mail.d.ts +189 -0
  88. package/dist/mail.js +999 -0
  89. package/dist/media.d.ts +129 -0
  90. package/dist/media.js +470 -0
  91. package/dist/meta.d.ts +54 -0
  92. package/dist/meta.js +146 -0
  93. package/dist/middleware.d.ts +20 -0
  94. package/dist/middleware.js +101 -0
  95. package/dist/migrate.d.ts +12 -0
  96. package/dist/migrate.js +88 -0
  97. package/dist/node.d.ts +26 -0
  98. package/dist/node.js +96 -0
  99. package/dist/notice.d.ts +21 -0
  100. package/dist/notice.js +48 -0
  101. package/dist/npm.d.ts +16 -0
  102. package/dist/npm.js +347 -0
  103. package/dist/oauth.d.ts +76 -0
  104. package/dist/oauth.js +408 -0
  105. package/dist/otel.d.ts +57 -0
  106. package/dist/otel.js +293 -0
  107. package/dist/passkey.d.ts +99 -0
  108. package/dist/passkey.js +572 -0
  109. package/dist/password.d.ts +8 -0
  110. package/dist/password.js +65 -0
  111. package/dist/pdf.d.ts +46 -0
  112. package/dist/pdf.js +332 -0
  113. package/dist/personal-data.d.ts +22 -0
  114. package/dist/personal-data.js +148 -0
  115. package/dist/pointers.d.ts +9 -0
  116. package/dist/pointers.js +148 -0
  117. package/dist/postcss.d.ts +3 -0
  118. package/dist/postcss.js +89 -0
  119. package/dist/presence.d.ts +27 -0
  120. package/dist/presence.js +161 -0
  121. package/dist/preview.d.ts +25 -0
  122. package/dist/preview.js +353 -0
  123. package/dist/production.d.ts +16 -0
  124. package/dist/production.js +119 -0
  125. package/dist/project.d.ts +23 -0
  126. package/dist/project.js +536 -0
  127. package/dist/regions.d.ts +47 -0
  128. package/dist/regions.js +511 -0
  129. package/dist/replay.d.ts +44 -0
  130. package/dist/replay.js +259 -0
  131. package/dist/router.d.ts +29 -0
  132. package/dist/router.js +146 -0
  133. package/dist/rules-diff.d.ts +18 -0
  134. package/dist/rules-diff.js +165 -0
  135. package/dist/rules-test.d.ts +17 -0
  136. package/dist/rules-test.js +108 -0
  137. package/dist/saml.d.ts +160 -0
  138. package/dist/saml.js +959 -0
  139. package/dist/seal.d.ts +35 -0
  140. package/dist/seal.js +107 -0
  141. package/dist/secret.d.ts +14 -0
  142. package/dist/secret.js +110 -0
  143. package/dist/security.d.ts +53 -0
  144. package/dist/security.js +250 -0
  145. package/dist/seed.d.ts +16 -0
  146. package/dist/seed.js +94 -0
  147. package/dist/seo.d.ts +42 -0
  148. package/dist/seo.js +175 -0
  149. package/dist/settings.d.ts +79 -0
  150. package/dist/settings.js +212 -0
  151. package/dist/shared.d.ts +15 -0
  152. package/dist/shared.js +283 -0
  153. package/dist/shell.d.ts +12 -0
  154. package/dist/shell.js +118 -0
  155. package/dist/storage.d.ts +13 -0
  156. package/dist/storage.js +55 -0
  157. package/dist/support.d.ts +83 -0
  158. package/dist/support.js +236 -0
  159. package/dist/sync.d.ts +35 -0
  160. package/dist/sync.js +167 -0
  161. package/dist/tailwind.d.ts +14 -0
  162. package/dist/tailwind.js +117 -0
  163. package/dist/two-factor.d.ts +103 -0
  164. package/dist/two-factor.js +435 -0
  165. package/dist/uploads.d.ts +185 -0
  166. package/dist/uploads.js +991 -0
  167. package/dist/webhooks.d.ts +169 -0
  168. package/dist/webhooks.js +758 -0
  169. package/dist/webpush.d.ts +97 -0
  170. package/dist/webpush.js +372 -0
  171. package/dist/wizard.d.ts +141 -0
  172. package/dist/wizard.js +410 -0
  173. package/dist/workflows.d.ts +134 -0
  174. package/dist/workflows.js +511 -0
  175. package/package.json +186 -4
@@ -0,0 +1,64 @@
1
+ export { checkOg, createApp, edgeReason, notFound, NotFound } from "./app.js";
2
+ export type { OgImage, PatchOver, QueryWarning } from "./app.js";
3
+ export { notifyReaders, NoticeError, type Notice, type NotifyOptions } from "./notice.js";
4
+ export type { App, AppOptions, CspViolation, Layout, LiveSocket, MetaSource, PageContext, Route, SocketData, UpgradeServer, } from "./app.js";
5
+ export { applySite, mergeMeta, renderMeta, resolveTitle } from "./meta.js";
6
+ export type { LinkTag, MetaTag, OpenGraph, PageMeta, TwitterCard } from "./meta.js";
7
+ export { Router, parsePattern, patternForFile, splitPath } from "./router.js";
8
+ export type { Params } from "./router.js";
9
+ export { DEFAULT_SHELL, parseShell } from "./shell.js";
10
+ export { LivePage, Redirect, redirect } from "./live.js";
11
+ export { ActionError, decodeForm, decodeJson, defineAction, fail, isAction } from "./action.js";
12
+ export type { Action, ActionContext, Decoded, ParamSpec, ParamType } from "./action.js";
13
+ export type { LivePageOptions } from "./live.js";
14
+ export { MIN_SECRET_LENGTH, RateLimiter, csrfToken, importSecret, parseCookies, randomId, sameOrigin, securityHeaders, checkCspSources, type CspSources, sessionCookie, signSession, timingSafeEqual, verifyCsrf, verifySession, } from "./security.js";
15
+ export type { RateLimitOptions, HeaderOptions, CookieOptions } from "./security.js";
16
+ export { external } from "./api.js";
17
+ export type { ApiHandler, ApiHandlers, ApiMethod } from "./api.js";
18
+ export type { Middleware, MiddlewareContext, MiddlewareResult } from "./middleware.js";
19
+ export type { SecretSource, WeftConfig } from "./config.js";
20
+ export { MemorySessionStore, login, logout, switchTenant, viewAs, stopViewingAs, viewingAs, allowWhileViewing } from "./auth.js";
21
+ export type { Viewing } from "./auth.js";
22
+ export type { AuthOptions, SessionRecord, SessionStore } from "./auth.js";
23
+ export { github, google, microsoft, oidc, SignInError } from "./oauth.js";
24
+ export { emailSignIn, EmailSignIn, EmailSignInError, MemoryEmailTokenStore, normalizeEmail, SqlEmailTokenStore } from "./email-signin.js";
25
+ export type { EmailPending } from "./email-signin.js";
26
+ export { fillPattern, robotsTxt, sitemapEntries, sitemapXml } from "./seo.js";
27
+ export type { ChangeFrequency, RobotsOptions, RobotsRule, RouteEntry, SitemapEntry, SitemapOptions } from "./seo.js";
28
+ export type { DrainOptions, ErrorReport } from "./app.js";
29
+ export { createLogger, redact, requestIdOf } from "./log.js";
30
+ export type { LogLevel, Logger, LoggerOptions } from "./log.js";
31
+ export { otlpExporter } from "./otel.js";
32
+ export type { OtlpExporter, OtlpOptions, Telemetry, TraceContext } from "./otel.js";
33
+ export type { EmailSignInMessage, EmailSignInOptions, EmailToken, EmailTokenStore } from "./email-signin.js";
34
+ export { definePasskeys, MemoryPasskeyStore, PasskeyError, Passkeys, SqlPasskeyStore } from "./passkey.js";
35
+ export type { PasskeyChallenge, PasskeyCredential, PasskeyOptions, PasskeyStore } from "./passkey.js";
36
+ export type { GitHubOptions, Identity, MicrosoftOptions, OidcOptions, Provider, ProviderOptions } from "./oauth.js";
37
+ export { isSecret, parseEnv, Secret, secretEnv } from "./secret.js";
38
+ export { acceptGrant, grantToken, openWith, seal, sealWith, unseal } from "./seal.js";
39
+ export type { GrantOptions, SealOptions, UnsealOptions } from "./seal.js";
40
+ export { defineGrants, GrantError, Grants } from "./grants.js";
41
+ export { dataManifest } from "./datamap.js";
42
+ export type { DataAccess, DataManifest } from "./datamap.js";
43
+ export type { GrantErrorCode, GrantInfo, GrantRow, GrantsConfig, IssueOptions } from "./grants.js";
44
+ export { definePresence } from "./presence.js";
45
+ export type { Presence, PresenceOptions } from "./presence.js";
46
+ export { pointerArea } from "./pointers.js";
47
+ export { authState, completeTwoFactor } from "./auth.js";
48
+ export type { AuthState, LoginResult, SecondFactor } from "./auth.js";
49
+ export { base32, defineTwoFactor, fromBase32, MemoryTwoFactorStore, SqlTwoFactorStore, totp, TwoFactor, TwoFactorError } from "./two-factor.js";
50
+ export type { TwoFactorErrorCode, TwoFactorOptions, TwoFactorRecord, TwoFactorSetup, TwoFactorStatus, TwoFactorStore } from "./two-factor.js";
51
+ export { listSessions, revokeSession, signOutEverywhere, signOutUser, SqlSessionStore } from "./auth.js";
52
+ export type { SessionBroadcast, SessionInfo } from "./auth.js";
53
+ export { Account, AccountError, defineAccount, MemoryAccountTokenStore, SqlAccountTokenStore } from "./account.js";
54
+ export type { AccountErrorCode, AccountMessage, AccountOptions, AccountToken, AccountTokenKind, AccountTokenStore } from "./account.js";
55
+ export { createJobs, defineJob, isJob, JobError, Jobs, MemoryJobStore, parseCron, SqlJobStore } from "./jobs.js";
56
+ export { buildMime, defineMail, htmlToText, Mail, MailError, mailPreview, Outbox, parseAddress, postmark, prepareMail, renderMail, renderTemplate, resend, ses, signAwsRequest, smtp, } from "./mail.js";
57
+ export type { Address, AddressInput, AttachmentInput, AwsCredentials, MailErrorCode, MailMessage, MailOptions, EmailTemplate, Template as EmailTemplateParts, MailTransport, OutgoingMail, Rendered, SendResult, SentMail, SmtpOptions, } from "./mail.js";
58
+ export type { Cron, EnqueueOptions, Job, JobActor, JobContext, JobFilter, JobOptions, JobRecord, JobsOptions, JobStatus, JobStore, Schedule } from "./jobs.js";
59
+ export { defineWebPush, encryptPushPayload, generateVapidKeys, MemoryPushStore, PUSH_SERVICES, PUSH_WORKER_JS, PushError, SqlPushStore, WebPush, } from "./webpush.js";
60
+ export type { PushMessage, PushResult, PushStore, PushSubscriptionRecord, WebPushOptions } from "./webpush.js";
61
+ export { defineWebhooks, isPublicAddress, MemoryWebhookStore, nodeTransport as webhookTransport, signWebhook, SqlWebhookStore, verifyWebhook, WebhookError, Webhooks, } from "./webhooks.js";
62
+ export type { DeliveryStatus, EndpointInput, WebhookAttempt, WebhookDelivery, WebhookEndpoint, WebhookKind, WebhookMessage, WebhookRequest, WebhookResponse, WebhooksOptions, WebhookStore, WebhookTransport, } from "./webhooks.js";
63
+ export { contentMatches, defineUploads, diskStorage, GB, MB, MemoryFileStore, presignS3, s3Storage, sniffType, SqlFileStore, UploadError, Uploads, } from "./uploads.js";
64
+ export type { FileInfo, FileRecord, FileStore, PartTarget, S3Options, ScanInput, UploadKind, UploadsOptions, UploadStorage } from "./uploads.js";
package/dist/index.js ADDED
@@ -0,0 +1,31 @@
1
+ export { checkOg, createApp, edgeReason, notFound, NotFound } from "./app.js";
2
+ export { notifyReaders, NoticeError } from "./notice.js";
3
+ export { applySite, mergeMeta, renderMeta, resolveTitle } from "./meta.js";
4
+ export { Router, parsePattern, patternForFile, splitPath } from "./router.js";
5
+ export { DEFAULT_SHELL, parseShell } from "./shell.js";
6
+ export { LivePage, Redirect, redirect } from "./live.js";
7
+ export { ActionError, decodeForm, decodeJson, defineAction, fail, isAction } from "./action.js";
8
+ export { MIN_SECRET_LENGTH, RateLimiter, csrfToken, importSecret, parseCookies, randomId, sameOrigin, securityHeaders, checkCspSources, sessionCookie, signSession, timingSafeEqual, verifyCsrf, verifySession, } from "./security.js";
9
+ export { external } from "./api.js";
10
+ export { MemorySessionStore, login, logout, switchTenant, viewAs, stopViewingAs, viewingAs, allowWhileViewing } from "./auth.js";
11
+ export { github, google, microsoft, oidc, SignInError } from "./oauth.js";
12
+ export { emailSignIn, EmailSignIn, EmailSignInError, MemoryEmailTokenStore, normalizeEmail, SqlEmailTokenStore } from "./email-signin.js";
13
+ export { fillPattern, robotsTxt, sitemapEntries, sitemapXml } from "./seo.js";
14
+ export { createLogger, redact, requestIdOf } from "./log.js";
15
+ export { otlpExporter } from "./otel.js";
16
+ export { definePasskeys, MemoryPasskeyStore, PasskeyError, Passkeys, SqlPasskeyStore } from "./passkey.js";
17
+ export { isSecret, parseEnv, Secret, secretEnv } from "./secret.js";
18
+ export { acceptGrant, grantToken, openWith, seal, sealWith, unseal } from "./seal.js";
19
+ export { defineGrants, GrantError, Grants } from "./grants.js";
20
+ export { dataManifest } from "./datamap.js";
21
+ export { definePresence } from "./presence.js";
22
+ export { pointerArea } from "./pointers.js";
23
+ export { authState, completeTwoFactor } from "./auth.js";
24
+ export { base32, defineTwoFactor, fromBase32, MemoryTwoFactorStore, SqlTwoFactorStore, totp, TwoFactor, TwoFactorError } from "./two-factor.js";
25
+ export { listSessions, revokeSession, signOutEverywhere, signOutUser, SqlSessionStore } from "./auth.js";
26
+ export { Account, AccountError, defineAccount, MemoryAccountTokenStore, SqlAccountTokenStore } from "./account.js";
27
+ export { createJobs, defineJob, isJob, JobError, Jobs, MemoryJobStore, parseCron, SqlJobStore } from "./jobs.js";
28
+ export { buildMime, defineMail, htmlToText, Mail, MailError, mailPreview, Outbox, parseAddress, postmark, prepareMail, renderMail, renderTemplate, resend, ses, signAwsRequest, smtp, } from "./mail.js";
29
+ export { defineWebPush, encryptPushPayload, generateVapidKeys, MemoryPushStore, PUSH_SERVICES, PUSH_WORKER_JS, PushError, SqlPushStore, WebPush, } from "./webpush.js";
30
+ export { defineWebhooks, isPublicAddress, MemoryWebhookStore, nodeTransport as webhookTransport, signWebhook, SqlWebhookStore, verifyWebhook, WebhookError, Webhooks, } from "./webhooks.js";
31
+ export { contentMatches, defineUploads, diskStorage, GB, MB, MemoryFileStore, presignS3, s3Storage, sniffType, SqlFileStore, UploadError, Uploads, } from "./uploads.js";
@@ -0,0 +1,42 @@
1
+ import type { DevMessage } from "./devtools.js";
2
+ import type { InspectNode } from "./live.js";
3
+ export interface InspectPage {
4
+ page: string;
5
+ path: string;
6
+ }
7
+ export interface InspectView {
8
+ page: string;
9
+ path: string;
10
+ tree: InspectNode;
11
+ messages: DevMessage[];
12
+ frames: {
13
+ n: number;
14
+ at: number;
15
+ what: string;
16
+ bytes: number;
17
+ }[];
18
+ reads: {
19
+ load: {
20
+ model: string;
21
+ scope: string[];
22
+ }[];
23
+ render: {
24
+ model: string;
25
+ scope: string[];
26
+ }[];
27
+ };
28
+ }
29
+ export interface InspectHub {
30
+ pages(key: string): InspectPage[];
31
+ watch(key: string, until: number): void;
32
+ view(key: string, page: string): InspectView | null;
33
+ frame(key: string, page: string, n: number): {
34
+ n: number;
35
+ at: number;
36
+ what: string;
37
+ html: string;
38
+ } | null;
39
+ }
40
+ export declare function addInspectHub(hub: InspectHub): () => void;
41
+ export declare function inspectHubs(): InspectHub[];
42
+ export declare function sessionKey(sid: string): string;
@@ -0,0 +1,14 @@
1
+ import { createHash } from "node:crypto";
2
+ const hubs = new Set();
3
+ export function addInspectHub(hub) {
4
+ hubs.add(hub);
5
+ return () => {
6
+ hubs.delete(hub);
7
+ };
8
+ }
9
+ export function inspectHubs() {
10
+ return [...hubs];
11
+ }
12
+ export function sessionKey(sid) {
13
+ return createHash("sha256").update("weft-inspect\0").update(sid).digest("base64url").slice(0, 32);
14
+ }
@@ -0,0 +1,51 @@
1
+ import { type Model } from "@weft-framework/data";
2
+ import { type Action } from "./action.js";
3
+ import type { PageContext } from "./context.js";
4
+ import { type InspectPage, type InspectView } from "./inspect-hub.js";
5
+ type Maybe<T> = T | Promise<T>;
6
+ export type InspectorEvent = "consent-grant" | "consent-withdraw" | "list" | "look" | "frame";
7
+ export interface InspectorLogEntry {
8
+ id: string;
9
+ event: InspectorEvent;
10
+ user: string | null;
11
+ operator: string | null;
12
+ at: number;
13
+ detail: string | null;
14
+ }
15
+ export interface InspectorSession {
16
+ id: string;
17
+ user: string;
18
+ until: number;
19
+ pages: InspectPage[];
20
+ }
21
+ export interface InspectorOptions {
22
+ allow(operator: string): Maybe<boolean>;
23
+ maxMinutes?: number;
24
+ userId?(ctx: PageContext): string | null | undefined;
25
+ name?: string;
26
+ now?(): number;
27
+ }
28
+ export interface Inspector {
29
+ models: Model<never>[];
30
+ actions: Record<string, Action<never[]>>;
31
+ consent(ctx: PageContext, minutes: number): {
32
+ id: string;
33
+ until: number;
34
+ } | null;
35
+ withdraw(ctx: PageContext): boolean;
36
+ mine(ctx: PageContext): {
37
+ until: number | null;
38
+ log: InspectorLogEntry[];
39
+ maxMinutes: number;
40
+ } | null;
41
+ sessions(ctx: PageContext): Promise<InspectorSession[] | null>;
42
+ look(ctx: PageContext, id: string, page: string): Promise<InspectView | null>;
43
+ frame(ctx: PageContext, id: string, page: string, n: number): Promise<{
44
+ n: number;
45
+ at: number;
46
+ what: string;
47
+ html: string;
48
+ } | null>;
49
+ }
50
+ export declare function defineInspector(opts: InspectorOptions): Inspector;
51
+ export {};
@@ -0,0 +1,193 @@
1
+ import { defineModel } from "@weft-framework/data";
2
+ import { defineAction } from "./action.js";
3
+ import { viewingAs } from "./auth.js";
4
+ import { inspectHubs, sessionKey } from "./inspect-hub.js";
5
+ const KEEPER = Object.freeze({ id: "\u0000weft-inspector" });
6
+ const MAX_ID = 256;
7
+ export function defineInspector(opts) {
8
+ const fail = (msg) => {
9
+ throw new Error(`defineInspector: ${msg}`);
10
+ };
11
+ if (!opts || typeof opts.allow !== "function")
12
+ fail("`allow(operator)` decides who may inspect");
13
+ for (const k of ["userId", "now"]) {
14
+ if (opts[k] !== undefined && typeof opts[k] !== "function")
15
+ fail(`${k} is a function`);
16
+ }
17
+ const prefix = opts.name ?? "inspector";
18
+ if (!/^[a-z][A-Za-z0-9]{0,40}$/.test(prefix))
19
+ fail("name is an identifier");
20
+ const maxMinutes = opts.maxMinutes ?? 60;
21
+ if (!Number.isInteger(maxMinutes) || maxMinutes < 1 || maxMinutes > 1440)
22
+ fail("maxMinutes is a whole number from 1 to 1440");
23
+ const now = opts.now ?? Date.now;
24
+ const Name = prefix.charAt(0).toUpperCase() + prefix.slice(1);
25
+ const Consent = defineModel(`${Name}Consent`, {
26
+ fields: { id: "string", key: "string", user: "string", until: "number", granted: "number" },
27
+ attrs: { key: { index: true } },
28
+ read: (a) => a === KEEPER,
29
+ write: (a) => a === KEEPER,
30
+ });
31
+ const Log = defineModel(`${Name}Log`, {
32
+ fields: { id: "string", event: "string", user: "string | null", operator: "string | null", at: "number", detail: "string | null" },
33
+ attrs: { user: { index: true } },
34
+ read: (a) => a === KEEPER,
35
+ write: (a) => a === KEEPER,
36
+ });
37
+ let lastAt = 0;
38
+ let seq = 0;
39
+ const record = (event, user, operator, detail = null) => {
40
+ const t = now();
41
+ seq = t === lastAt ? seq + 1 : 0;
42
+ lastAt = t;
43
+ const id = `${t.toString(36).padStart(10, "0")}${seq.toString(36).padStart(4, "0")}${crypto.randomUUID().replaceAll("-", "").slice(0, 12)}`;
44
+ Log.as(KEEPER).create({ id, event, user, operator, at: t, detail });
45
+ };
46
+ const userIdOf = (ctx) => {
47
+ if (viewingAs(ctx))
48
+ return null;
49
+ try {
50
+ const id = opts.userId ? opts.userId(ctx) : ctx.user?.id;
51
+ return typeof id === "string" && id !== "" && id.length <= MAX_ID ? id : null;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ };
57
+ const operator = async (ctx) => {
58
+ const id = userIdOf(ctx);
59
+ if (id === null)
60
+ return null;
61
+ try {
62
+ return (await opts.allow(id)) === true ? id : null;
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ };
68
+ const watch = (key, until) => {
69
+ for (const hub of inspectHubs())
70
+ hub.watch(key, until);
71
+ };
72
+ const valid = (id) => {
73
+ if (typeof id !== "string" || id === "" || id.length > MAX_ID)
74
+ return null;
75
+ const row = Consent.as(KEEPER).get(id);
76
+ if (!row)
77
+ return null;
78
+ if (row.until <= now()) {
79
+ Consent.as(KEEPER).delete((r) => r.id === row.id);
80
+ watch(row.key, 0);
81
+ return null;
82
+ }
83
+ watch(row.key, row.until);
84
+ return row;
85
+ };
86
+ const inspector = {
87
+ models: [Consent, Log],
88
+ actions: {},
89
+ consent(ctx, minutes) {
90
+ const me = userIdOf(ctx);
91
+ if (me === null || typeof ctx.session !== "string" || ctx.session === "")
92
+ return null;
93
+ if (!Number.isInteger(minutes) || minutes < 1 || minutes > maxMinutes) {
94
+ throw new RangeError(`inspector.consent: minutes is a whole number from 1 to ${maxMinutes}`);
95
+ }
96
+ const key = sessionKey(ctx.session);
97
+ const t = now();
98
+ const until = t + minutes * 60_000;
99
+ const c = Consent.as(KEEPER);
100
+ const had = c.query().where({ key }).all()[0];
101
+ if (had && had.user !== me)
102
+ c.delete((r) => r.id === had.id);
103
+ let id;
104
+ if (had && had.user === me) {
105
+ id = had.id;
106
+ c.update((r) => r.id === id, { until, granted: t });
107
+ }
108
+ else {
109
+ id = crypto.randomUUID();
110
+ c.create({ id, key, user: me, until, granted: t });
111
+ }
112
+ watch(key, until);
113
+ record("consent-grant", me, null, String(minutes));
114
+ return { id, until };
115
+ },
116
+ withdraw(ctx) {
117
+ const me = userIdOf(ctx);
118
+ if (me === null || typeof ctx.session !== "string")
119
+ return false;
120
+ const key = sessionKey(ctx.session);
121
+ const n = Consent.as(KEEPER).delete((r) => r.key === key);
122
+ watch(key, 0);
123
+ if (n > 0)
124
+ record("consent-withdraw", me, null);
125
+ return n > 0;
126
+ },
127
+ mine(ctx) {
128
+ const me = userIdOf(ctx);
129
+ if (me === null || typeof ctx.session !== "string")
130
+ return null;
131
+ const row = Consent.as(KEEPER).query().where({ key: sessionKey(ctx.session) }).all()[0];
132
+ const until = row && row.user === me && row.until > now() ? row.until : null;
133
+ const log = Log.as(KEEPER)
134
+ .query()
135
+ .where({ user: me })
136
+ .orderBy("id", "desc")
137
+ .limit(100)
138
+ .all()
139
+ .map((r) => ({ id: r.id, event: r.event, user: r.user, operator: r.operator, at: r.at, detail: r.detail }));
140
+ return { until, log, maxMinutes };
141
+ },
142
+ async sessions(ctx) {
143
+ const op = await operator(ctx);
144
+ if (op === null)
145
+ return null;
146
+ const out = [];
147
+ for (const row of Consent.as(KEEPER).all()) {
148
+ if (!valid(row.id))
149
+ continue;
150
+ out.push({ id: row.id, user: row.user, until: row.until, pages: inspectHubs().flatMap((h) => h.pages(row.key)) });
151
+ }
152
+ record("list", null, op, String(out.length));
153
+ return out;
154
+ },
155
+ async look(ctx, id, page) {
156
+ const op = await operator(ctx);
157
+ const row = op === null ? null : valid(id);
158
+ if (op === null || !row || typeof page !== "string")
159
+ return null;
160
+ for (const hub of inspectHubs()) {
161
+ const view = hub.view(row.key, page);
162
+ if (view) {
163
+ record("look", row.user, op, view.path);
164
+ return view;
165
+ }
166
+ }
167
+ return null;
168
+ },
169
+ async frame(ctx, id, page, n) {
170
+ const op = await operator(ctx);
171
+ const row = op === null ? null : valid(id);
172
+ if (op === null || !row || typeof page !== "string" || !Number.isInteger(n) || n < 0)
173
+ return null;
174
+ for (const hub of inspectHubs()) {
175
+ const f = hub.frame(row.key, page, n);
176
+ if (f) {
177
+ record("frame", row.user, op, `${hub.pages(row.key).find((p) => p.page === page)?.path ?? ""} #${n}`);
178
+ return f;
179
+ }
180
+ }
181
+ return null;
182
+ },
183
+ };
184
+ const minutes = (raw) => (/^\d{1,5}$/.test(raw.trim()) ? Number(raw.trim()) : Number.NaN);
185
+ inspector.actions = {
186
+ [`${prefix}Consent`]: defineAction(`${prefix}Consent`, [{ name: "minutes", type: "string" }], (ctx, m) => {
187
+ const n = minutes(m);
188
+ return Number.isInteger(n) && n >= 1 && n <= maxMinutes ? inspector.consent(ctx, n) : null;
189
+ }),
190
+ [`${prefix}Withdraw`]: defineAction(`${prefix}Withdraw`, [], (ctx) => inspector.withdraw(ctx)),
191
+ };
192
+ return inspector;
193
+ }
@@ -0,0 +1,55 @@
1
+ import { type Action } from "./action.js";
2
+ import type { PageContext } from "./context.js";
3
+ import type { JobRecord, Jobs, JobStatus } from "./jobs.js";
4
+ export interface JobAdminOptions {
5
+ jobs: Jobs;
6
+ allow(ctx: PageContext): boolean | Promise<boolean>;
7
+ showArgs?: boolean | ((job: JobRecord) => boolean);
8
+ name?: string;
9
+ }
10
+ export interface JobView {
11
+ id: string;
12
+ name: string;
13
+ status: JobStatus;
14
+ attempts: number;
15
+ maxAttempts: number;
16
+ runAt: number;
17
+ created: number;
18
+ updated: number;
19
+ progress: number | null;
20
+ error: string | null;
21
+ key: string | null;
22
+ queuedBy: {
23
+ user: string;
24
+ tenant: string | null;
25
+ } | null;
26
+ args: unknown[] | null;
27
+ canRetry: boolean;
28
+ canCancel: boolean;
29
+ }
30
+ export type JobActionResult = {
31
+ ok: true;
32
+ job: JobView;
33
+ } | {
34
+ ok: false;
35
+ reason: "not found" | "wrong state";
36
+ };
37
+ export interface JobAdmin {
38
+ overview(ctx: PageContext, filter?: {
39
+ status?: string | null;
40
+ name?: string | null;
41
+ limit?: number;
42
+ }): Promise<{
43
+ counts: Record<JobStatus, number>;
44
+ jobs: JobView[];
45
+ names: string[];
46
+ status: JobStatus | null;
47
+ name: string | null;
48
+ } | null>;
49
+ job(ctx: PageContext, id: string): Promise<JobView | null>;
50
+ retry(ctx: PageContext, id: string): Promise<JobActionResult>;
51
+ cancel(ctx: PageContext, id: string): Promise<JobActionResult>;
52
+ actions: Record<string, Action<never[]>>;
53
+ }
54
+ export declare const JOB_STATUSES: readonly JobStatus[];
55
+ export declare function defineJobAdmin(opts: JobAdminOptions): JobAdmin;
@@ -0,0 +1,89 @@
1
+ import { defineAction } from "./action.js";
2
+ export const JOB_STATUSES = ["queued", "running", "dead", "done", "cancelled"];
3
+ const ID_RE = /^[0-9a-f]{32}$/;
4
+ const NAME_RE = /^[A-Za-z_$][A-Za-z0-9_$]{0,100}$/;
5
+ const MAX_LIST = 500;
6
+ export function defineJobAdmin(opts) {
7
+ if (!opts || typeof opts.allow !== "function")
8
+ throw new Error("defineJobAdmin: `allow(ctx)` decides who may use it");
9
+ if (!opts.jobs || typeof opts.jobs.list !== "function")
10
+ throw new Error("defineJobAdmin: `jobs` is a createJobs(...)");
11
+ const prefix = opts.name ?? "jobs";
12
+ if (!/^[a-z][A-Za-z0-9]{0,40}$/.test(prefix))
13
+ throw new Error("defineJobAdmin: name is an identifier");
14
+ const jobs = opts.jobs;
15
+ const showArgs = (r) => (typeof opts.showArgs === "function" ? opts.showArgs(r) === true : opts.showArgs === true);
16
+ async function gate(ctx) {
17
+ try {
18
+ return (await opts.allow(ctx)) === true;
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ const view = (r) => {
25
+ let args = null;
26
+ try {
27
+ args = showArgs(r) ? structuredClone(r.args) : null;
28
+ }
29
+ catch {
30
+ args = null;
31
+ }
32
+ return {
33
+ id: r.id,
34
+ name: r.name,
35
+ status: r.status,
36
+ attempts: r.attempts,
37
+ maxAttempts: r.maxAttempts,
38
+ runAt: r.runAt,
39
+ created: r.created,
40
+ updated: r.updated,
41
+ progress: r.progress,
42
+ error: r.error,
43
+ key: r.key,
44
+ queuedBy: r.actor ? { user: r.actor.user, tenant: r.actor.tenant ?? null } : null,
45
+ args,
46
+ canRetry: r.status === "dead" || r.status === "cancelled",
47
+ canCancel: r.status === "queued" || r.status === "dead",
48
+ };
49
+ };
50
+ const find = async (ctx, id) => {
51
+ if (!(await gate(ctx)) || typeof id !== "string" || !ID_RE.test(id))
52
+ return null;
53
+ return (await jobs.get(id)) ?? null;
54
+ };
55
+ const act = async (ctx, id, op) => {
56
+ const r = await find(ctx, id);
57
+ if (!r)
58
+ return { ok: false, reason: "not found" };
59
+ if (!(await jobs[op](r.id)))
60
+ return { ok: false, reason: "wrong state" };
61
+ return { ok: true, job: view((await jobs.get(r.id))) };
62
+ };
63
+ const admin = {
64
+ async overview(ctx, filter = {}) {
65
+ if (!(await gate(ctx)))
66
+ return null;
67
+ const status = JOB_STATUSES.includes(filter.status) ? filter.status : null;
68
+ const name = typeof filter.name === "string" && NAME_RE.test(filter.name) ? filter.name : null;
69
+ const limit = filter.limit === undefined ? 200 : filter.limit;
70
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIST)
71
+ throw new RangeError(`jobAdmin.overview: limit is from 1 to ${MAX_LIST}`);
72
+ const rows = await jobs.list({ ...(status ? { status } : {}), ...(name ? { name } : {}), limit });
73
+ return { counts: await jobs.counts(), jobs: rows.map(view), names: jobs.names(), status, name };
74
+ },
75
+ async job(ctx, id) {
76
+ const r = await find(ctx, id);
77
+ return r ? view(r) : null;
78
+ },
79
+ retry: (ctx, id) => act(ctx, id, "retry"),
80
+ cancel: (ctx, id) => act(ctx, id, "cancel"),
81
+ actions: {},
82
+ };
83
+ const idParam = [{ name: "id", type: "string" }];
84
+ admin.actions = {
85
+ [`${prefix}Retry`]: defineAction(`${prefix}Retry`, idParam, (ctx, id) => admin.retry(ctx, id)),
86
+ [`${prefix}Cancel`]: defineAction(`${prefix}Cancel`, idParam, (ctx, id) => admin.cancel(ctx, id)),
87
+ };
88
+ return admin;
89
+ }