@cicord/client 0.1.3 → 0.1.5

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/dist/index.d.mts CHANGED
@@ -413,12 +413,25 @@ interface PlanBlocked {
413
413
  fields?: Record<string, PlanFieldChange>;
414
414
  /** `reason` explained. */
415
415
  error?: HumanError;
416
+ /** The refused operation for humans, when kind and key alone do not say it (memberRole). */
417
+ summary?: string;
418
+ }
419
+ /**
420
+ * Information that needs no action: the server stays in sync (e.g. a user listed in
421
+ * `roles.<key>.members` who has not joined the server yet).
422
+ */
423
+ interface PlanNote {
424
+ kind: PlanKind;
425
+ key: string;
426
+ message: string;
416
427
  }
417
428
  /** Diff between the desired and the live state of one server; changes are in apply order. */
418
429
  interface Plan {
419
430
  server: string;
420
431
  changes: PlanChange[];
421
432
  blocked: PlanBlocked[];
433
+ /** Absent when there is none. */
434
+ notes?: PlanNote[];
422
435
  }
423
436
  interface SyncResult {
424
437
  plan: Plan;
@@ -471,7 +484,7 @@ type AnalyticsKind = "counter" | "max" | "last" | (string & {});
471
484
  /** Unit of a metric's values. */
472
485
  type AnalyticsUnit = "count" | "members" | "seconds" | "level" | (string & {});
473
486
  /** Metric names of the analytics catalog. */
474
- type AnalyticsMetric = "members.total" | "members.bots" | "members.online" | "members.joined" | "members.left" | "members.joined.age" | "members.joined.bots" | "members.roles.added" | "members.roles.removed" | "members.boosting" | "server.boost.tier" | "members.active" | "members.active.chat" | "members.active.voice" | "invites.uses" | "invites.created" | "onboarding.completed" | "messages.sent" | "messages.sent.bots" | "messages.edited" | "messages.deleted" | "messages.attachments" | "messages.replies" | "messages.stickers" | "reactions.added" | "threads.created" | "polls.created" | "voice.seconds" | "voice.sessions" | "voice.peak" | "voice.streaming" | "stage.seconds" | "events.interested" | "moderation.actions" | "automod.triggers" | "automod.blocked" | "commands.used" | "components.used" | "presence.status" | "presence.platform" | "presence.activity";
487
+ type AnalyticsMetric = "members.total" | "members.bots" | "members.online" | "members.joined" | "members.left" | "members.joined.age" | "members.joined.bots" | "members.roles.added" | "members.roles.removed" | "members.boosting" | "server.boost.tier" | "members.active" | "members.active.chat" | "members.active.voice" | "invites.uses" | "invites.created" | "onboarding.completed" | "messages.sent" | "messages.sent.bots" | "messages.edited" | "messages.deleted" | "messages.attachments" | "messages.replies" | "messages.stickers" | "reactions.added" | "threads.created" | "polls.created" | "voice.seconds" | "voice.sessions" | "voice.peak" | "voice.streaming" | "stage.seconds" | "events.interested" | "moderation.actions" | "automod.triggers" | "automod.blocked" | "commands.used" | "components.used" | "bots.commands" | "bots.commands.channels" | "bots.commands.tenure" | "members.active.bots" | "presence.status" | "presence.platform" | "presence.activity";
475
488
  /** A metric group that is not collected, with the reason and the fix. */
476
489
  interface AnalyticsMissing {
477
490
  metrics: string[];
@@ -587,10 +600,17 @@ interface AnalyticsSummary {
587
600
  * of the samples), reactions.added, commands.used, moderation.actions.
588
601
  */
589
602
  kpis: AnalyticsKpi[];
590
- /** Top 10 per metric name over the period. */
603
+ /**
604
+ * Top 10 per metric name over the period: messages.sent, voice.seconds, reactions.added,
605
+ * invites.uses, commands.used, moderation.actions, automod.triggers, members.roles.added,
606
+ * members.joined.age, bots.commands (`"<bot> /<command>"`), bots.commands.channels,
607
+ * bots.commands.tenure, components.used (per bot) and, with presence, presence.activity.
608
+ */
591
609
  rankings: Record<string, AnalyticsRanked[]>;
592
610
  /** Human messages per weekday and hour (UTC): `heatmap[weekday][hour]`, weekday 0 = Monday. */
593
611
  heatmap: number[][];
612
+ /** Bot commands (`bots.commands`) per weekday and hour (UTC), shaped like `heatmap`. */
613
+ botsHeatmap: number[][];
594
614
  labels: Record<string, AnalyticsLabel>;
595
615
  status: AnalyticsStatus;
596
616
  }
@@ -1290,6 +1310,59 @@ interface WriteResult {
1290
1310
  revision?: string;
1291
1311
  pullRequestUrl?: string;
1292
1312
  }
1313
+ /**
1314
+ * An event of `GET /api/v1/events`: `hello` first (runtime version and revision), then
1315
+ * change hints. A hint carries no content: refetch what you display.
1316
+ */
1317
+ type AdminEvent = {
1318
+ type: "hello";
1319
+ version: string;
1320
+ revision: string;
1321
+ } |
1322
+ /** The runtime is shutting down (restart, update): reconnect. */
1323
+ {
1324
+ type: "stopping";
1325
+ } | {
1326
+ type: "status";
1327
+ } | {
1328
+ type: "sync" | "plugins" | "analytics";
1329
+ server?: string;
1330
+ };
1331
+ /** Periods of `GET /portal/{server}/analytics`. */
1332
+ type PortalAnalyticsPeriod = "7d" | "30d" | "90d";
1333
+ /**
1334
+ * `GET /portal/{server}/analytics`: server-wide aggregates for members (opt-in per
1335
+ * server, `spec.analytics.portal`). Nothing per member; only channels @everyone can see
1336
+ * are named.
1337
+ */
1338
+ interface PortalAnalytics {
1339
+ server: string;
1340
+ period: PortalAnalyticsPeriod;
1341
+ from: Timestamp;
1342
+ to: Timestamp;
1343
+ /** Oldest data point, null before the first one. */
1344
+ since: Timestamp | null;
1345
+ /**
1346
+ * In this order: members.total, members.joined, members.active (average per day),
1347
+ * messages.sent, voice.seconds, reactions.added, bots.commands, members.active.bots
1348
+ * (average per day). `spark` is per day.
1349
+ */
1350
+ kpis: AnalyticsKpi[];
1351
+ /** Channels with the most messages among those everyone can see, top 5. */
1352
+ topChannels: {
1353
+ id: string;
1354
+ name: string;
1355
+ value: number;
1356
+ }[];
1357
+ /** Most used bot commands (every bot of the server), top 8; command starts with "/". */
1358
+ topBotCommands: {
1359
+ bot: string;
1360
+ command: string;
1361
+ value: number;
1362
+ }[];
1363
+ /** Messages per weekday (0 = Monday) and UTC hour. */
1364
+ heatmap: number[][];
1365
+ }
1293
1366
  type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
1294
1367
  /** "<METHOD> /path", `:name` segments being parameters: "GET /polls/:id". */
1295
1368
  type RouteKey = `${RouteMethod} /${string}`;
@@ -1467,6 +1540,12 @@ interface EventStreamOptions {
1467
1540
  retryMs?: number;
1468
1541
  /** Stop after the first disconnection instead of reconnecting. */
1469
1542
  once?: boolean;
1543
+ /**
1544
+ * Reconnect when nothing (event or comment) arrives for this long, in ms: a proxy can
1545
+ * keep the connection open after the server went away. Use it with a server that sends
1546
+ * keep-alive comments more often (Cicord's streams: every 25 s). Default: no limit.
1547
+ */
1548
+ idleTimeoutMs?: number;
1470
1549
  signal?: AbortSignal;
1471
1550
  }
1472
1551
  interface EventStream {
@@ -1642,6 +1721,11 @@ export declare class CicordClient {
1642
1721
  server: (server: string, options?: CallOptions) => Promise<PortalServer>;
1643
1722
  /** `GET /portal/{server}/me` — the viewer as a member of the server. */
1644
1723
  me: (server: string, options?: CallOptions) => Promise<PortalMe>;
1724
+ /**
1725
+ * `GET /portal/{server}/analytics?period=` — server-wide activity for the portal, when
1726
+ * the server opts in (`spec.analytics.portal`: members or public; 404 otherwise).
1727
+ */
1728
+ analytics: (server: string, period?: PortalAnalyticsPeriod, options?: CallOptions) => Promise<PortalAnalytics>;
1645
1729
  };
1646
1730
  /** Routes of a plugin instance: `/api/v1/portal/{server}/plugins/{bot}/{instance}/{path}`. */
1647
1731
  plugin(server: string, bot: string, instance: string): PluginRoutes;
@@ -1655,6 +1739,12 @@ export declare class CicordClient {
1655
1739
  instance: string;
1656
1740
  }): TypedPluginRoutes<N>;
1657
1741
  readonly admin: {
1742
+ /**
1743
+ * Subscribes to `GET /events` (SSE, moderator): `hello` on every (re)connection, then
1744
+ * change hints for the runtime (`status`) and the servers you moderate (`sync`,
1745
+ * `plugins`, `analytics`). Reconnects automatically; call `close()` to stop.
1746
+ */
1747
+ subscribe: (onEvent: (event: AdminEvent) => void, options?: Omit<EventStreamOptions, "onEvent">) => EventStream;
1658
1748
  /** `GET /status` (admin, moderator) — visible servers only. */
1659
1749
  status: (options?: CallOptions) => Promise<RuntimeStatus>;
1660
1750
  /** `GET /history?limit=&target=` (admin, moderator), newest first. */
@@ -1870,5 +1960,5 @@ export declare class CicordApiError extends Error {
1870
1960
  static fromResponse(status: number, statusText: string, body: Json | string | undefined): CicordApiError;
1871
1961
  }
1872
1962
  export declare function isCicordApiError(error: unknown, code?: ApiErrorCode): error is CicordApiError;
1873
- export type { AccessRole, AddRegistryRequest, AnalyticsCatalog, AnalyticsCatalogEntry, AnalyticsKind, AnalyticsKpi, AnalyticsLabel, AnalyticsLabelKind, AnalyticsMetric, AnalyticsMissing, AnalyticsPeriod, AnalyticsPoint, AnalyticsRange, AnalyticsRanked, AnalyticsSerie, AnalyticsSeries, AnalyticsSeriesParams, AnalyticsStatus, AnalyticsStep, AnalyticsSummary, AnalyticsSummaryQuery, AnalyticsUnit, ApiErrorBody, ApiErrorCode, AuditEntry, AuditQuery, AuthMode, BotStatus, ButtonStyle, CallOptions, CicordClientOptions, ConfigScope, Diagnostic, Drift, EventStream, EventStreamOptions, ExchangeLinkTokenOptions, FetchLike, HealthState, HistoryLike, HistoryQuery, HumanError, HumanErrorCode, InstallResult, InstalledPluginVersion, InteractionResult, InteractionStatus, Items, Json, Leaderboard, LeaderboardEntry, LevelsStanding, ListDiff, LocationLike, Me, MeServer, Message, MessageButton, MessageEmbed, MessageRow, MessageSelect, MessageSelectOption, OfficialPluginRoutes, OnboardingAnswers, OnboardingApi, OnboardingCompleteRequest, OnboardingCompleteResponse, OnboardingOption, OnboardingRole, OnboardingStep, OnboardingSteps, OptionalArg, Page, PageParams, PermissionDiff, Plan, PlanAction, PlanBlocked, PlanChange, PlanFieldChange, PlanKind, PluginCommandSummary, PluginInstance, PluginInstanceStatus, PluginListParams, PluginManifestSummary, PluginRouteRegistry, PluginRoutes, PluginSortKey, PluginTrust, PluginUpdate, PluginUpdateFiles, PluginUpdateInstance, PluginUpdateKind, PluginUpdateLevel, PollResults, PortalLink, PortalLinkIcon, PortalLocale, PortalMe, PortalMember, PortalPages, PortalPlugin, PortalRole, PortalServer, PortalTheme, Query, RemotePlanResult, RequestOptions, ResourceCategory, ResourceChannel, ResourceRole, Revision, RouteAccess, RouteCallOptions, RouteEntry, RouteInput, RouteKey, RouteKeyOf, RouteMethod, RouteParams, RouteResponseOf, RoutesOf, RuntimeMode, RuntimeStatus, ServerAssetKind, ServerAssetResult, ServerDetail, ServerResources, ServerSentEvent, ServerStatus, SimChannel, SimCommand, SimCommandOption, SimCommandOptionType, SimCommandRequest, SimComponentRequest, SimMember, SimModal, SimModalRequest, SimModalRow, SimRole, SimSendMessageRequest, SimServer, SimState, SimTextInput, SortOrder, StoreDetail, StoreInstallRequest, StoreInstallation, StorePlugin, StorePluginParams, StorePluginSortKey, StoreSignature, StoreSource, StoreSourceKind, StoreSourceSummary, StoreTrust, StoreUpdateRequest, StoreUpdateResult, StoreUpdateReview, StoredSession, StreamFetch, SyncRecord, SyncRecordStatus, SyncResult, SyncState, Ticket, TicketList, TicketStatus, Timestamp, TokenSession, TokenStore, TypedPluginRoutes, UninstallResult, UntypedRoute, UpdatePluginConfigRequest, UpdatedInstance, User, WriteBackResult, WriteResult };
1963
+ export type { AccessRole, AddRegistryRequest, AdminEvent, AnalyticsCatalog, AnalyticsCatalogEntry, AnalyticsKind, AnalyticsKpi, AnalyticsLabel, AnalyticsLabelKind, AnalyticsMetric, AnalyticsMissing, AnalyticsPeriod, AnalyticsPoint, AnalyticsRange, AnalyticsRanked, AnalyticsSerie, AnalyticsSeries, AnalyticsSeriesParams, AnalyticsStatus, AnalyticsStep, AnalyticsSummary, AnalyticsSummaryQuery, AnalyticsUnit, ApiErrorBody, ApiErrorCode, AuditEntry, AuditQuery, AuthMode, BotStatus, ButtonStyle, CallOptions, CicordClientOptions, ConfigScope, Diagnostic, Drift, EventStream, EventStreamOptions, ExchangeLinkTokenOptions, FetchLike, HealthState, HistoryLike, HistoryQuery, HumanError, HumanErrorCode, InstallResult, InstalledPluginVersion, InteractionResult, InteractionStatus, Items, Json, Leaderboard, LeaderboardEntry, LevelsStanding, ListDiff, LocationLike, Me, MeServer, Message, MessageButton, MessageEmbed, MessageRow, MessageSelect, MessageSelectOption, OfficialPluginRoutes, OnboardingAnswers, OnboardingApi, OnboardingCompleteRequest, OnboardingCompleteResponse, OnboardingOption, OnboardingRole, OnboardingStep, OnboardingSteps, OptionalArg, Page, PageParams, PermissionDiff, Plan, PlanAction, PlanBlocked, PlanChange, PlanFieldChange, PlanKind, PlanNote, PluginCommandSummary, PluginInstance, PluginInstanceStatus, PluginListParams, PluginManifestSummary, PluginRouteRegistry, PluginRoutes, PluginSortKey, PluginTrust, PluginUpdate, PluginUpdateFiles, PluginUpdateInstance, PluginUpdateKind, PluginUpdateLevel, PollResults, PortalAnalytics, PortalAnalyticsPeriod, PortalLink, PortalLinkIcon, PortalLocale, PortalMe, PortalMember, PortalPages, PortalPlugin, PortalRole, PortalServer, PortalTheme, Query, RemotePlanResult, RequestOptions, ResourceCategory, ResourceChannel, ResourceRole, Revision, RouteAccess, RouteCallOptions, RouteEntry, RouteInput, RouteKey, RouteKeyOf, RouteMethod, RouteParams, RouteResponseOf, RoutesOf, RuntimeMode, RuntimeStatus, ServerAssetKind, ServerAssetResult, ServerDetail, ServerResources, ServerSentEvent, ServerStatus, SimChannel, SimCommand, SimCommandOption, SimCommandOptionType, SimCommandRequest, SimComponentRequest, SimMember, SimModal, SimModalRequest, SimModalRow, SimRole, SimSendMessageRequest, SimServer, SimState, SimTextInput, SortOrder, StoreDetail, StoreInstallRequest, StoreInstallation, StorePlugin, StorePluginParams, StorePluginSortKey, StoreSignature, StoreSource, StoreSourceKind, StoreSourceSummary, StoreTrust, StoreUpdateRequest, StoreUpdateResult, StoreUpdateReview, StoredSession, StreamFetch, SyncRecord, SyncRecordStatus, SyncResult, SyncState, Ticket, TicketList, TicketStatus, Timestamp, TokenSession, TokenStore, TypedPluginRoutes, UninstallResult, UntypedRoute, UpdatePluginConfigRequest, UpdatedInstance, User, WriteBackResult, WriteResult };
1874
1964
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -164,19 +164,34 @@ function openEventStream(fetcher, url, init, options) {
164
164
  const run = async () => {
165
165
  while (!controller.signal.aborted) {
166
166
  const parser = new SseParser(options.onEvent);
167
+ const attempt = new AbortController();
168
+ const endAttempt = () => attempt.abort();
169
+ controller.signal.addEventListener("abort", endAttempt, { once: true });
170
+ let idle;
171
+ let timedOut = false;
172
+ const arm = () => {
173
+ if (options.idleTimeoutMs === void 0) return;
174
+ clearTimeout(idle);
175
+ idle = setTimeout(() => {
176
+ timedOut = true;
177
+ attempt.abort();
178
+ }, options.idleTimeoutMs);
179
+ };
167
180
  try {
168
181
  const headers = new Headers(init.headers);
169
182
  headers.set("Accept", "text/event-stream");
170
183
  if (lastEventId) headers.set("Last-Event-ID", lastEventId);
184
+ arm();
171
185
  const response = await fetcher(url, {
172
186
  ...init,
173
187
  headers,
174
- signal: controller.signal
188
+ signal: attempt.signal
175
189
  });
176
190
  if (!response.ok || !response.body) throw new Error(`event stream ${url}: HTTP ${response.status}`);
177
191
  options.onOpen?.();
178
192
  const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
179
193
  for (;;) {
194
+ arm();
180
195
  const { value, done } = await reader.read();
181
196
  if (done) break;
182
197
  parser.push(value);
@@ -186,7 +201,10 @@ function openEventStream(fetcher, url, init, options) {
186
201
  if (!controller.signal.aborted) options.onError?.(/* @__PURE__ */ new Error(`event stream ${url}: disconnected`));
187
202
  } catch (error) {
188
203
  if (controller.signal.aborted) break;
189
- options.onError?.(error);
204
+ options.onError?.(timedOut ? /* @__PURE__ */ new Error(`event stream ${url}: nothing received for ${options.idleTimeoutMs} ms`) : error);
205
+ } finally {
206
+ clearTimeout(idle);
207
+ controller.signal.removeEventListener("abort", endAttempt);
190
208
  }
191
209
  if (options.once) break;
192
210
  await sleep(retryMs, controller.signal);
@@ -512,7 +530,15 @@ var CicordClient = class {
512
530
  /** `GET /portal/{server}`. */
513
531
  server: async (server, options) => this.#absolutize(await this.#api("GET", `/portal/${seg(server)}`, options)),
514
532
  /** `GET /portal/{server}/me` — the viewer as a member of the server. */
515
- me: (server, options) => this.#api("GET", `/portal/${seg(server)}/me`, options)
533
+ me: (server, options) => this.#api("GET", `/portal/${seg(server)}/me`, options),
534
+ /**
535
+ * `GET /portal/{server}/analytics?period=` — server-wide activity for the portal, when
536
+ * the server opts in (`spec.analytics.portal`: members or public; 404 otherwise).
537
+ */
538
+ analytics: (server, period = "30d", options) => this.#api("GET", `/portal/${seg(server)}/analytics`, {
539
+ query: { period },
540
+ ...options
541
+ })
516
542
  };
517
543
  /** Runtime-relative image URLs (logo, banner) resolved against `baseUrl` (embedded portals). */
518
544
  #absolutize(server) {
@@ -580,6 +606,42 @@ var CicordClient = class {
580
606
  };
581
607
  }
582
608
  admin = {
609
+ /**
610
+ * Subscribes to `GET /events` (SSE, moderator): `hello` on every (re)connection, then
611
+ * change hints for the runtime (`status`) and the servers you moderate (`sync`,
612
+ * `plugins`, `analytics`). Reconnects automatically; call `close()` to stop.
613
+ */
614
+ subscribe: (onEvent, options = {}) => this.events("/events", {
615
+ ...options,
616
+ onEvent: (e) => {
617
+ let data = {};
618
+ try {
619
+ data = JSON.parse(e.data || "{}");
620
+ } catch {
621
+ return;
622
+ }
623
+ const server = typeof data.server === "string" ? data.server : void 0;
624
+ switch (e.event) {
625
+ case "hello":
626
+ onEvent({
627
+ type: "hello",
628
+ version: typeof data.version === "string" ? data.version : "",
629
+ revision: typeof data.revision === "string" ? data.revision : ""
630
+ });
631
+ break;
632
+ case "status":
633
+ case "stopping":
634
+ onEvent({ type: e.event });
635
+ break;
636
+ case "sync":
637
+ case "plugins":
638
+ case "analytics": onEvent(server === void 0 ? { type: e.event } : {
639
+ type: e.event,
640
+ server
641
+ });
642
+ }
643
+ }
644
+ }),
583
645
  /** `GET /status` (admin, moderator) — visible servers only. */
584
646
  status: (options) => this.#api("GET", "/status", options),
585
647
  /** `GET /history?limit=&target=` (admin, moderator), newest first. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/routes.ts","../src/sse.ts","../src/client.ts","../src/onboarding.ts","../src/showcase.ts"],"sourcesContent":["import type { ApiErrorCode, Diagnostic, Json } from \"./types.ts\";\n\nconst CODE_BY_STATUS: Record<number, ApiErrorCode> = {\n 400: \"invalid\",\n 401: \"unauthenticated\",\n 403: \"forbidden\",\n 404: \"not_found\",\n 405: \"invalid\",\n 409: \"conflict\",\n 413: \"invalid\",\n 415: \"invalid\",\n 421: \"forbidden\",\n 422: \"invalid\",\n 500: \"internal\",\n 503: \"unavailable\",\n};\n\n/** Error code for a status when the body carries none (plain-text 404s, proxies…). */\nexport function codeForStatus(status: number): ApiErrorCode {\n return CODE_BY_STATUS[status] ?? (status >= 500 ? \"internal\" : `http_${status}`);\n}\n\n/**\n * Error raised for every non-2xx response of the runtime API (and for network failures,\n * with `status: 0` and code `\"network\"`).\n */\nexport class CicordApiError extends Error {\n /** `snake_case` error code from the body (`{\"error\": {\"code\"}}`), or derived from the status. */\n readonly code: ApiErrorCode;\n /** HTTP status, 0 for network errors. */\n readonly status: number;\n /** Validation diagnostics (422 on config updates, `POST /plan`). */\n readonly diagnostics: Diagnostic[];\n /** Parsed response body (JSON or text), when any. */\n readonly body: Json | string | undefined;\n /** How to fix it, when the runtime explains the error (plan / sync failures). */\n readonly hint: string | undefined;\n /** Raw technical text behind `message`, when the runtime explains the error. */\n readonly details: string | undefined;\n /** Humanized error code (`HumanErrorCode`), when the runtime explains the error. */\n readonly reason: string | undefined;\n\n constructor(init: {\n code: ApiErrorCode;\n status: number;\n message: string;\n diagnostics?: Diagnostic[];\n body?: Json | string;\n cause?: unknown;\n hint?: string | undefined;\n details?: string | undefined;\n reason?: string | undefined;\n }) {\n super(init.message, init.cause === undefined ? undefined : { cause: init.cause });\n this.name = \"CicordApiError\";\n this.code = init.code;\n this.status = init.status;\n this.diagnostics = init.diagnostics ?? [];\n this.body = init.body;\n this.hint = init.hint;\n this.details = init.details;\n this.reason = init.reason;\n }\n\n /** Builds the error from a response status and its (already parsed) body. */\n static fromResponse(\n status: number,\n statusText: string,\n body: Json | string | undefined,\n ): CicordApiError {\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n const error = (body as { error?: unknown }).error;\n if (error && typeof error === \"object\" && !Array.isArray(error)) {\n const e = error as {\n code?: unknown;\n message?: unknown;\n diagnostics?: unknown;\n hint?: unknown;\n details?: unknown;\n reason?: unknown;\n };\n const str = (v: unknown) => (typeof v === \"string\" && v ? v : undefined);\n return new CicordApiError({\n code: typeof e.code === \"string\" && e.code ? e.code : codeForStatus(status),\n status,\n message:\n typeof e.message === \"string\" && e.message ? e.message : statusText || `HTTP ${status}`,\n diagnostics: Array.isArray(e.diagnostics) ? e.diagnostics : [],\n body,\n hint: str(e.hint),\n details: str(e.details),\n reason: str(e.reason),\n });\n }\n }\n const text = typeof body === \"string\" ? body.trim() : \"\";\n return new CicordApiError({\n code: codeForStatus(status),\n status,\n message: text && text.length <= 200 ? text : statusText || `HTTP ${status}`,\n ...(body === undefined ? {} : { body }),\n });\n }\n}\n\nexport function isCicordApiError(error: unknown, code?: ApiErrorCode): error is CicordApiError {\n return error instanceof CicordApiError && (code === undefined || error.code === code);\n}\n","/**\n * Typed plugin routes. A portal learns the routes of the plugins of its repository from\n * `src/cicord-routes.d.ts`, generated by `cicord portal typegen` (and `cicord portal build`): a\n * module augmentation of `PluginRouteRegistry`, keyed by plugin name then route key, with\n * the access level and the query, body and response types declared by the plugin's route\n * contract (plugin.yaml `spec.routes.types`).\n *\n * ```ts\n * const levels = client.routes(\"levels\", server.key, instance); // instance: { bot, instance }\n * const board = await levels.call(\"GET /leaderboard\", { query: { limit: 10 } }); // board.items…\n * const poll = await client.routes(\"polls\", server.key, p).call(\"GET /polls/:id\", { params: { id } });\n * ```\n */\nimport type { CallOptions, Query } from \"./client.ts\";\nimport type {\n OnboardingAnswers,\n OnboardingCompleteResponse,\n OnboardingSteps,\n} from \"./onboarding.ts\";\nimport type { Leaderboard, TicketList, TicketStatus } from \"./showcase.ts\";\nimport type { Json } from \"./types.ts\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n/** \"<METHOD> /path\", `:name` segments being parameters: \"GET /polls/:id\". */\nexport type RouteKey = `${RouteMethod} /${string}`;\n/** Access level of a route (`definePlugin({ routes })`). */\nexport type RouteAccess = \"public\" | \"member\" | \"moderator\" | \"admin\";\n\n/** `{ id: string }` for \"GET /polls/:id\". */\nexport type RouteParams<K extends string> = K extends `${string}/:${infer Rest}`\n ? Rest extends `${infer Name}/${infer Tail}`\n ? { [P in Name]: string } & RouteParams<`/${Tail}`>\n : { [P in Rest]: string }\n : {};\n\n/** A route whose plugin declares no types: any query and body, a JSON response. */\nexport interface UntypedRoute {\n query?: Query;\n body?: unknown;\n response: Json;\n}\n\n/**\n * One route of `PluginRouteRegistry`: its access level and, when the plugin's contract\n * `Contract` declares route `K`, its `query`, `body` and `response` (absent: `204`).\n */\nexport type RouteEntry<\n A extends RouteAccess = RouteAccess,\n Contract = {},\n K extends string = never,\n> = { readonly access: A } & ([K] extends [never]\n ? UntypedRoute\n : K extends keyof Contract\n ? Contract[K]\n : UntypedRoute);\n\n/**\n * Routes of the plugins of the repository, by plugin name then route key. Empty here:\n * `src/cicord-routes.d.ts` (generated by `cicord portal typegen`) fills it.\n */\nexport interface PluginRouteRegistry {}\n\n/** levels `GET /me`: the viewer's own standing. */\nexport interface LevelsStanding {\n userId: string;\n /** From 1, null when the viewer has no XP yet. */\n rank: number | null;\n xp: number;\n level: number;\n /** XP earned inside the current level. */\n current: number;\n /** XP needed for the next level. */\n needed: number;\n}\n\n/** polls `GET /polls/:id`. */\nexport interface PollResults {\n id: string;\n question: string;\n status: \"open\" | \"closed\";\n multiple: boolean;\n createdAt: string;\n closesAt: string;\n closedAt: string | null;\n choices: { label: string; votes: number }[];\n voters: number;\n}\n\n/**\n * Routes of the official plugins (the `cicord` source), used for a plugin that the generated\n * registry does not list: the reference portal type-checks in a repository without them.\n */\nexport interface OfficialPluginRoutes {\n levels: {\n \"GET /leaderboard\": {\n readonly access: \"public\";\n query: { limit?: number };\n response: Leaderboard;\n };\n \"GET /me\": { readonly access: \"member\"; response: LevelsStanding };\n };\n polls: { \"GET /polls/:id\": { readonly access: \"public\"; response: PollResults } };\n tickets: {\n \"GET /tickets\": {\n readonly access: \"moderator\";\n query: { status?: TicketStatus };\n response: TicketList;\n };\n \"GET /tickets/:id\": RouteEntry<\"moderator\">;\n };\n onboarding: {\n \"GET /steps\": { readonly access: \"member\"; response: OnboardingSteps };\n \"POST /complete\": {\n readonly access: \"member\";\n body: { answers: OnboardingAnswers };\n response: OnboardingCompleteResponse;\n };\n };\n}\n\n/** The routes of plugin `N`: generated registry, else official plugin, else untyped. */\nexport type RoutesOf<N extends string> = N extends keyof PluginRouteRegistry\n ? PluginRouteRegistry[N]\n : N extends keyof OfficialPluginRoutes\n ? OfficialPluginRoutes[N]\n : { [K in RouteKey]: RouteEntry };\n\n/** Route keys of plugin `N` (optionally only those of `M` methods). */\nexport type RouteKeyOf<N extends string, M extends RouteMethod = RouteMethod> = Extract<\n keyof RoutesOf<N>,\n `${M} /${string}`\n>;\n\n/** The JSON a route answers with (`undefined` for routes declaring no response: 204). */\nexport type RouteResponseOf<E> = E extends { response: infer R } ? R : undefined;\n\ntype ParamsArg<K extends string> = keyof RouteParams<K> extends never\n ? { params?: Record<string, never> }\n : { params: RouteParams<K> };\ntype QueryArg<E> = E extends { query: infer Q }\n ? {} extends Q\n ? { query?: Q }\n : { query: Q }\n : E extends { query?: infer Q }\n ? { query?: Q }\n : { query?: undefined };\ntype BodyArg<E> = E extends { body: infer B }\n ? { body: B }\n : E extends { body?: infer B }\n ? { body?: B }\n : { body?: undefined };\n\n/** What a call needs: `params` (from the key), `query` and `body` (as declared). */\nexport type RouteInput<K extends string, E> = ParamsArg<K> & QueryArg<E> & BodyArg<E>;\nexport type RouteCallOptions<K extends string, E> = RouteInput<K, E> &\n CallOptions & { headers?: Record<string, string> };\n\n/** Makes the options argument optional when nothing in it is required. */\nexport type OptionalArg<T> = {} extends T ? [options?: T] : [options: T];\n\n/** Typed calls to the routes of one instance of plugin `N`. */\nexport interface TypedPluginRoutes<N extends string> {\n readonly plugin: N;\n readonly server: string;\n readonly bot: string;\n readonly instance: string;\n /** Calls a route: `call(\"GET /polls/:id\", { params: { id } })`. */\n call<K extends RouteKeyOf<N> & string>(\n this: void,\n route: K,\n ...options: OptionalArg<RouteCallOptions<K, RoutesOf<N>[K]>>\n ): Promise<RouteResponseOf<RoutesOf<N>[K]>>;\n /** Absolute URL of a route (`GET` routes: links, `<img src>`, EventSource…). */\n url<K extends RouteKeyOf<N> & string>(\n this: void,\n route: K,\n ...options: OptionalArg<RouteInput<K, RoutesOf<N>[K]>>\n ): string;\n}\n\n/** Splits \"GET /polls/:id\" with `{ id: \"4\" }` into `[\"GET\", \"/polls/4\"]`. */\nexport function resolveRoute(\n route: string,\n params: Record<string, string | number> | undefined = {},\n): [method: RouteMethod, path: string] {\n const space = route.indexOf(\" \");\n const method = route.slice(0, space) as RouteMethod;\n if (space < 0 || ![\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"].includes(method))\n throw new Error(`@cicord/client: invalid route key ${JSON.stringify(route)}`);\n const path = route\n .slice(space + 1)\n .split(\"/\")\n .map((segment) => {\n if (!segment.startsWith(\":\")) return segment;\n const value = params[segment.slice(1)];\n if (value === undefined || value === \"\")\n throw new Error(`@cicord/client: missing parameter ${segment.slice(1)} of ${route}`);\n // A value taken from the page URL must never climb out of the route (\"..\": another\n // route of the instance, another plugin, another API endpoint with the viewer's\n // cookies). Dots are encoded too, so no segment can be a dot-segment; the runtime\n // reads %2E as a literal dot.\n if (value === \".\" || value === \"..\")\n throw new Error(\n `@cicord/client: invalid parameter ${segment.slice(1)} of ${route}: ${value}`,\n );\n return encodeURIComponent(String(value)).replace(/\\./g, \"%2E\");\n })\n .join(\"/\");\n return [method, path];\n}\n","/**\n * Minimal Server-Sent Events client built on fetch (not EventSource), so it can send an\n * `Authorization` header, works in Node 24 and is easy to test with a mocked fetch.\n */\n\nexport interface ServerSentEvent {\n /** Event type (`event:` field), \"message\" by default. */\n event: string;\n data: string;\n id: string;\n}\n\nexport interface EventStreamOptions {\n onEvent: (event: ServerSentEvent) => void;\n /** Called on connection errors; the stream reconnects afterwards unless closed. */\n onError?: (error: unknown) => void;\n /** Called when a connection is (re)established. */\n onOpen?: () => void;\n /** Delay before reconnecting, in ms (updated by the server's `retry:` field). Default 2000. */\n retryMs?: number;\n /** Stop after the first disconnection instead of reconnecting. */\n once?: boolean;\n signal?: AbortSignal;\n}\n\nexport interface EventStream {\n close: () => void;\n /** Resolves when the stream is closed for good. */\n readonly closed: Promise<void>;\n}\n\nexport type StreamFetch = (url: string, init: RequestInit) => Promise<Response>;\n\n/** Incremental SSE parser (https://html.spec.whatwg.org/multipage/server-sent-events.html). */\nexport class SseParser {\n #buffer = \"\";\n #data: string[] = [];\n #event = \"\";\n #lastId = \"\";\n retry: number | undefined;\n readonly #emit: (event: ServerSentEvent) => void;\n\n constructor(emit: (event: ServerSentEvent) => void) {\n this.#emit = emit;\n }\n\n push(chunk: string): void {\n this.#buffer += chunk;\n let index: number;\n while ((index = this.#buffer.search(/\\r\\n|\\r|\\n/)) >= 0) {\n const line = this.#buffer.slice(0, index);\n const sep = this.#buffer.startsWith(\"\\r\\n\", index) ? 2 : 1;\n // A lone trailing \"\\r\" might be the first half of \"\\r\\n\": wait for more input.\n if (sep === 1 && this.#buffer[index] === \"\\r\" && index === this.#buffer.length - 1) break;\n this.#buffer = this.#buffer.slice(index + sep);\n this.#line(line);\n }\n }\n\n #line(line: string): void {\n if (line === \"\") {\n if (this.#data.length > 0) {\n this.#emit({\n event: this.#event || \"message\",\n data: this.#data.join(\"\\n\"),\n id: this.#lastId,\n });\n }\n this.#data = [];\n this.#event = \"\";\n return;\n }\n if (line.startsWith(\":\")) return;\n const colon = line.indexOf(\":\");\n const field = colon < 0 ? line : line.slice(0, colon);\n let value = colon < 0 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n switch (field) {\n case \"data\":\n this.#data.push(value);\n break;\n case \"event\":\n this.#event = value;\n break;\n case \"id\":\n if (!value.includes(\"\\0\")) this.#lastId = value;\n break;\n case \"retry\":\n if (/^\\d+$/.test(value)) this.retry = Number(value);\n break;\n }\n }\n\n get lastEventId(): string {\n return this.#lastId;\n }\n}\n\nexport function openEventStream(\n fetcher: StreamFetch,\n url: string,\n init: RequestInit,\n options: EventStreamOptions,\n): EventStream {\n const controller = new AbortController();\n const abort = (): void => controller.abort();\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n if (options.signal?.aborted) controller.abort();\n let retryMs = options.retryMs ?? 2000;\n let lastEventId = \"\";\n\n const run = async (): Promise<void> => {\n while (!controller.signal.aborted) {\n const parser = new SseParser(options.onEvent);\n try {\n const headers = new Headers(init.headers);\n headers.set(\"Accept\", \"text/event-stream\");\n if (lastEventId) headers.set(\"Last-Event-ID\", lastEventId);\n const response = await fetcher(url, { ...init, headers, signal: controller.signal });\n if (!response.ok || !response.body) {\n throw new Error(`event stream ${url}: HTTP ${response.status}`);\n }\n options.onOpen?.();\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n parser.push(value);\n lastEventId = parser.lastEventId;\n if (parser.retry !== undefined) retryMs = parser.retry;\n }\n if (!controller.signal.aborted)\n options.onError?.(new Error(`event stream ${url}: disconnected`));\n } catch (error) {\n if (controller.signal.aborted) break;\n options.onError?.(error);\n }\n if (options.once) break;\n await sleep(retryMs, controller.signal);\n }\n options.signal?.removeEventListener(\"abort\", abort);\n };\n\n const closed = run();\n return {\n close: abort,\n closed,\n };\n}\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) return resolve();\n const timer = setTimeout(done, ms);\n function done(): void {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n }\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n","import { CicordApiError } from \"./errors.ts\";\nimport { resolveRoute, type TypedPluginRoutes } from \"./routes.ts\";\nimport {\n openEventStream,\n type EventStream,\n type EventStreamOptions,\n type ServerSentEvent,\n} from \"./sse.ts\";\nimport type {\n AddRegistryRequest,\n AnalyticsCatalog,\n AnalyticsSeries,\n AnalyticsSeriesParams,\n AnalyticsSummary,\n AnalyticsSummaryQuery,\n AuditEntry,\n AuditQuery,\n InstallResult,\n InteractionResult,\n Items,\n Json,\n HistoryQuery,\n Me,\n Message,\n Page,\n PageParams,\n Plan,\n PluginInstance,\n PluginListParams,\n PortalMe,\n PortalServer,\n RemotePlanResult,\n RuntimeStatus,\n ServerAssetKind,\n ServerAssetResult,\n ServerDetail,\n ServerResources,\n SimCommand,\n SimCommandRequest,\n SimComponentRequest,\n SimModalRequest,\n SimSendMessageRequest,\n SimState,\n StoreDetail,\n StoreInstallRequest,\n StorePlugin,\n StorePluginParams,\n StoreSource,\n StoreSourceSummary,\n StoreUpdateRequest,\n StoreUpdateResult,\n StoreUpdateReview,\n SyncRecord,\n SyncResult,\n TokenSession,\n UninstallResult,\n UpdatePluginConfigRequest,\n User,\n WriteBackResult,\n WriteResult,\n} from \"./types.ts\";\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\n/**\n * How browser clients authenticate (https://cicord.dev/docs/reference/http-api/authentication/):\n * - `\"cookie\"` (default): the `cicord_session` cookie, for a portal served by the runtime or\n * on a same-site origin listed in `--cors-origin`;\n * - `\"token\"`: a bearer session token kept in a `TokenStore` and sent as `Authorization`,\n * for sites embedding the SDK on another origin (cicord.yaml `spec.portal.allowedOrigins`).\n */\nexport type AuthMode = \"cookie\" | \"token\";\n\n/** A token-mode session as stored by the client. */\nexport interface StoredSession {\n token: string;\n expiresAt: string;\n}\n\n/** Where token mode keeps the session token. */\nexport interface TokenStore {\n get(): StoredSession | null;\n set(session: StoredSession | null): void;\n}\n\n/** Keeps the token in memory (lost on reload; safest against XSS persistence). */\nexport function memoryTokenStore(): TokenStore {\n let value: StoredSession | null = null;\n return { get: () => value, set: (session) => void (value = session) };\n}\n\n/** Keeps the token in `localStorage` / `sessionStorage` (falls back to memory when unavailable). */\nexport function webStorageTokenStore(\n storage: Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\"> | undefined,\n key = \"cicord:session\",\n): TokenStore {\n const memory = memoryTokenStore();\n if (!storage) return memory;\n return {\n get: () => {\n try {\n const raw = storage.getItem(key);\n const parsed = raw ? (JSON.parse(raw) as Partial<StoredSession>) : null;\n return parsed && typeof parsed.token === \"string\" && typeof parsed.expiresAt === \"string\"\n ? { token: parsed.token, expiresAt: parsed.expiresAt }\n : null;\n } catch {\n return memory.get();\n }\n },\n set: (session) => {\n try {\n if (session) storage.setItem(key, JSON.stringify(session));\n else storage.removeItem(key);\n } catch {\n memory.set(session);\n }\n },\n };\n}\n\n/** True for absolute http(s) URLs (links from the server config, plugin data…). */\nexport function isSafeUrl(url: string): boolean {\n try {\n const u = new URL(url);\n return u.protocol === \"https:\" || u.protocol === \"http:\";\n } catch {\n return false;\n }\n}\n\nexport interface CicordClientOptions {\n /**\n * Origin (or origin + prefix) of the Cicord runtime, e.g. \"https://cicord.example.org\".\n * Default \"\": same origin as the page.\n */\n baseUrl?: string;\n /** API prefix. Default \"/api/v1\". */\n apiPath?: string;\n /** Auth prefix (https://cicord.dev/docs/reference/http-api/authentication/). Default \"/auth\". */\n authPath?: string;\n /** fetch implementation. Default: the global `fetch`, looked up at call time. */\n fetch?: FetchLike;\n /** Bearer token (runtime token) for machine clients; a function is called per request. */\n token?: string | (() => string | undefined | null);\n /** Extra headers sent with every request. */\n headers?: Record<string, string>;\n /**\n * Fetch credentials mode. Default \"include\" in cookie mode (session cookie, also\n * cross-origin with CORS), \"omit\" in token mode.\n */\n credentials?: RequestCredentials;\n /** Browser auth mode. Default \"cookie\". See `AuthMode`. */\n auth?: AuthMode;\n /**\n * Token mode: where the session token lives. \"local\" (default in browsers) and\n * \"session\" use Web Storage under `storageKey`; \"memory\" forgets it on reload.\n */\n tokenStore?: TokenStore | \"local\" | \"session\" | \"memory\";\n /** Web Storage key of token mode. Default \"cicord:session:<baseUrl>\". */\n storageKey?: string;\n}\n\nexport type Query = Record<string, string | number | boolean | undefined | null>;\n\nexport interface RequestOptions {\n query?: Query;\n /** JSON-serialisable body, or a raw body (Blob, ArrayBuffer, Uint8Array, string, FormData…). */\n body?: unknown;\n /** Content type for raw bodies. */\n contentType?: string;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\nexport interface CallOptions {\n signal?: AbortSignal;\n}\n\n/** Calls to the routes of one plugin instance (https://cicord.dev/docs/reference/http-api/portal/). */\nexport interface PluginRoutes {\n readonly server: string;\n readonly bot: string;\n readonly instance: string;\n /** Absolute URL of a route path. */\n url: (path: string, query?: Query) => string;\n request<T = Json>(method: string, path: string, options?: RequestOptions): Promise<T>;\n get<T = Json>(path: string, query?: Query, options?: CallOptions): Promise<T>;\n post<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n put<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n patch<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n delete<T = Json>(path: string, options?: CallOptions): Promise<T>;\n}\n\n/** Minimal Location / History used by the auth helpers (injectable for tests and SSR). */\nexport interface LocationLike {\n href: string;\n assign?: (url: string) => void;\n}\nexport interface HistoryLike {\n replaceState: (data: unknown, unused: string, url?: string | URL | null) => void;\n readonly state?: unknown;\n}\n\nexport interface ExchangeLinkTokenOptions {\n location?: LocationLike;\n history?: HistoryLike;\n /** Query parameter carrying the token. Default \"cicord_token\". */\n param?: string;\n /** Query parameter carrying the one-time code of a token-mode login. Default \"cicord_code\". */\n codeParam?: string;\n}\n\n/** Query parameters a login may leave in the URL (removed by `exchangeLinkToken`). */\nexport const LOGIN_PARAMS = [\"cicord_token\", \"cicord_code\"] as const;\n\nconst isRawBody = (body: unknown): boolean =>\n typeof body === \"string\" ||\n body instanceof ArrayBuffer ||\n ArrayBuffer.isView(body) ||\n (typeof Blob !== \"undefined\" && body instanceof Blob) ||\n (typeof FormData !== \"undefined\" && body instanceof FormData) ||\n (typeof URLSearchParams !== \"undefined\" && body instanceof URLSearchParams) ||\n (typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream);\n\nconst seg = (value: string): string => encodeURIComponent(value);\n\nfunction trimSlash(value: string): string {\n // A loop, not /\\/+$/: that regex backtracks quadratically on many slashes not at the end.\n let end = value.length;\n while (end > 0 && value[end - 1] === \"/\") end--;\n return value.slice(0, end);\n}\n\n/** Query string of a paged list (https://cicord.dev/docs/reference/http-api/ \"Data tables\"); empty values are left out. */\nfunction pageQuery(params: PageParams = {}): Query {\n return {\n q: params.q?.trim() || undefined,\n sort: params.sort || undefined,\n order: params.order,\n offset: params.offset,\n limit: params.limit,\n };\n}\n\n/** A Date as RFC 3339 UTC without milliseconds (strings pass through). */\nfunction rfc3339(value: Date | string | undefined): string | undefined {\n if (value === undefined || typeof value === \"string\") return value;\n return value.toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n}\n\nfunction withQuery(url: string, query?: Query): string {\n if (!query) return url;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== null) params.set(key, String(value));\n }\n const qs = params.toString();\n return qs ? `${url}${url.includes(\"?\") ? \"&\" : \"?\"}${qs}` : url;\n}\n\n/**\n * Typed client for the Cicord runtime HTTP API v1 (https://cicord.dev/docs/reference/http-api/). Framework-agnostic: works in\n * browsers, Node 24, workers. Every non-2xx response rejects with `CicordApiError`.\n */\nexport class CicordClient {\n readonly baseUrl: string;\n readonly apiPath: string;\n readonly authPath: string;\n readonly authMode: AuthMode;\n readonly #options: CicordClientOptions;\n readonly #store: TokenStore;\n readonly #listeners = new Set<() => void>();\n #pendingLink: Promise<Me> | undefined;\n\n constructor(options: CicordClientOptions = {}) {\n this.#options = options;\n this.baseUrl = trimSlash(options.baseUrl ?? \"\");\n this.apiPath = trimSlash(options.apiPath ?? \"/api/v1\");\n this.authPath = trimSlash(options.authPath ?? \"/auth\");\n this.authMode = options.auth ?? \"cookie\";\n this.#store = resolveStore(\n options.tokenStore,\n options.storageKey ?? `cicord:session:${this.baseUrl}`,\n );\n }\n\n // ─────────────────────────────────────────────────────────── token-mode session\n\n /** The token-mode session, or null (cookie mode, logged out or expired). */\n session(): StoredSession | null {\n if (this.authMode !== \"token\") return null;\n const s = this.#store.get();\n if (s && Date.parse(s.expiresAt) <= Date.now()) {\n this.#setSession(null);\n return null;\n }\n return s;\n }\n\n /** Called when the token-mode session changes (login, logout, expiry, revocation). */\n onSessionChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n #setSession(session: StoredSession | null): void {\n this.#store.set(session);\n for (const listener of this.#listeners) listener();\n }\n\n #adopt(session: TokenSession): Me {\n this.#setSession({ token: session.token, expiresAt: session.expiresAt });\n return session.me;\n }\n\n // ─────────────────────────────────────────────────────────── transport\n\n /** Absolute URL of a path relative to the runtime origin (e.g. \"/api/v1/me\"). */\n url(path: string, query?: Query): string {\n return withQuery(`${this.baseUrl}${path.startsWith(\"/\") ? path : `/${path}`}`, query);\n }\n\n /** URL of an API path (e.g. \"/me\" → \"/api/v1/me\"). */\n apiUrl(path: string, query?: Query): string {\n return this.url(`${this.apiPath}${path.startsWith(\"/\") ? path : `/${path}`}`, query);\n }\n\n #headers(extra?: Record<string, string>): Headers {\n const headers = new Headers(this.#options.headers);\n // CSRF protection (https://cicord.dev/docs/reference/http-api/authentication/): the runtime rejects cookie-authenticated\n // state-changing requests without this header.\n headers.set(\"X-Cicord-Request\", \"1\");\n const token =\n (typeof this.#options.token === \"function\" ? this.#options.token() : this.#options.token) ??\n this.session()?.token;\n if (token) headers.set(\"Authorization\", `Bearer ${token}`);\n for (const [k, v] of Object.entries(extra ?? {})) headers.set(k, v);\n return headers;\n }\n\n #fetch: FetchLike = (input, init) => {\n const impl = this.#options.fetch ?? globalThis.fetch;\n if (!impl) throw new Error(\"@cicord/client: no fetch implementation available\");\n return impl(input, init);\n };\n\n /** Sends a request to an absolute runtime path (no API prefix added). */\n async request<T = Json>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n const headers = this.#headers(options.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n let body: BodyInit | undefined;\n if (options.body !== undefined) {\n if (isRawBody(options.body)) {\n body = options.body as BodyInit;\n if (options.contentType) headers.set(\"Content-Type\", options.contentType);\n } else {\n body = JSON.stringify(options.body);\n headers.set(\"Content-Type\", options.contentType ?? \"application/json\");\n }\n }\n const init: RequestInit = {\n method: method.toUpperCase(),\n headers,\n credentials: this.#credentials(),\n ...(body === undefined ? {} : { body }),\n ...(options.signal ? { signal: options.signal } : {}),\n };\n\n let response: Response;\n try {\n response = await this.#fetch(this.url(path, options.query), init);\n } catch (cause) {\n if (options.signal?.aborted) throw cause;\n throw new CicordApiError({\n code: \"network\",\n status: 0,\n message: cause instanceof Error ? cause.message : \"network error\",\n cause,\n });\n }\n\n const parsed = await readBody(response);\n if (!response.ok) {\n // A revoked or expired token: forget it so the app shows the logged-out state.\n if (response.status === 401 && this.session()?.token && !this.#options.token)\n this.#setSession(null);\n throw CicordApiError.fromResponse(response.status, response.statusText, parsed);\n }\n return parsed as T;\n }\n\n #credentials(): RequestCredentials {\n return this.#options.credentials ?? (this.authMode === \"token\" ? \"omit\" : \"include\");\n }\n\n #api<T>(method: string, path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(method, `${this.apiPath}${path}`, options);\n }\n\n // ─────────────────────────────────────────────────────────── me & auth (§1, §2)\n\n /** `GET /api/v1/me`. Rejects with code `unauthenticated` when there is no session. */\n me(options?: CallOptions): Promise<Me> {\n return this.#api<Me>(\"GET\", \"/me\", options);\n }\n\n /** Like `me()`, but resolves `null` instead of rejecting when not logged in. */\n async meOrNull(options?: CallOptions): Promise<Me | null> {\n try {\n return await this.me(options);\n } catch (error) {\n if (error instanceof CicordApiError && error.code === \"unauthenticated\") return null;\n throw error;\n }\n }\n\n readonly auth = {\n /**\n * URL that starts the Discord OAuth2 login and comes back to `redirect` (a path on the\n * portal; default: the current page).\n */\n loginUrl: (redirect?: string): string => {\n if (this.authMode === \"token\") {\n // The runtime redirects back with ?cicord_code=… to this absolute URL, which must be\n // on an allowed origin (spec.portal.allowedOrigins or --cors-origin).\n const here = globalLocation()?.href;\n const target =\n redirect !== undefined && here ? new URL(redirect, here).toString() : (redirect ?? here);\n return this.url(`${this.authPath}/login`, { mode: \"token\", redirect: target });\n }\n const target = redirect ?? currentPath();\n return this.url(`${this.authPath}/login`, target ? { redirect: target } : undefined);\n },\n\n /** Navigates the browser to the login URL. */\n login: (redirect?: string, location: LocationLike | undefined = globalLocation()): void => {\n const url = this.auth.loginUrl(redirect);\n if (location?.assign) location.assign(url);\n else if (location) location.href = url;\n else throw new Error(\"@cicord/client: auth.login() needs a browser location\");\n },\n\n /** `POST /auth/link` with an explicit token (stores the session token in token mode). */\n link: async (token: string, options?: CallOptions): Promise<Me> => {\n if (this.authMode !== \"token\")\n return this.request<Me>(\"POST\", `${this.authPath}/link`, { body: { token }, ...options });\n return this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/link`, {\n body: { token, mode: \"token\" },\n ...options,\n }),\n );\n },\n\n /** Token mode: `POST /auth/token` — redeems the one-time code of an OAuth login. */\n redeem: async (code: string, options?: CallOptions): Promise<Me> =>\n this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/token`, {\n body: { code },\n ...options,\n }),\n ),\n\n /**\n * Reads `cicord_token` from the current URL (a signed link from `ctx.portal.link()`),\n * removes it from the address bar right away (so it is neither bookmarked nor sent twice),\n * and exchanges it for a session. Resolves `null` when the URL has no token.\n * Calls made while an exchange is in flight share it (safe under React StrictMode).\n */\n exchangeLinkToken: (options: ExchangeLinkTokenOptions = {}): Promise<Me | null> => {\n const location = options.location ?? globalLocation();\n const param = options.param ?? \"cicord_token\";\n const codeParam = options.codeParam ?? \"cicord_code\";\n if (!location) return Promise.resolve(null);\n const url = new URL(location.href);\n const token = url.searchParams.get(param);\n // A token-mode OAuth login comes back with a one-time code.\n const code = this.authMode === \"token\" ? url.searchParams.get(codeParam) : null;\n if (!token && !code) return this.#pendingLink ?? Promise.resolve(null);\n\n url.searchParams.delete(param);\n url.searchParams.delete(codeParam);\n const history = options.history ?? globalHistory();\n const clean = `${url.pathname}${url.search}${url.hash}`;\n if (history) history.replaceState(history.state ?? null, \"\", clean);\n else location.href = url.toString();\n\n const exchange = token ? this.auth.link(token) : this.auth.redeem(code as string);\n const pending = exchange.finally(() => {\n if (this.#pendingLink === pending) this.#pendingLink = undefined;\n });\n this.#pendingLink = pending;\n return pending;\n },\n\n /** `POST /auth/dev-login` — `cicord dev` only (stores the session token in token mode). */\n devLogin: async (userId: string, options?: CallOptions): Promise<Me> => {\n if (this.authMode !== \"token\")\n return this.request<Me>(\"POST\", `${this.authPath}/dev-login`, {\n body: { userId },\n ...options,\n });\n return this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/dev-login`, {\n body: { userId, mode: \"token\" },\n ...options,\n }),\n );\n },\n\n /** `POST /auth/logout` (token mode: revokes the token and forgets it). */\n logout: async (options?: CallOptions): Promise<void> => {\n try {\n await this.request<void>(\"POST\", `${this.authPath}/logout`, options);\n } finally {\n if (this.authMode === \"token\") this.#setSession(null);\n }\n },\n };\n\n // ─────────────────────────────────────────────────────────── portal (§6)\n\n readonly portal = {\n /** `GET /portal/servers` — servers with a portal. */\n servers: async (options?: CallOptions): Promise<PortalServer[]> =>\n (await this.#api<Items<PortalServer>>(\"GET\", \"/portal/servers\", options)).items.map((s) =>\n this.#absolutize(s),\n ),\n /** `GET /portal/{server}`. */\n server: async (server: string, options?: CallOptions): Promise<PortalServer> =>\n this.#absolutize(await this.#api<PortalServer>(\"GET\", `/portal/${seg(server)}`, options)),\n /** `GET /portal/{server}/me` — the viewer as a member of the server. */\n me: (server: string, options?: CallOptions): Promise<PortalMe> =>\n this.#api<PortalMe>(\"GET\", `/portal/${seg(server)}/me`, options),\n };\n\n /** Runtime-relative image URLs (logo, banner) resolved against `baseUrl` (embedded portals). */\n #absolutize(server: PortalServer): PortalServer {\n if (!this.baseUrl) return server;\n const abs = (u: string | undefined) => (u && u.startsWith(\"/\") ? this.url(u) : u);\n return {\n ...server,\n theme: { ...server.theme, logo: abs(server.theme.logo) ?? \"\" },\n banner: abs(server.banner) ?? \"\",\n };\n }\n\n /** Routes of a plugin instance: `/api/v1/portal/{server}/plugins/{bot}/{instance}/{path}`. */\n plugin(server: string, bot: string, instance: string): PluginRoutes {\n const prefix = `${this.apiPath}/portal/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`;\n const full = (path: string): string => `${prefix}${path.startsWith(\"/\") ? path : `/${path}`}`;\n const request = <T = Json>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<T> => this.request<T>(method, full(path), options);\n const withBody =\n (method: string) =>\n <T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T> =>\n request<T>(method, path, { ...options, ...(body === undefined ? {} : { body }) });\n return {\n server,\n bot,\n instance,\n url: (path, query) => this.url(full(path), query),\n request,\n get: <T = Json>(path: string, query?: Query, options?: CallOptions) =>\n request<T>(\"GET\", path, { ...options, ...(query ? { query } : {}) }),\n post: withBody(\"POST\"),\n put: withBody(\"PUT\"),\n patch: withBody(\"PATCH\"),\n delete: <T = Json>(path: string, options?: CallOptions) =>\n request<T>(\"DELETE\", path, options),\n };\n }\n\n /**\n * Typed calls to the routes of an instance of plugin `plugin` (types from the generated\n * `src/cicord-routes.d.ts`, see `PluginRouteRegistry`). `at` is the instance, typically\n * found in `PortalServer.plugins` by plugin name.\n */\n routes<N extends string>(\n plugin: N,\n server: string,\n at: { bot: string; instance: string },\n ): TypedPluginRoutes<N> {\n const routes = this.plugin(server, at.bot, at.instance);\n type Loose = { params?: Record<string, string>; query?: object; body?: unknown };\n return {\n plugin,\n server,\n bot: at.bot,\n instance: at.instance,\n // async: an invalid parameter rejects like any failed call.\n call: (async (route: string, options: Loose & RequestOptions = {}) => {\n const { params, query, body, ...rest } = options;\n const [method, path] = resolveRoute(route, params);\n return routes.request(method, path, {\n ...rest,\n ...(query ? { query } : {}),\n ...(body === undefined ? {} : { body }),\n });\n }) as TypedPluginRoutes<N>[\"call\"],\n url: ((route: string, options: Loose = {}) => {\n const [, path] = resolveRoute(route, options.params);\n return routes.url(path, options.query as Query | undefined);\n }) as TypedPluginRoutes<N>[\"url\"],\n };\n }\n\n // ─────────────────────────────────────────────────────────── admin (§3–§5)\n\n readonly admin = {\n /** `GET /status` (admin, moderator) — visible servers only. */\n status: (options?: CallOptions): Promise<RuntimeStatus> =>\n this.#api<RuntimeStatus>(\"GET\", \"/status\", options),\n /** `GET /history?limit=&target=` (admin, moderator), newest first. */\n history: async (query: HistoryQuery = {}, options?: CallOptions): Promise<SyncRecord[]> =>\n (\n await this.#api<Items<SyncRecord>>(\"GET\", \"/history\", {\n query: { limit: query.limit, target: query.target },\n ...options,\n })\n ).items,\n /** `GET /servers/{server}` (moderator). */\n server: (server: string, options?: CallOptions): Promise<ServerDetail> =>\n this.#api<ServerDetail>(\"GET\", `/servers/${seg(server)}`, options),\n /** `GET /servers/{server}/resources` (moderator) — roles, categories, channels for pickers. */\n resources: (server: string, options?: CallOptions): Promise<ServerResources> =>\n this.#api<ServerResources>(\"GET\", `/servers/${seg(server)}/resources`, options),\n /** `GET /servers/{server}/plan` (admin). */\n plan: (server: string, options?: CallOptions): Promise<Plan> =>\n this.#api<Plan>(\"GET\", `/servers/${seg(server)}/plan`, options),\n /** `POST /servers/{server}/sync` (admin) — reconcile now. */\n sync: (server: string, options?: CallOptions): Promise<SyncResult> =>\n this.#api<SyncResult>(\"POST\", `/servers/${seg(server)}/sync`, options),\n /** `GET /servers/{server}/audit?before=&limit=` (moderator), newest first. */\n audit: async (\n server: string,\n query: AuditQuery = {},\n options?: CallOptions,\n ): Promise<AuditEntry[]> =>\n (\n await this.#api<Items<AuditEntry>>(\"GET\", `/servers/${seg(server)}/audit`, {\n query: { before: query.before, limit: query.limit },\n ...options,\n })\n ).items,\n /** `GET /servers/{server}/plugins` (moderator): every instance. */\n plugins: async (server: string, options?: CallOptions): Promise<PluginInstance[]> =>\n (await this.#api<Items<PluginInstance>>(\"GET\", `/servers/${seg(server)}/plugins`, options))\n .items,\n /**\n * `GET /servers/{server}/plugins?q&sort&order&offset&limit` (moderator): one page of\n * instances. Without `limit` the page holds every instance. Rejects with `invalid` (400)\n * on an unknown sort key.\n */\n pluginsPage: (\n server: string,\n params: PluginListParams = {},\n options?: CallOptions,\n ): Promise<Page<PluginInstance>> =>\n this.#api<Page<PluginInstance>>(\"GET\", `/servers/${seg(server)}/plugins`, {\n query: { ...pageQuery(params), updates: params.updates },\n ...options,\n }),\n /** `GET /servers/{server}/plugins/{bot}/{instance}` (moderator). Rejects with `not_found`. */\n plugin: (\n server: string,\n bot: string,\n instance: string,\n options?: CallOptions,\n ): Promise<PluginInstance> =>\n this.#api<PluginInstance>(\n \"GET\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`,\n options,\n ),\n /**\n * `DELETE /servers/{server}/plugins/{bot}/{instance}` (admin): uninstalls the instance from\n * the server (plugin data is kept). Rejects with `invalid` + `diagnostics` (422, something\n * depends on it), `conflict` (409), `forbidden` (403) or `not_found` (404).\n */\n uninstallPlugin: (\n server: string,\n bot: string,\n instance: string,\n options?: CallOptions,\n ): Promise<UninstallResult> =>\n this.#api<UninstallResult>(\n \"DELETE\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`,\n options,\n ),\n /**\n * `PUT /servers/{server}/plugins/{bot}/{instance}/config` (moderator, field-restricted).\n * Rejects with `forbidden` (403), `invalid` + `diagnostics` (422) or `conflict` (409).\n */\n updatePluginConfig: (\n server: string,\n bot: string,\n instance: string,\n request: UpdatePluginConfigRequest,\n options?: CallOptions,\n ): Promise<WriteBackResult> =>\n this.#api<WriteBackResult>(\n \"PUT\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}/config`,\n {\n body: request,\n ...options,\n },\n ),\n /**\n * `PUT /servers/{server}/assets/{kind}` (admin) — uploads the server icon, banner or\n * splash (PNG, JPEG, GIF, WebP ≤ 8 MiB) into the repository and points\n * `spec.profile.<kind>` at it. Rejects with `unsupported_media_type` (415),\n * `too_large` (413) or `conflict` (409, when `revision` is stale).\n */\n uploadServerAsset: (\n server: string,\n kind: ServerAssetKind,\n image: Blob | ArrayBuffer | Uint8Array,\n options: CallOptions & { revision?: string } = {},\n ): Promise<ServerAssetResult> => {\n const { revision, ...rest } = options;\n return this.#api<ServerAssetResult>(\"PUT\", `/servers/${seg(server)}/assets/${seg(kind)}`, {\n body: image,\n contentType: image instanceof Blob && image.type ? image.type : \"application/octet-stream\",\n ...(revision ? { query: { revision } } : {}),\n ...rest,\n });\n },\n /** URL of the image declared in `spec.profile.<kind>` (moderator), for previews. */\n serverAssetUrl: (server: string, kind: ServerAssetKind): string =>\n this.url(`${this.apiPath}/servers/${seg(server)}/assets/${seg(kind)}`),\n };\n\n // ─────────────────────────────────────────────────────────── analytics\n\n /**\n * Server activity analytics (moderator and admin of the server). Times are UTC. Every call\n * rejects with `analytics_disabled` (404) when the runtime has no analytics store.\n */\n readonly analytics = {\n /**\n * `GET /servers/{server}/analytics/summary?period=` or `?from=&to=`: headline numbers\n * compared with the previous period of the same length, rankings and the weekday × hour\n * heatmap. `query` is a preset period (`\"30d\"`, `{ period: \"30d\" }`) or a custom range\n * (`{ from, to }`, RFC 3339 or Dates). Rejects with `invalid` (400) for a range shorter\n * than an hour, longer than 400 days or starting in the future.\n */\n summary: (\n server: string,\n query: AnalyticsSummaryQuery = \"30d\",\n options?: CallOptions,\n ): Promise<AnalyticsSummary> =>\n this.#api<AnalyticsSummary>(\"GET\", `/servers/${seg(server)}/analytics/summary`, {\n query:\n typeof query === \"string\"\n ? { period: query }\n : \"period\" in query\n ? { period: query.period }\n : { from: rfc3339(query.from), to: rfc3339(query.to) },\n ...options,\n }),\n /**\n * `GET /servers/{server}/analytics/series?metrics=&from=&to=&step=[&dim=][&top=]`. Rejects\n * with `invalid` (400) for an unknown metric or step, more than 400 days or more than 2000\n * points per series.\n */\n series: (\n server: string,\n params: AnalyticsSeriesParams,\n options?: CallOptions,\n ): Promise<AnalyticsSeries> =>\n this.#api<AnalyticsSeries>(\"GET\", `/servers/${seg(server)}/analytics/series`, {\n query: {\n metrics: params.metrics.join(\",\"),\n from: rfc3339(params.from),\n to: rfc3339(params.to),\n step: params.step,\n dim: params.dim,\n top: params.top,\n },\n ...options,\n }),\n /** `GET /servers/{server}/analytics/catalog`: every metric and whether it is collected. */\n catalog: (server: string, options?: CallOptions): Promise<AnalyticsCatalog> =>\n this.#api<AnalyticsCatalog>(\"GET\", `/servers/${seg(server)}/analytics/catalog`, options),\n };\n\n // ─────────────────────────────────────────────────────────── store (§11)\n\n readonly store = {\n /** `GET /store` (admin of a server): every source, `cicord` first, then the registries. */\n list: async (options?: CallOptions): Promise<StoreSource[]> =>\n (await this.#api<{ sources: StoreSource[] }>(\"GET\", \"/store\", options)).sources,\n /**\n * `GET /store?summary=1` (admin of a server): every source with its plugin count, without\n * the plugins (`summary: false` is `list()`).\n */\n sources: async (\n { summary = true }: { summary?: boolean } = {},\n options?: CallOptions,\n ): Promise<StoreSourceSummary[]> =>\n (\n await this.#api<{ sources: StoreSourceSummary[] }>(\"GET\", \"/store\", {\n ...(summary ? { query: { summary: 1 } } : {}),\n ...options,\n })\n ).sources,\n /**\n * `GET /store/plugins` (admin of a server): one page of the plugins of every source,\n * filtered by `source`, `trust` and `installed` (default limit 50).\n */\n plugins: (params: StorePluginParams = {}, options?: CallOptions): Promise<Page<StorePlugin>> =>\n this.#api<Page<StorePlugin>>(\"GET\", \"/store/plugins\", {\n query: {\n ...pageQuery(params),\n source: params.source || undefined,\n trust: params.trust,\n installed: params.installed,\n updates: params.updates,\n },\n ...options,\n }),\n /** `POST /store/refresh` (admin of a server): refetches every registry index. */\n refresh: async (options?: CallOptions): Promise<StoreSource[]> =>\n (await this.#api<{ sources: StoreSource[] }>(\"POST\", \"/store/refresh\", options)).sources,\n /**\n * `GET /store/{source}/{plugin}` (admin of a server): the latest version and what it\n * requests. Rejects with `not_found` (404) or `registry_unavailable` (502).\n */\n detail: (source: string, plugin: string, options?: CallOptions): Promise<StoreDetail> =>\n this.#api<StoreDetail>(\"GET\", `/store/${seg(source)}/${seg(plugin)}`, options),\n /**\n * `POST /servers/{server}/store/install` (admin of `server`). Rejects with `changed`,\n * `confirmation_required`, `intents`, `conflict` (409) or `invalid` + `diagnostics` (422).\n */\n install: (\n server: string,\n request: StoreInstallRequest,\n options?: CallOptions,\n ): Promise<InstallResult> =>\n this.#api<InstallResult>(\"POST\", `/servers/${seg(server)}/store/install`, {\n body: request,\n ...options,\n }),\n /**\n * `GET /store/{source}/{plugin}/update` (admin of a server): the latest version, what is\n * installed and the permission diff. Rejects with `not_installed` / `not_found` (404) or\n * `registry_unavailable` (502).\n */\n updateReview: (\n source: string,\n plugin: string,\n options?: CallOptions,\n ): Promise<StoreUpdateReview> =>\n this.#api<StoreUpdateReview>(\"GET\", `/store/${seg(source)}/${seg(plugin)}/update`, options),\n /**\n * `POST /store/{source}/{plugin}/update` (admin of every server where the plugin runs):\n * updates every instance in one write-back. Rejects with `changed`, `confirmation_required`,\n * `modified`, `up_to_date`, `intents`, `conflict` (409), `invalid` + `diagnostics` (422) or\n * `forbidden` (403, not admin on one of the servers).\n */\n update: (\n source: string,\n plugin: string,\n request: StoreUpdateRequest,\n options?: CallOptions,\n ): Promise<StoreUpdateResult> =>\n this.#api<StoreUpdateResult>(\"POST\", `/store/${seg(source)}/${seg(plugin)}/update`, {\n body: request,\n ...options,\n }),\n };\n\n readonly registries = {\n /**\n * `POST /registries` (bearer, or admin of every server): adds a registry to\n * `cicord.yaml`. Rejects with `invalid` (400 bad name / URL, 422 unreachable index) or\n * `forbidden` (403).\n */\n add: (request: AddRegistryRequest, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"POST\", \"/registries\", { body: request, ...options }),\n /** `DELETE /registries/{name}`. Rejects with `not_found` (404) or `in_use` (409). */\n remove: (name: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"DELETE\", `/registries/${seg(name)}`, options),\n /**\n * `PUT /registries/{name}/token`: stores the access token of a private registry (checked\n * against its index first). Rejects with `invalid` (422, the index cannot be read with it),\n * `not_found` (404) or `unavailable` (503, no secret store).\n */\n setToken: (name: string, token: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"PUT\", `/registries/${seg(name)}/token`, {\n body: { token },\n ...options,\n }),\n /** `DELETE /registries/{name}/token`: makes the registry public again. */\n removeToken: (name: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"DELETE\", `/registries/${seg(name)}/token`, options),\n };\n\n // ─────────────────────────────────────────────────────────── machine (§7)\n\n readonly machine = {\n /** `POST /api/v1/sync` — fetch the source now and sync (202). */\n sync: async (options?: CallOptions): Promise<void> => {\n await this.#api<void>(\"POST\", \"/sync\", options);\n },\n /** `POST /api/v1/plan` with a `.tar.gz` of a repository. */\n plan: (\n archive: Blob | ArrayBuffer | Uint8Array,\n options?: CallOptions,\n ): Promise<RemotePlanResult> =>\n this.#api<RemotePlanResult>(\"POST\", \"/plan\", {\n body: archive,\n contentType: \"application/gzip\",\n ...options,\n }),\n /** `GET /healthz` → true when the process is up. */\n healthz: (options?: CallOptions): Promise<boolean> => this.#probe(\"/healthz\", options),\n /** `GET /readyz` → true once a revision is active. */\n readyz: (options?: CallOptions): Promise<boolean> => this.#probe(\"/readyz\", options),\n };\n\n async #probe(path: string, options?: CallOptions): Promise<boolean> {\n try {\n await this.request(\"GET\", path, {\n ...options,\n headers: { Accept: \"text/plain, application/json\" },\n });\n return true;\n } catch (error) {\n if (error instanceof CicordApiError) return false;\n throw error;\n }\n }\n\n // ─────────────────────────────────────────────────────────── simulator (§8)\n\n readonly sim = {\n /** `GET /sim/state`. */\n state: (options?: CallOptions): Promise<SimState> =>\n this.#api<SimState>(\"GET\", \"/sim/state\", options),\n /** `POST /sim/users` — creates a simulated user. */\n createUser: (username: string, options?: CallOptions): Promise<User> =>\n this.#api<User>(\"POST\", \"/sim/users\", { body: { username }, ...options }),\n /** `POST /sim/servers/{id}/members` — the user joins the server. */\n join: async (serverId: string, userId: string, options?: CallOptions): Promise<void> => {\n await this.#api<void>(\"POST\", `/sim/servers/${seg(serverId)}/members`, {\n body: { userId },\n ...options,\n });\n },\n /** `DELETE /sim/servers/{id}/members/{userId}` — the user leaves. */\n leave: async (serverId: string, userId: string, options?: CallOptions): Promise<void> => {\n await this.#api<void>(\n \"DELETE\",\n `/sim/servers/${seg(serverId)}/members/${seg(userId)}`,\n options,\n );\n },\n /** `GET /sim/channels/{id}/messages?limit=` — oldest first. */\n messages: async (\n channelId: string,\n query: { limit?: number } = {},\n options?: CallOptions,\n ): Promise<Message[]> =>\n (\n await this.#api<Items<Message>>(\"GET\", `/sim/channels/${seg(channelId)}/messages`, {\n query,\n ...options,\n })\n ).items,\n /** `GET /sim/users/{id}/dms?limit=` — DMs received by the user from bots, oldest first. */\n dms: async (\n userId: string,\n { limit, ...options }: CallOptions & { limit?: number } = {},\n ): Promise<Message[]> =>\n (\n await this.#api<Items<Message>>(\"GET\", `/sim/users/${seg(userId)}/dms`, {\n query: { limit },\n ...options,\n })\n ).items,\n /** `POST /sim/messages`. */\n sendMessage: (request: SimSendMessageRequest, options?: CallOptions): Promise<Message> =>\n this.#api<Message>(\"POST\", \"/sim/messages\", { body: request, ...options }),\n /** `POST /sim/commands` — runs a slash command (waits up to 5 s for the answer). */\n command: (request: SimCommandRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/commands\", {\n body: { options: {}, ...request },\n ...options,\n }),\n /** `POST /sim/components` — clicks a button / picks select values. */\n component: (request: SimComponentRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/components\", {\n body: { values: [], ...request },\n ...options,\n }),\n /**\n * `POST /sim/modals` — submits a modal shown by a previous interaction\n * (`InteractionResult.modal`); `fields` maps text input ids to values.\n */\n modal: (request: SimModalRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/modals\", { body: request, ...options }),\n /** `GET /sim/commands?serverId=` — registered commands (all simulated servers by default). */\n commands: async (serverId?: string, options?: CallOptions): Promise<SimCommand[]> =>\n (\n await this.#api<Items<SimCommand>>(\"GET\", \"/sim/commands\", {\n query: { serverId },\n ...options,\n })\n ).items,\n /**\n * Subscribes to `GET /sim/events` (SSE). `onChange` fires for every `event: change`\n * (a hint to refresh); reconnects automatically. Call `close()` to stop.\n */\n subscribe: (\n onChange: (event: ServerSentEvent) => void,\n options: Omit<EventStreamOptions, \"onEvent\"> = {},\n ): EventStream =>\n this.events(\"/sim/events\", {\n ...options,\n onEvent: (e) => e.event === \"change\" && onChange(e),\n }),\n };\n\n /** Opens a Server-Sent Events stream on an API path (fetch-based, sends credentials/token). */\n events(path: string, options: EventStreamOptions): EventStream {\n return openEventStream(\n this.#fetch,\n this.apiUrl(path),\n {\n method: \"GET\",\n headers: this.#headers(),\n credentials: this.#credentials(),\n },\n options,\n );\n }\n}\n\nasync function readBody(response: Response): Promise<Json | string | undefined> {\n if (response.status === 204 || response.status === 205 || response.status === 304)\n return undefined;\n const text = await response.text();\n if (text === \"\") return undefined;\n const type = response.headers.get(\"Content-Type\") ?? \"\";\n if (type.includes(\"json\") || /^\\s*[[{]/.test(text)) {\n try {\n return JSON.parse(text) as Json;\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction resolveStore(store: CicordClientOptions[\"tokenStore\"], key: string): TokenStore {\n if (store && typeof store === \"object\") return store;\n if (store === \"memory\") return memoryTokenStore();\n const storage = (name: \"localStorage\" | \"sessionStorage\") => {\n try {\n return (globalThis as Record<string, unknown>)[name] as Storage | undefined;\n } catch {\n return undefined;\n }\n };\n return webStorageTokenStore(\n storage(store === \"session\" ? \"sessionStorage\" : \"localStorage\"),\n key,\n );\n}\n\nfunction globalLocation(): LocationLike | undefined {\n return typeof location === \"undefined\" ? undefined : location;\n}\n\nfunction globalHistory(): HistoryLike | undefined {\n return typeof history === \"undefined\" ? undefined : history;\n}\n\nfunction currentPath(): string | undefined {\n const loc = globalLocation();\n if (!loc) return undefined;\n const url = new URL(loc.href);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\n/** Creates a client. See `CicordClientOptions`. */\nexport function createCicordClient(options?: CicordClientOptions): CicordClient {\n return new CicordClient(options);\n}\n","/**\n * Contract of the `onboarding` plugin's portal routes\n * (examples/basic/plugins/onboarding — `GET /steps`, `POST /complete`).\n */\nimport type { PluginRoutes } from \"./client.ts\";\n\n/** A role a member can pick, resolved by the plugin from the server's roles. */\nexport interface OnboardingOption {\n /** Role key (servers/<server>.yaml). Used in answers. */\n role: string;\n /** Label shown in the portal (config `label`, defaults to the role name). */\n label: string;\n emoji: string;\n description: string;\n /** Discord role name and color (\"\" when the role has none). */\n name: string;\n color: string;\n}\n\nexport interface OnboardingStep {\n id: string;\n title: string;\n description: string;\n /** Several options may be selected. */\n multiple: boolean;\n /** At least one option must be selected. */\n required: boolean;\n options: OnboardingOption[];\n /** Role keys of this step the member currently has. */\n selected: string[];\n}\n\nexport interface OnboardingRole {\n key: string;\n id: string;\n name: string;\n color: string;\n}\n\n/** `GET /steps` */\nexport interface OnboardingSteps {\n title: string;\n intro: string;\n steps: OnboardingStep[];\n /** Role given when the flow is completed, if configured. */\n completedRole: OnboardingRole | null;\n completed: boolean;\n completedAt: string | null;\n}\n\n/** Answers: step id → selected role keys. */\nexport type OnboardingAnswers = Record<string, string[]>;\n\n/** `POST /complete` body. */\nexport interface OnboardingCompleteRequest {\n answers: OnboardingAnswers;\n}\n\n/** `POST /complete` response (200). Errors use the API error shape (`invalid`, 422/400). */\nexport interface OnboardingCompleteResponse {\n completed: true;\n completedAt: string;\n /** Member roles after the update. */\n roles: OnboardingRole[];\n /** Role keys added / removed by this call. */\n added: string[];\n removed: string[];\n /** Success message configured by the server. */\n message: string;\n}\n\n/** Typed wrapper over the onboarding plugin routes. */\nexport function onboardingApi(routes: PluginRoutes) {\n return {\n steps: (init?: { signal?: AbortSignal }) =>\n routes.get<OnboardingSteps>(\"/steps\", undefined, init),\n complete: (answers: OnboardingAnswers, init?: { signal?: AbortSignal }) =>\n routes.post<OnboardingCompleteResponse>(\n \"/complete\",\n { answers } satisfies OnboardingCompleteRequest,\n init,\n ),\n };\n}\n\nexport type OnboardingApi = ReturnType<typeof onboardingApi>;\n","/**\n * Contracts of the showcase plugins' portal routes (examples/showcase): `tickets` and\n * `levels`. They illustrate typing a plugin's routes on top of `client.plugin(...)`; extra\n * fields sent by a plugin are kept as is.\n */\nimport type { CallOptions, PluginRoutes } from \"./client.ts\";\n\nexport type TicketStatus = \"open\" | \"closed\";\n\nexport interface Ticket {\n /** Ticket number, as a string. */\n id: string;\n subject: string;\n status: TicketStatus;\n author: { id: string; displayName: string };\n createdAt: string;\n}\n\n/** tickets `GET /tickets` (moderator), newest first. */\nexport interface TicketList {\n items: Ticket[];\n}\n\nexport interface LeaderboardEntry {\n /** From 1. */\n rank: number;\n userId: string;\n displayName: string;\n avatarUrl: string | null;\n level: number;\n xp: number;\n}\n\n/** levels `GET /leaderboard` (public). */\nexport interface Leaderboard {\n items: LeaderboardEntry[];\n}\n\n/** Typed wrapper over the `tickets` plugin routes. */\nexport function ticketsApi(routes: PluginRoutes) {\n return {\n list: (query: { status?: TicketStatus } = {}, options?: CallOptions) =>\n routes.get<TicketList>(\"/tickets\", query, options),\n };\n}\n\n/** Typed wrapper over the `levels` plugin routes. */\nexport function levelsApi(routes: PluginRoutes) {\n return {\n leaderboard: (query: { limit?: number } = {}, options?: CallOptions) =>\n routes.get<Leaderboard>(\"/leaderboard\", query, options),\n /** levels `GET /me` (member): the viewer's own entry (shape owned by the plugin). */\n me: <T = LeaderboardEntry>(options?: CallOptions) => routes.get<T>(\"/me\", undefined, options),\n };\n}\n"],"m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c,QAAsB;CAClD,OAAO;EACL,QAAQ,SACN,OAAO,IAAqB,UAAU,KAAA,GAAW,IAAI;EACvD,WAAW,SAA4B,SACrC,OAAO,KACL,aACA,EAAE,QAAQ,GACV,IACF;CACJ;AACF;;;AC5CA,SAAgB,WAAW,QAAsB;CAC/C,OAAO,EACL,OAAO,QAAmC,CAAC,GAAG,YAC5C,OAAO,IAAgB,YAAY,OAAO,OAAO,EACrD;AACF;;AAGA,SAAgB,UAAU,QAAsB;CAC9C,OAAO;EACL,cAAc,QAA4B,CAAC,GAAG,YAC5C,OAAO,IAAiB,gBAAgB,OAAO,OAAO;;EAExD,KAA2B,YAA0B,OAAO,IAAO,OAAO,KAAA,GAAW,OAAO;CAC9F;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/errors.ts","../src/routes.ts","../src/sse.ts","../src/client.ts","../src/onboarding.ts","../src/showcase.ts"],"sourcesContent":["import type { ApiErrorCode, Diagnostic, Json } from \"./types.ts\";\n\nconst CODE_BY_STATUS: Record<number, ApiErrorCode> = {\n 400: \"invalid\",\n 401: \"unauthenticated\",\n 403: \"forbidden\",\n 404: \"not_found\",\n 405: \"invalid\",\n 409: \"conflict\",\n 413: \"invalid\",\n 415: \"invalid\",\n 421: \"forbidden\",\n 422: \"invalid\",\n 500: \"internal\",\n 503: \"unavailable\",\n};\n\n/** Error code for a status when the body carries none (plain-text 404s, proxies…). */\nexport function codeForStatus(status: number): ApiErrorCode {\n return CODE_BY_STATUS[status] ?? (status >= 500 ? \"internal\" : `http_${status}`);\n}\n\n/**\n * Error raised for every non-2xx response of the runtime API (and for network failures,\n * with `status: 0` and code `\"network\"`).\n */\nexport class CicordApiError extends Error {\n /** `snake_case` error code from the body (`{\"error\": {\"code\"}}`), or derived from the status. */\n readonly code: ApiErrorCode;\n /** HTTP status, 0 for network errors. */\n readonly status: number;\n /** Validation diagnostics (422 on config updates, `POST /plan`). */\n readonly diagnostics: Diagnostic[];\n /** Parsed response body (JSON or text), when any. */\n readonly body: Json | string | undefined;\n /** How to fix it, when the runtime explains the error (plan / sync failures). */\n readonly hint: string | undefined;\n /** Raw technical text behind `message`, when the runtime explains the error. */\n readonly details: string | undefined;\n /** Humanized error code (`HumanErrorCode`), when the runtime explains the error. */\n readonly reason: string | undefined;\n\n constructor(init: {\n code: ApiErrorCode;\n status: number;\n message: string;\n diagnostics?: Diagnostic[];\n body?: Json | string;\n cause?: unknown;\n hint?: string | undefined;\n details?: string | undefined;\n reason?: string | undefined;\n }) {\n super(init.message, init.cause === undefined ? undefined : { cause: init.cause });\n this.name = \"CicordApiError\";\n this.code = init.code;\n this.status = init.status;\n this.diagnostics = init.diagnostics ?? [];\n this.body = init.body;\n this.hint = init.hint;\n this.details = init.details;\n this.reason = init.reason;\n }\n\n /** Builds the error from a response status and its (already parsed) body. */\n static fromResponse(\n status: number,\n statusText: string,\n body: Json | string | undefined,\n ): CicordApiError {\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n const error = (body as { error?: unknown }).error;\n if (error && typeof error === \"object\" && !Array.isArray(error)) {\n const e = error as {\n code?: unknown;\n message?: unknown;\n diagnostics?: unknown;\n hint?: unknown;\n details?: unknown;\n reason?: unknown;\n };\n const str = (v: unknown) => (typeof v === \"string\" && v ? v : undefined);\n return new CicordApiError({\n code: typeof e.code === \"string\" && e.code ? e.code : codeForStatus(status),\n status,\n message:\n typeof e.message === \"string\" && e.message ? e.message : statusText || `HTTP ${status}`,\n diagnostics: Array.isArray(e.diagnostics) ? e.diagnostics : [],\n body,\n hint: str(e.hint),\n details: str(e.details),\n reason: str(e.reason),\n });\n }\n }\n const text = typeof body === \"string\" ? body.trim() : \"\";\n return new CicordApiError({\n code: codeForStatus(status),\n status,\n message: text && text.length <= 200 ? text : statusText || `HTTP ${status}`,\n ...(body === undefined ? {} : { body }),\n });\n }\n}\n\nexport function isCicordApiError(error: unknown, code?: ApiErrorCode): error is CicordApiError {\n return error instanceof CicordApiError && (code === undefined || error.code === code);\n}\n","/**\n * Typed plugin routes. A portal learns the routes of the plugins of its repository from\n * `src/cicord-routes.d.ts`, generated by `cicord portal typegen` (and `cicord portal build`): a\n * module augmentation of `PluginRouteRegistry`, keyed by plugin name then route key, with\n * the access level and the query, body and response types declared by the plugin's route\n * contract (plugin.yaml `spec.routes.types`).\n *\n * ```ts\n * const levels = client.routes(\"levels\", server.key, instance); // instance: { bot, instance }\n * const board = await levels.call(\"GET /leaderboard\", { query: { limit: 10 } }); // board.items…\n * const poll = await client.routes(\"polls\", server.key, p).call(\"GET /polls/:id\", { params: { id } });\n * ```\n */\nimport type { CallOptions, Query } from \"./client.ts\";\nimport type {\n OnboardingAnswers,\n OnboardingCompleteResponse,\n OnboardingSteps,\n} from \"./onboarding.ts\";\nimport type { Leaderboard, TicketList, TicketStatus } from \"./showcase.ts\";\nimport type { Json } from \"./types.ts\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n/** \"<METHOD> /path\", `:name` segments being parameters: \"GET /polls/:id\". */\nexport type RouteKey = `${RouteMethod} /${string}`;\n/** Access level of a route (`definePlugin({ routes })`). */\nexport type RouteAccess = \"public\" | \"member\" | \"moderator\" | \"admin\";\n\n/** `{ id: string }` for \"GET /polls/:id\". */\nexport type RouteParams<K extends string> = K extends `${string}/:${infer Rest}`\n ? Rest extends `${infer Name}/${infer Tail}`\n ? { [P in Name]: string } & RouteParams<`/${Tail}`>\n : { [P in Rest]: string }\n : {};\n\n/** A route whose plugin declares no types: any query and body, a JSON response. */\nexport interface UntypedRoute {\n query?: Query;\n body?: unknown;\n response: Json;\n}\n\n/**\n * One route of `PluginRouteRegistry`: its access level and, when the plugin's contract\n * `Contract` declares route `K`, its `query`, `body` and `response` (absent: `204`).\n */\nexport type RouteEntry<\n A extends RouteAccess = RouteAccess,\n Contract = {},\n K extends string = never,\n> = { readonly access: A } & ([K] extends [never]\n ? UntypedRoute\n : K extends keyof Contract\n ? Contract[K]\n : UntypedRoute);\n\n/**\n * Routes of the plugins of the repository, by plugin name then route key. Empty here:\n * `src/cicord-routes.d.ts` (generated by `cicord portal typegen`) fills it.\n */\nexport interface PluginRouteRegistry {}\n\n/** levels `GET /me`: the viewer's own standing. */\nexport interface LevelsStanding {\n userId: string;\n /** From 1, null when the viewer has no XP yet. */\n rank: number | null;\n xp: number;\n level: number;\n /** XP earned inside the current level. */\n current: number;\n /** XP needed for the next level. */\n needed: number;\n}\n\n/** polls `GET /polls/:id`. */\nexport interface PollResults {\n id: string;\n question: string;\n status: \"open\" | \"closed\";\n multiple: boolean;\n createdAt: string;\n closesAt: string;\n closedAt: string | null;\n choices: { label: string; votes: number }[];\n voters: number;\n}\n\n/**\n * Routes of the official plugins (the `cicord` source), used for a plugin that the generated\n * registry does not list: the reference portal type-checks in a repository without them.\n */\nexport interface OfficialPluginRoutes {\n levels: {\n \"GET /leaderboard\": {\n readonly access: \"public\";\n query: { limit?: number };\n response: Leaderboard;\n };\n \"GET /me\": { readonly access: \"member\"; response: LevelsStanding };\n };\n polls: { \"GET /polls/:id\": { readonly access: \"public\"; response: PollResults } };\n tickets: {\n \"GET /tickets\": {\n readonly access: \"moderator\";\n query: { status?: TicketStatus };\n response: TicketList;\n };\n \"GET /tickets/:id\": RouteEntry<\"moderator\">;\n };\n onboarding: {\n \"GET /steps\": { readonly access: \"member\"; response: OnboardingSteps };\n \"POST /complete\": {\n readonly access: \"member\";\n body: { answers: OnboardingAnswers };\n response: OnboardingCompleteResponse;\n };\n };\n}\n\n/** The routes of plugin `N`: generated registry, else official plugin, else untyped. */\nexport type RoutesOf<N extends string> = N extends keyof PluginRouteRegistry\n ? PluginRouteRegistry[N]\n : N extends keyof OfficialPluginRoutes\n ? OfficialPluginRoutes[N]\n : { [K in RouteKey]: RouteEntry };\n\n/** Route keys of plugin `N` (optionally only those of `M` methods). */\nexport type RouteKeyOf<N extends string, M extends RouteMethod = RouteMethod> = Extract<\n keyof RoutesOf<N>,\n `${M} /${string}`\n>;\n\n/** The JSON a route answers with (`undefined` for routes declaring no response: 204). */\nexport type RouteResponseOf<E> = E extends { response: infer R } ? R : undefined;\n\ntype ParamsArg<K extends string> = keyof RouteParams<K> extends never\n ? { params?: Record<string, never> }\n : { params: RouteParams<K> };\ntype QueryArg<E> = E extends { query: infer Q }\n ? {} extends Q\n ? { query?: Q }\n : { query: Q }\n : E extends { query?: infer Q }\n ? { query?: Q }\n : { query?: undefined };\ntype BodyArg<E> = E extends { body: infer B }\n ? { body: B }\n : E extends { body?: infer B }\n ? { body?: B }\n : { body?: undefined };\n\n/** What a call needs: `params` (from the key), `query` and `body` (as declared). */\nexport type RouteInput<K extends string, E> = ParamsArg<K> & QueryArg<E> & BodyArg<E>;\nexport type RouteCallOptions<K extends string, E> = RouteInput<K, E> &\n CallOptions & { headers?: Record<string, string> };\n\n/** Makes the options argument optional when nothing in it is required. */\nexport type OptionalArg<T> = {} extends T ? [options?: T] : [options: T];\n\n/** Typed calls to the routes of one instance of plugin `N`. */\nexport interface TypedPluginRoutes<N extends string> {\n readonly plugin: N;\n readonly server: string;\n readonly bot: string;\n readonly instance: string;\n /** Calls a route: `call(\"GET /polls/:id\", { params: { id } })`. */\n call<K extends RouteKeyOf<N> & string>(\n this: void,\n route: K,\n ...options: OptionalArg<RouteCallOptions<K, RoutesOf<N>[K]>>\n ): Promise<RouteResponseOf<RoutesOf<N>[K]>>;\n /** Absolute URL of a route (`GET` routes: links, `<img src>`, EventSource…). */\n url<K extends RouteKeyOf<N> & string>(\n this: void,\n route: K,\n ...options: OptionalArg<RouteInput<K, RoutesOf<N>[K]>>\n ): string;\n}\n\n/** Splits \"GET /polls/:id\" with `{ id: \"4\" }` into `[\"GET\", \"/polls/4\"]`. */\nexport function resolveRoute(\n route: string,\n params: Record<string, string | number> | undefined = {},\n): [method: RouteMethod, path: string] {\n const space = route.indexOf(\" \");\n const method = route.slice(0, space) as RouteMethod;\n if (space < 0 || ![\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"].includes(method))\n throw new Error(`@cicord/client: invalid route key ${JSON.stringify(route)}`);\n const path = route\n .slice(space + 1)\n .split(\"/\")\n .map((segment) => {\n if (!segment.startsWith(\":\")) return segment;\n const value = params[segment.slice(1)];\n if (value === undefined || value === \"\")\n throw new Error(`@cicord/client: missing parameter ${segment.slice(1)} of ${route}`);\n // A value taken from the page URL must never climb out of the route (\"..\": another\n // route of the instance, another plugin, another API endpoint with the viewer's\n // cookies). Dots are encoded too, so no segment can be a dot-segment; the runtime\n // reads %2E as a literal dot.\n if (value === \".\" || value === \"..\")\n throw new Error(\n `@cicord/client: invalid parameter ${segment.slice(1)} of ${route}: ${value}`,\n );\n return encodeURIComponent(String(value)).replace(/\\./g, \"%2E\");\n })\n .join(\"/\");\n return [method, path];\n}\n","/**\n * Minimal Server-Sent Events client built on fetch (not EventSource), so it can send an\n * `Authorization` header, works in Node 24 and is easy to test with a mocked fetch.\n */\n\nexport interface ServerSentEvent {\n /** Event type (`event:` field), \"message\" by default. */\n event: string;\n data: string;\n id: string;\n}\n\nexport interface EventStreamOptions {\n onEvent: (event: ServerSentEvent) => void;\n /** Called on connection errors; the stream reconnects afterwards unless closed. */\n onError?: (error: unknown) => void;\n /** Called when a connection is (re)established. */\n onOpen?: () => void;\n /** Delay before reconnecting, in ms (updated by the server's `retry:` field). Default 2000. */\n retryMs?: number;\n /** Stop after the first disconnection instead of reconnecting. */\n once?: boolean;\n /**\n * Reconnect when nothing (event or comment) arrives for this long, in ms: a proxy can\n * keep the connection open after the server went away. Use it with a server that sends\n * keep-alive comments more often (Cicord's streams: every 25 s). Default: no limit.\n */\n idleTimeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport interface EventStream {\n close: () => void;\n /** Resolves when the stream is closed for good. */\n readonly closed: Promise<void>;\n}\n\nexport type StreamFetch = (url: string, init: RequestInit) => Promise<Response>;\n\n/** Incremental SSE parser (https://html.spec.whatwg.org/multipage/server-sent-events.html). */\nexport class SseParser {\n #buffer = \"\";\n #data: string[] = [];\n #event = \"\";\n #lastId = \"\";\n retry: number | undefined;\n readonly #emit: (event: ServerSentEvent) => void;\n\n constructor(emit: (event: ServerSentEvent) => void) {\n this.#emit = emit;\n }\n\n push(chunk: string): void {\n this.#buffer += chunk;\n let index: number;\n while ((index = this.#buffer.search(/\\r\\n|\\r|\\n/)) >= 0) {\n const line = this.#buffer.slice(0, index);\n const sep = this.#buffer.startsWith(\"\\r\\n\", index) ? 2 : 1;\n // A lone trailing \"\\r\" might be the first half of \"\\r\\n\": wait for more input.\n if (sep === 1 && this.#buffer[index] === \"\\r\" && index === this.#buffer.length - 1) break;\n this.#buffer = this.#buffer.slice(index + sep);\n this.#line(line);\n }\n }\n\n #line(line: string): void {\n if (line === \"\") {\n if (this.#data.length > 0) {\n this.#emit({\n event: this.#event || \"message\",\n data: this.#data.join(\"\\n\"),\n id: this.#lastId,\n });\n }\n this.#data = [];\n this.#event = \"\";\n return;\n }\n if (line.startsWith(\":\")) return;\n const colon = line.indexOf(\":\");\n const field = colon < 0 ? line : line.slice(0, colon);\n let value = colon < 0 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n switch (field) {\n case \"data\":\n this.#data.push(value);\n break;\n case \"event\":\n this.#event = value;\n break;\n case \"id\":\n if (!value.includes(\"\\0\")) this.#lastId = value;\n break;\n case \"retry\":\n if (/^\\d+$/.test(value)) this.retry = Number(value);\n break;\n }\n }\n\n get lastEventId(): string {\n return this.#lastId;\n }\n}\n\nexport function openEventStream(\n fetcher: StreamFetch,\n url: string,\n init: RequestInit,\n options: EventStreamOptions,\n): EventStream {\n const controller = new AbortController();\n const abort = (): void => controller.abort();\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n if (options.signal?.aborted) controller.abort();\n let retryMs = options.retryMs ?? 2000;\n let lastEventId = \"\";\n\n const run = async (): Promise<void> => {\n while (!controller.signal.aborted) {\n const parser = new SseParser(options.onEvent);\n // One controller per connection: the idle watchdog ends it without closing the stream.\n const attempt = new AbortController();\n const endAttempt = (): void => attempt.abort();\n controller.signal.addEventListener(\"abort\", endAttempt, { once: true });\n let idle: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n const arm = (): void => {\n if (options.idleTimeoutMs === undefined) return;\n clearTimeout(idle);\n idle = setTimeout(() => {\n timedOut = true;\n attempt.abort();\n }, options.idleTimeoutMs);\n };\n try {\n const headers = new Headers(init.headers);\n headers.set(\"Accept\", \"text/event-stream\");\n if (lastEventId) headers.set(\"Last-Event-ID\", lastEventId);\n arm();\n const response = await fetcher(url, { ...init, headers, signal: attempt.signal });\n if (!response.ok || !response.body) {\n throw new Error(`event stream ${url}: HTTP ${response.status}`);\n }\n options.onOpen?.();\n const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();\n for (;;) {\n arm();\n const { value, done } = await reader.read();\n if (done) break;\n parser.push(value);\n lastEventId = parser.lastEventId;\n if (parser.retry !== undefined) retryMs = parser.retry;\n }\n if (!controller.signal.aborted)\n options.onError?.(new Error(`event stream ${url}: disconnected`));\n } catch (error) {\n if (controller.signal.aborted) break;\n options.onError?.(\n timedOut\n ? new Error(`event stream ${url}: nothing received for ${options.idleTimeoutMs} ms`)\n : error,\n );\n } finally {\n clearTimeout(idle);\n controller.signal.removeEventListener(\"abort\", endAttempt);\n }\n if (options.once) break;\n await sleep(retryMs, controller.signal);\n }\n options.signal?.removeEventListener(\"abort\", abort);\n };\n\n const closed = run();\n return {\n close: abort,\n closed,\n };\n}\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) return resolve();\n const timer = setTimeout(done, ms);\n function done(): void {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n }\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n","import { CicordApiError } from \"./errors.ts\";\nimport { resolveRoute, type TypedPluginRoutes } from \"./routes.ts\";\nimport {\n openEventStream,\n type EventStream,\n type EventStreamOptions,\n type ServerSentEvent,\n} from \"./sse.ts\";\nimport type {\n AdminEvent,\n PortalAnalytics,\n PortalAnalyticsPeriod,\n AddRegistryRequest,\n AnalyticsCatalog,\n AnalyticsSeries,\n AnalyticsSeriesParams,\n AnalyticsSummary,\n AnalyticsSummaryQuery,\n AuditEntry,\n AuditQuery,\n InstallResult,\n InteractionResult,\n Items,\n Json,\n HistoryQuery,\n Me,\n Message,\n Page,\n PageParams,\n Plan,\n PluginInstance,\n PluginListParams,\n PortalMe,\n PortalServer,\n RemotePlanResult,\n RuntimeStatus,\n ServerAssetKind,\n ServerAssetResult,\n ServerDetail,\n ServerResources,\n SimCommand,\n SimCommandRequest,\n SimComponentRequest,\n SimModalRequest,\n SimSendMessageRequest,\n SimState,\n StoreDetail,\n StoreInstallRequest,\n StorePlugin,\n StorePluginParams,\n StoreSource,\n StoreSourceSummary,\n StoreUpdateRequest,\n StoreUpdateResult,\n StoreUpdateReview,\n SyncRecord,\n SyncResult,\n TokenSession,\n UninstallResult,\n UpdatePluginConfigRequest,\n User,\n WriteBackResult,\n WriteResult,\n} from \"./types.ts\";\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\n/**\n * How browser clients authenticate (https://cicord.dev/docs/reference/http-api/authentication/):\n * - `\"cookie\"` (default): the `cicord_session` cookie, for a portal served by the runtime or\n * on a same-site origin listed in `--cors-origin`;\n * - `\"token\"`: a bearer session token kept in a `TokenStore` and sent as `Authorization`,\n * for sites embedding the SDK on another origin (cicord.yaml `spec.portal.allowedOrigins`).\n */\nexport type AuthMode = \"cookie\" | \"token\";\n\n/** A token-mode session as stored by the client. */\nexport interface StoredSession {\n token: string;\n expiresAt: string;\n}\n\n/** Where token mode keeps the session token. */\nexport interface TokenStore {\n get(): StoredSession | null;\n set(session: StoredSession | null): void;\n}\n\n/** Keeps the token in memory (lost on reload; safest against XSS persistence). */\nexport function memoryTokenStore(): TokenStore {\n let value: StoredSession | null = null;\n return { get: () => value, set: (session) => void (value = session) };\n}\n\n/** Keeps the token in `localStorage` / `sessionStorage` (falls back to memory when unavailable). */\nexport function webStorageTokenStore(\n storage: Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\"> | undefined,\n key = \"cicord:session\",\n): TokenStore {\n const memory = memoryTokenStore();\n if (!storage) return memory;\n return {\n get: () => {\n try {\n const raw = storage.getItem(key);\n const parsed = raw ? (JSON.parse(raw) as Partial<StoredSession>) : null;\n return parsed && typeof parsed.token === \"string\" && typeof parsed.expiresAt === \"string\"\n ? { token: parsed.token, expiresAt: parsed.expiresAt }\n : null;\n } catch {\n return memory.get();\n }\n },\n set: (session) => {\n try {\n if (session) storage.setItem(key, JSON.stringify(session));\n else storage.removeItem(key);\n } catch {\n memory.set(session);\n }\n },\n };\n}\n\n/** True for absolute http(s) URLs (links from the server config, plugin data…). */\nexport function isSafeUrl(url: string): boolean {\n try {\n const u = new URL(url);\n return u.protocol === \"https:\" || u.protocol === \"http:\";\n } catch {\n return false;\n }\n}\n\nexport interface CicordClientOptions {\n /**\n * Origin (or origin + prefix) of the Cicord runtime, e.g. \"https://cicord.example.org\".\n * Default \"\": same origin as the page.\n */\n baseUrl?: string;\n /** API prefix. Default \"/api/v1\". */\n apiPath?: string;\n /** Auth prefix (https://cicord.dev/docs/reference/http-api/authentication/). Default \"/auth\". */\n authPath?: string;\n /** fetch implementation. Default: the global `fetch`, looked up at call time. */\n fetch?: FetchLike;\n /** Bearer token (runtime token) for machine clients; a function is called per request. */\n token?: string | (() => string | undefined | null);\n /** Extra headers sent with every request. */\n headers?: Record<string, string>;\n /**\n * Fetch credentials mode. Default \"include\" in cookie mode (session cookie, also\n * cross-origin with CORS), \"omit\" in token mode.\n */\n credentials?: RequestCredentials;\n /** Browser auth mode. Default \"cookie\". See `AuthMode`. */\n auth?: AuthMode;\n /**\n * Token mode: where the session token lives. \"local\" (default in browsers) and\n * \"session\" use Web Storage under `storageKey`; \"memory\" forgets it on reload.\n */\n tokenStore?: TokenStore | \"local\" | \"session\" | \"memory\";\n /** Web Storage key of token mode. Default \"cicord:session:<baseUrl>\". */\n storageKey?: string;\n}\n\nexport type Query = Record<string, string | number | boolean | undefined | null>;\n\nexport interface RequestOptions {\n query?: Query;\n /** JSON-serialisable body, or a raw body (Blob, ArrayBuffer, Uint8Array, string, FormData…). */\n body?: unknown;\n /** Content type for raw bodies. */\n contentType?: string;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\nexport interface CallOptions {\n signal?: AbortSignal;\n}\n\n/** Calls to the routes of one plugin instance (https://cicord.dev/docs/reference/http-api/portal/). */\nexport interface PluginRoutes {\n readonly server: string;\n readonly bot: string;\n readonly instance: string;\n /** Absolute URL of a route path. */\n url: (path: string, query?: Query) => string;\n request<T = Json>(method: string, path: string, options?: RequestOptions): Promise<T>;\n get<T = Json>(path: string, query?: Query, options?: CallOptions): Promise<T>;\n post<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n put<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n patch<T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T>;\n delete<T = Json>(path: string, options?: CallOptions): Promise<T>;\n}\n\n/** Minimal Location / History used by the auth helpers (injectable for tests and SSR). */\nexport interface LocationLike {\n href: string;\n assign?: (url: string) => void;\n}\nexport interface HistoryLike {\n replaceState: (data: unknown, unused: string, url?: string | URL | null) => void;\n readonly state?: unknown;\n}\n\nexport interface ExchangeLinkTokenOptions {\n location?: LocationLike;\n history?: HistoryLike;\n /** Query parameter carrying the token. Default \"cicord_token\". */\n param?: string;\n /** Query parameter carrying the one-time code of a token-mode login. Default \"cicord_code\". */\n codeParam?: string;\n}\n\n/** Query parameters a login may leave in the URL (removed by `exchangeLinkToken`). */\nexport const LOGIN_PARAMS = [\"cicord_token\", \"cicord_code\"] as const;\n\nconst isRawBody = (body: unknown): boolean =>\n typeof body === \"string\" ||\n body instanceof ArrayBuffer ||\n ArrayBuffer.isView(body) ||\n (typeof Blob !== \"undefined\" && body instanceof Blob) ||\n (typeof FormData !== \"undefined\" && body instanceof FormData) ||\n (typeof URLSearchParams !== \"undefined\" && body instanceof URLSearchParams) ||\n (typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream);\n\nconst seg = (value: string): string => encodeURIComponent(value);\n\nfunction trimSlash(value: string): string {\n // A loop, not /\\/+$/: that regex backtracks quadratically on many slashes not at the end.\n let end = value.length;\n while (end > 0 && value[end - 1] === \"/\") end--;\n return value.slice(0, end);\n}\n\n/** Query string of a paged list (https://cicord.dev/docs/reference/http-api/ \"Data tables\"); empty values are left out. */\nfunction pageQuery(params: PageParams = {}): Query {\n return {\n q: params.q?.trim() || undefined,\n sort: params.sort || undefined,\n order: params.order,\n offset: params.offset,\n limit: params.limit,\n };\n}\n\n/** A Date as RFC 3339 UTC without milliseconds (strings pass through). */\nfunction rfc3339(value: Date | string | undefined): string | undefined {\n if (value === undefined || typeof value === \"string\") return value;\n return value.toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n}\n\nfunction withQuery(url: string, query?: Query): string {\n if (!query) return url;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== null) params.set(key, String(value));\n }\n const qs = params.toString();\n return qs ? `${url}${url.includes(\"?\") ? \"&\" : \"?\"}${qs}` : url;\n}\n\n/**\n * Typed client for the Cicord runtime HTTP API v1 (https://cicord.dev/docs/reference/http-api/). Framework-agnostic: works in\n * browsers, Node 24, workers. Every non-2xx response rejects with `CicordApiError`.\n */\nexport class CicordClient {\n readonly baseUrl: string;\n readonly apiPath: string;\n readonly authPath: string;\n readonly authMode: AuthMode;\n readonly #options: CicordClientOptions;\n readonly #store: TokenStore;\n readonly #listeners = new Set<() => void>();\n #pendingLink: Promise<Me> | undefined;\n\n constructor(options: CicordClientOptions = {}) {\n this.#options = options;\n this.baseUrl = trimSlash(options.baseUrl ?? \"\");\n this.apiPath = trimSlash(options.apiPath ?? \"/api/v1\");\n this.authPath = trimSlash(options.authPath ?? \"/auth\");\n this.authMode = options.auth ?? \"cookie\";\n this.#store = resolveStore(\n options.tokenStore,\n options.storageKey ?? `cicord:session:${this.baseUrl}`,\n );\n }\n\n // ─────────────────────────────────────────────────────────── token-mode session\n\n /** The token-mode session, or null (cookie mode, logged out or expired). */\n session(): StoredSession | null {\n if (this.authMode !== \"token\") return null;\n const s = this.#store.get();\n if (s && Date.parse(s.expiresAt) <= Date.now()) {\n this.#setSession(null);\n return null;\n }\n return s;\n }\n\n /** Called when the token-mode session changes (login, logout, expiry, revocation). */\n onSessionChange(listener: () => void): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n #setSession(session: StoredSession | null): void {\n this.#store.set(session);\n for (const listener of this.#listeners) listener();\n }\n\n #adopt(session: TokenSession): Me {\n this.#setSession({ token: session.token, expiresAt: session.expiresAt });\n return session.me;\n }\n\n // ─────────────────────────────────────────────────────────── transport\n\n /** Absolute URL of a path relative to the runtime origin (e.g. \"/api/v1/me\"). */\n url(path: string, query?: Query): string {\n return withQuery(`${this.baseUrl}${path.startsWith(\"/\") ? path : `/${path}`}`, query);\n }\n\n /** URL of an API path (e.g. \"/me\" → \"/api/v1/me\"). */\n apiUrl(path: string, query?: Query): string {\n return this.url(`${this.apiPath}${path.startsWith(\"/\") ? path : `/${path}`}`, query);\n }\n\n #headers(extra?: Record<string, string>): Headers {\n const headers = new Headers(this.#options.headers);\n // CSRF protection (https://cicord.dev/docs/reference/http-api/authentication/): the runtime rejects cookie-authenticated\n // state-changing requests without this header.\n headers.set(\"X-Cicord-Request\", \"1\");\n const token =\n (typeof this.#options.token === \"function\" ? this.#options.token() : this.#options.token) ??\n this.session()?.token;\n if (token) headers.set(\"Authorization\", `Bearer ${token}`);\n for (const [k, v] of Object.entries(extra ?? {})) headers.set(k, v);\n return headers;\n }\n\n #fetch: FetchLike = (input, init) => {\n const impl = this.#options.fetch ?? globalThis.fetch;\n if (!impl) throw new Error(\"@cicord/client: no fetch implementation available\");\n return impl(input, init);\n };\n\n /** Sends a request to an absolute runtime path (no API prefix added). */\n async request<T = Json>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n const headers = this.#headers(options.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n let body: BodyInit | undefined;\n if (options.body !== undefined) {\n if (isRawBody(options.body)) {\n body = options.body as BodyInit;\n if (options.contentType) headers.set(\"Content-Type\", options.contentType);\n } else {\n body = JSON.stringify(options.body);\n headers.set(\"Content-Type\", options.contentType ?? \"application/json\");\n }\n }\n const init: RequestInit = {\n method: method.toUpperCase(),\n headers,\n credentials: this.#credentials(),\n ...(body === undefined ? {} : { body }),\n ...(options.signal ? { signal: options.signal } : {}),\n };\n\n let response: Response;\n try {\n response = await this.#fetch(this.url(path, options.query), init);\n } catch (cause) {\n if (options.signal?.aborted) throw cause;\n throw new CicordApiError({\n code: \"network\",\n status: 0,\n message: cause instanceof Error ? cause.message : \"network error\",\n cause,\n });\n }\n\n const parsed = await readBody(response);\n if (!response.ok) {\n // A revoked or expired token: forget it so the app shows the logged-out state.\n if (response.status === 401 && this.session()?.token && !this.#options.token)\n this.#setSession(null);\n throw CicordApiError.fromResponse(response.status, response.statusText, parsed);\n }\n return parsed as T;\n }\n\n #credentials(): RequestCredentials {\n return this.#options.credentials ?? (this.authMode === \"token\" ? \"omit\" : \"include\");\n }\n\n #api<T>(method: string, path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>(method, `${this.apiPath}${path}`, options);\n }\n\n // ─────────────────────────────────────────────────────────── me & auth (§1, §2)\n\n /** `GET /api/v1/me`. Rejects with code `unauthenticated` when there is no session. */\n me(options?: CallOptions): Promise<Me> {\n return this.#api<Me>(\"GET\", \"/me\", options);\n }\n\n /** Like `me()`, but resolves `null` instead of rejecting when not logged in. */\n async meOrNull(options?: CallOptions): Promise<Me | null> {\n try {\n return await this.me(options);\n } catch (error) {\n if (error instanceof CicordApiError && error.code === \"unauthenticated\") return null;\n throw error;\n }\n }\n\n readonly auth = {\n /**\n * URL that starts the Discord OAuth2 login and comes back to `redirect` (a path on the\n * portal; default: the current page).\n */\n loginUrl: (redirect?: string): string => {\n if (this.authMode === \"token\") {\n // The runtime redirects back with ?cicord_code=… to this absolute URL, which must be\n // on an allowed origin (spec.portal.allowedOrigins or --cors-origin).\n const here = globalLocation()?.href;\n const target =\n redirect !== undefined && here ? new URL(redirect, here).toString() : (redirect ?? here);\n return this.url(`${this.authPath}/login`, { mode: \"token\", redirect: target });\n }\n const target = redirect ?? currentPath();\n return this.url(`${this.authPath}/login`, target ? { redirect: target } : undefined);\n },\n\n /** Navigates the browser to the login URL. */\n login: (redirect?: string, location: LocationLike | undefined = globalLocation()): void => {\n const url = this.auth.loginUrl(redirect);\n if (location?.assign) location.assign(url);\n else if (location) location.href = url;\n else throw new Error(\"@cicord/client: auth.login() needs a browser location\");\n },\n\n /** `POST /auth/link` with an explicit token (stores the session token in token mode). */\n link: async (token: string, options?: CallOptions): Promise<Me> => {\n if (this.authMode !== \"token\")\n return this.request<Me>(\"POST\", `${this.authPath}/link`, { body: { token }, ...options });\n return this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/link`, {\n body: { token, mode: \"token\" },\n ...options,\n }),\n );\n },\n\n /** Token mode: `POST /auth/token` — redeems the one-time code of an OAuth login. */\n redeem: async (code: string, options?: CallOptions): Promise<Me> =>\n this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/token`, {\n body: { code },\n ...options,\n }),\n ),\n\n /**\n * Reads `cicord_token` from the current URL (a signed link from `ctx.portal.link()`),\n * removes it from the address bar right away (so it is neither bookmarked nor sent twice),\n * and exchanges it for a session. Resolves `null` when the URL has no token.\n * Calls made while an exchange is in flight share it (safe under React StrictMode).\n */\n exchangeLinkToken: (options: ExchangeLinkTokenOptions = {}): Promise<Me | null> => {\n const location = options.location ?? globalLocation();\n const param = options.param ?? \"cicord_token\";\n const codeParam = options.codeParam ?? \"cicord_code\";\n if (!location) return Promise.resolve(null);\n const url = new URL(location.href);\n const token = url.searchParams.get(param);\n // A token-mode OAuth login comes back with a one-time code.\n const code = this.authMode === \"token\" ? url.searchParams.get(codeParam) : null;\n if (!token && !code) return this.#pendingLink ?? Promise.resolve(null);\n\n url.searchParams.delete(param);\n url.searchParams.delete(codeParam);\n const history = options.history ?? globalHistory();\n const clean = `${url.pathname}${url.search}${url.hash}`;\n if (history) history.replaceState(history.state ?? null, \"\", clean);\n else location.href = url.toString();\n\n const exchange = token ? this.auth.link(token) : this.auth.redeem(code as string);\n const pending = exchange.finally(() => {\n if (this.#pendingLink === pending) this.#pendingLink = undefined;\n });\n this.#pendingLink = pending;\n return pending;\n },\n\n /** `POST /auth/dev-login` — `cicord dev` only (stores the session token in token mode). */\n devLogin: async (userId: string, options?: CallOptions): Promise<Me> => {\n if (this.authMode !== \"token\")\n return this.request<Me>(\"POST\", `${this.authPath}/dev-login`, {\n body: { userId },\n ...options,\n });\n return this.#adopt(\n await this.request<TokenSession>(\"POST\", `${this.authPath}/dev-login`, {\n body: { userId, mode: \"token\" },\n ...options,\n }),\n );\n },\n\n /** `POST /auth/logout` (token mode: revokes the token and forgets it). */\n logout: async (options?: CallOptions): Promise<void> => {\n try {\n await this.request<void>(\"POST\", `${this.authPath}/logout`, options);\n } finally {\n if (this.authMode === \"token\") this.#setSession(null);\n }\n },\n };\n\n // ─────────────────────────────────────────────────────────── portal (§6)\n\n readonly portal = {\n /** `GET /portal/servers` — servers with a portal. */\n servers: async (options?: CallOptions): Promise<PortalServer[]> =>\n (await this.#api<Items<PortalServer>>(\"GET\", \"/portal/servers\", options)).items.map((s) =>\n this.#absolutize(s),\n ),\n /** `GET /portal/{server}`. */\n server: async (server: string, options?: CallOptions): Promise<PortalServer> =>\n this.#absolutize(await this.#api<PortalServer>(\"GET\", `/portal/${seg(server)}`, options)),\n /** `GET /portal/{server}/me` — the viewer as a member of the server. */\n me: (server: string, options?: CallOptions): Promise<PortalMe> =>\n this.#api<PortalMe>(\"GET\", `/portal/${seg(server)}/me`, options),\n /**\n * `GET /portal/{server}/analytics?period=` — server-wide activity for the portal, when\n * the server opts in (`spec.analytics.portal`: members or public; 404 otherwise).\n */\n analytics: (\n server: string,\n period: PortalAnalyticsPeriod = \"30d\",\n options?: CallOptions,\n ): Promise<PortalAnalytics> =>\n this.#api<PortalAnalytics>(\"GET\", `/portal/${seg(server)}/analytics`, {\n query: { period },\n ...options,\n }),\n };\n\n /** Runtime-relative image URLs (logo, banner) resolved against `baseUrl` (embedded portals). */\n #absolutize(server: PortalServer): PortalServer {\n if (!this.baseUrl) return server;\n const abs = (u: string | undefined) => (u && u.startsWith(\"/\") ? this.url(u) : u);\n return {\n ...server,\n theme: { ...server.theme, logo: abs(server.theme.logo) ?? \"\" },\n banner: abs(server.banner) ?? \"\",\n };\n }\n\n /** Routes of a plugin instance: `/api/v1/portal/{server}/plugins/{bot}/{instance}/{path}`. */\n plugin(server: string, bot: string, instance: string): PluginRoutes {\n const prefix = `${this.apiPath}/portal/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`;\n const full = (path: string): string => `${prefix}${path.startsWith(\"/\") ? path : `/${path}`}`;\n const request = <T = Json>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<T> => this.request<T>(method, full(path), options);\n const withBody =\n (method: string) =>\n <T = Json>(path: string, body?: unknown, options?: CallOptions): Promise<T> =>\n request<T>(method, path, { ...options, ...(body === undefined ? {} : { body }) });\n return {\n server,\n bot,\n instance,\n url: (path, query) => this.url(full(path), query),\n request,\n get: <T = Json>(path: string, query?: Query, options?: CallOptions) =>\n request<T>(\"GET\", path, { ...options, ...(query ? { query } : {}) }),\n post: withBody(\"POST\"),\n put: withBody(\"PUT\"),\n patch: withBody(\"PATCH\"),\n delete: <T = Json>(path: string, options?: CallOptions) =>\n request<T>(\"DELETE\", path, options),\n };\n }\n\n /**\n * Typed calls to the routes of an instance of plugin `plugin` (types from the generated\n * `src/cicord-routes.d.ts`, see `PluginRouteRegistry`). `at` is the instance, typically\n * found in `PortalServer.plugins` by plugin name.\n */\n routes<N extends string>(\n plugin: N,\n server: string,\n at: { bot: string; instance: string },\n ): TypedPluginRoutes<N> {\n const routes = this.plugin(server, at.bot, at.instance);\n type Loose = { params?: Record<string, string>; query?: object; body?: unknown };\n return {\n plugin,\n server,\n bot: at.bot,\n instance: at.instance,\n // async: an invalid parameter rejects like any failed call.\n call: (async (route: string, options: Loose & RequestOptions = {}) => {\n const { params, query, body, ...rest } = options;\n const [method, path] = resolveRoute(route, params);\n return routes.request(method, path, {\n ...rest,\n ...(query ? { query } : {}),\n ...(body === undefined ? {} : { body }),\n });\n }) as TypedPluginRoutes<N>[\"call\"],\n url: ((route: string, options: Loose = {}) => {\n const [, path] = resolveRoute(route, options.params);\n return routes.url(path, options.query as Query | undefined);\n }) as TypedPluginRoutes<N>[\"url\"],\n };\n }\n\n // ─────────────────────────────────────────────────────────── admin (§3–§5)\n\n readonly admin = {\n /**\n * Subscribes to `GET /events` (SSE, moderator): `hello` on every (re)connection, then\n * change hints for the runtime (`status`) and the servers you moderate (`sync`,\n * `plugins`, `analytics`). Reconnects automatically; call `close()` to stop.\n */\n subscribe: (\n onEvent: (event: AdminEvent) => void,\n options: Omit<EventStreamOptions, \"onEvent\"> = {},\n ): EventStream =>\n this.events(\"/events\", {\n ...options,\n onEvent: (e) => {\n let data: Record<string, unknown> = {};\n try {\n data = JSON.parse(e.data || \"{}\") as Record<string, unknown>;\n } catch {\n return;\n }\n const server = typeof data.server === \"string\" ? data.server : undefined;\n switch (e.event) {\n case \"hello\":\n onEvent({\n type: \"hello\",\n version: typeof data.version === \"string\" ? data.version : \"\",\n revision: typeof data.revision === \"string\" ? data.revision : \"\",\n });\n break;\n case \"status\":\n case \"stopping\":\n onEvent({ type: e.event });\n break;\n case \"sync\":\n case \"plugins\":\n case \"analytics\":\n onEvent(server === undefined ? { type: e.event } : { type: e.event, server });\n break;\n }\n },\n }),\n /** `GET /status` (admin, moderator) — visible servers only. */\n status: (options?: CallOptions): Promise<RuntimeStatus> =>\n this.#api<RuntimeStatus>(\"GET\", \"/status\", options),\n /** `GET /history?limit=&target=` (admin, moderator), newest first. */\n history: async (query: HistoryQuery = {}, options?: CallOptions): Promise<SyncRecord[]> =>\n (\n await this.#api<Items<SyncRecord>>(\"GET\", \"/history\", {\n query: { limit: query.limit, target: query.target },\n ...options,\n })\n ).items,\n /** `GET /servers/{server}` (moderator). */\n server: (server: string, options?: CallOptions): Promise<ServerDetail> =>\n this.#api<ServerDetail>(\"GET\", `/servers/${seg(server)}`, options),\n /** `GET /servers/{server}/resources` (moderator) — roles, categories, channels for pickers. */\n resources: (server: string, options?: CallOptions): Promise<ServerResources> =>\n this.#api<ServerResources>(\"GET\", `/servers/${seg(server)}/resources`, options),\n /** `GET /servers/{server}/plan` (admin). */\n plan: (server: string, options?: CallOptions): Promise<Plan> =>\n this.#api<Plan>(\"GET\", `/servers/${seg(server)}/plan`, options),\n /** `POST /servers/{server}/sync` (admin) — reconcile now. */\n sync: (server: string, options?: CallOptions): Promise<SyncResult> =>\n this.#api<SyncResult>(\"POST\", `/servers/${seg(server)}/sync`, options),\n /** `GET /servers/{server}/audit?before=&limit=` (moderator), newest first. */\n audit: async (\n server: string,\n query: AuditQuery = {},\n options?: CallOptions,\n ): Promise<AuditEntry[]> =>\n (\n await this.#api<Items<AuditEntry>>(\"GET\", `/servers/${seg(server)}/audit`, {\n query: { before: query.before, limit: query.limit },\n ...options,\n })\n ).items,\n /** `GET /servers/{server}/plugins` (moderator): every instance. */\n plugins: async (server: string, options?: CallOptions): Promise<PluginInstance[]> =>\n (await this.#api<Items<PluginInstance>>(\"GET\", `/servers/${seg(server)}/plugins`, options))\n .items,\n /**\n * `GET /servers/{server}/plugins?q&sort&order&offset&limit` (moderator): one page of\n * instances. Without `limit` the page holds every instance. Rejects with `invalid` (400)\n * on an unknown sort key.\n */\n pluginsPage: (\n server: string,\n params: PluginListParams = {},\n options?: CallOptions,\n ): Promise<Page<PluginInstance>> =>\n this.#api<Page<PluginInstance>>(\"GET\", `/servers/${seg(server)}/plugins`, {\n query: { ...pageQuery(params), updates: params.updates },\n ...options,\n }),\n /** `GET /servers/{server}/plugins/{bot}/{instance}` (moderator). Rejects with `not_found`. */\n plugin: (\n server: string,\n bot: string,\n instance: string,\n options?: CallOptions,\n ): Promise<PluginInstance> =>\n this.#api<PluginInstance>(\n \"GET\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`,\n options,\n ),\n /**\n * `DELETE /servers/{server}/plugins/{bot}/{instance}` (admin): uninstalls the instance from\n * the server (plugin data is kept). Rejects with `invalid` + `diagnostics` (422, something\n * depends on it), `conflict` (409), `forbidden` (403) or `not_found` (404).\n */\n uninstallPlugin: (\n server: string,\n bot: string,\n instance: string,\n options?: CallOptions,\n ): Promise<UninstallResult> =>\n this.#api<UninstallResult>(\n \"DELETE\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}`,\n options,\n ),\n /**\n * `PUT /servers/{server}/plugins/{bot}/{instance}/config` (moderator, field-restricted).\n * Rejects with `forbidden` (403), `invalid` + `diagnostics` (422) or `conflict` (409).\n */\n updatePluginConfig: (\n server: string,\n bot: string,\n instance: string,\n request: UpdatePluginConfigRequest,\n options?: CallOptions,\n ): Promise<WriteBackResult> =>\n this.#api<WriteBackResult>(\n \"PUT\",\n `/servers/${seg(server)}/plugins/${seg(bot)}/${seg(instance)}/config`,\n {\n body: request,\n ...options,\n },\n ),\n /**\n * `PUT /servers/{server}/assets/{kind}` (admin) — uploads the server icon, banner or\n * splash (PNG, JPEG, GIF, WebP ≤ 8 MiB) into the repository and points\n * `spec.profile.<kind>` at it. Rejects with `unsupported_media_type` (415),\n * `too_large` (413) or `conflict` (409, when `revision` is stale).\n */\n uploadServerAsset: (\n server: string,\n kind: ServerAssetKind,\n image: Blob | ArrayBuffer | Uint8Array,\n options: CallOptions & { revision?: string } = {},\n ): Promise<ServerAssetResult> => {\n const { revision, ...rest } = options;\n return this.#api<ServerAssetResult>(\"PUT\", `/servers/${seg(server)}/assets/${seg(kind)}`, {\n body: image,\n contentType: image instanceof Blob && image.type ? image.type : \"application/octet-stream\",\n ...(revision ? { query: { revision } } : {}),\n ...rest,\n });\n },\n /** URL of the image declared in `spec.profile.<kind>` (moderator), for previews. */\n serverAssetUrl: (server: string, kind: ServerAssetKind): string =>\n this.url(`${this.apiPath}/servers/${seg(server)}/assets/${seg(kind)}`),\n };\n\n // ─────────────────────────────────────────────────────────── analytics\n\n /**\n * Server activity analytics (moderator and admin of the server). Times are UTC. Every call\n * rejects with `analytics_disabled` (404) when the runtime has no analytics store.\n */\n readonly analytics = {\n /**\n * `GET /servers/{server}/analytics/summary?period=` or `?from=&to=`: headline numbers\n * compared with the previous period of the same length, rankings and the weekday × hour\n * heatmap. `query` is a preset period (`\"30d\"`, `{ period: \"30d\" }`) or a custom range\n * (`{ from, to }`, RFC 3339 or Dates). Rejects with `invalid` (400) for a range shorter\n * than an hour, longer than 400 days or starting in the future.\n */\n summary: (\n server: string,\n query: AnalyticsSummaryQuery = \"30d\",\n options?: CallOptions,\n ): Promise<AnalyticsSummary> =>\n this.#api<AnalyticsSummary>(\"GET\", `/servers/${seg(server)}/analytics/summary`, {\n query:\n typeof query === \"string\"\n ? { period: query }\n : \"period\" in query\n ? { period: query.period }\n : { from: rfc3339(query.from), to: rfc3339(query.to) },\n ...options,\n }),\n /**\n * `GET /servers/{server}/analytics/series?metrics=&from=&to=&step=[&dim=][&top=]`. Rejects\n * with `invalid` (400) for an unknown metric or step, more than 400 days or more than 2000\n * points per series.\n */\n series: (\n server: string,\n params: AnalyticsSeriesParams,\n options?: CallOptions,\n ): Promise<AnalyticsSeries> =>\n this.#api<AnalyticsSeries>(\"GET\", `/servers/${seg(server)}/analytics/series`, {\n query: {\n metrics: params.metrics.join(\",\"),\n from: rfc3339(params.from),\n to: rfc3339(params.to),\n step: params.step,\n dim: params.dim,\n top: params.top,\n },\n ...options,\n }),\n /** `GET /servers/{server}/analytics/catalog`: every metric and whether it is collected. */\n catalog: (server: string, options?: CallOptions): Promise<AnalyticsCatalog> =>\n this.#api<AnalyticsCatalog>(\"GET\", `/servers/${seg(server)}/analytics/catalog`, options),\n };\n\n // ─────────────────────────────────────────────────────────── store (§11)\n\n readonly store = {\n /** `GET /store` (admin of a server): every source, `cicord` first, then the registries. */\n list: async (options?: CallOptions): Promise<StoreSource[]> =>\n (await this.#api<{ sources: StoreSource[] }>(\"GET\", \"/store\", options)).sources,\n /**\n * `GET /store?summary=1` (admin of a server): every source with its plugin count, without\n * the plugins (`summary: false` is `list()`).\n */\n sources: async (\n { summary = true }: { summary?: boolean } = {},\n options?: CallOptions,\n ): Promise<StoreSourceSummary[]> =>\n (\n await this.#api<{ sources: StoreSourceSummary[] }>(\"GET\", \"/store\", {\n ...(summary ? { query: { summary: 1 } } : {}),\n ...options,\n })\n ).sources,\n /**\n * `GET /store/plugins` (admin of a server): one page of the plugins of every source,\n * filtered by `source`, `trust` and `installed` (default limit 50).\n */\n plugins: (params: StorePluginParams = {}, options?: CallOptions): Promise<Page<StorePlugin>> =>\n this.#api<Page<StorePlugin>>(\"GET\", \"/store/plugins\", {\n query: {\n ...pageQuery(params),\n source: params.source || undefined,\n trust: params.trust,\n installed: params.installed,\n updates: params.updates,\n },\n ...options,\n }),\n /** `POST /store/refresh` (admin of a server): refetches every registry index. */\n refresh: async (options?: CallOptions): Promise<StoreSource[]> =>\n (await this.#api<{ sources: StoreSource[] }>(\"POST\", \"/store/refresh\", options)).sources,\n /**\n * `GET /store/{source}/{plugin}` (admin of a server): the latest version and what it\n * requests. Rejects with `not_found` (404) or `registry_unavailable` (502).\n */\n detail: (source: string, plugin: string, options?: CallOptions): Promise<StoreDetail> =>\n this.#api<StoreDetail>(\"GET\", `/store/${seg(source)}/${seg(plugin)}`, options),\n /**\n * `POST /servers/{server}/store/install` (admin of `server`). Rejects with `changed`,\n * `confirmation_required`, `intents`, `conflict` (409) or `invalid` + `diagnostics` (422).\n */\n install: (\n server: string,\n request: StoreInstallRequest,\n options?: CallOptions,\n ): Promise<InstallResult> =>\n this.#api<InstallResult>(\"POST\", `/servers/${seg(server)}/store/install`, {\n body: request,\n ...options,\n }),\n /**\n * `GET /store/{source}/{plugin}/update` (admin of a server): the latest version, what is\n * installed and the permission diff. Rejects with `not_installed` / `not_found` (404) or\n * `registry_unavailable` (502).\n */\n updateReview: (\n source: string,\n plugin: string,\n options?: CallOptions,\n ): Promise<StoreUpdateReview> =>\n this.#api<StoreUpdateReview>(\"GET\", `/store/${seg(source)}/${seg(plugin)}/update`, options),\n /**\n * `POST /store/{source}/{plugin}/update` (admin of every server where the plugin runs):\n * updates every instance in one write-back. Rejects with `changed`, `confirmation_required`,\n * `modified`, `up_to_date`, `intents`, `conflict` (409), `invalid` + `diagnostics` (422) or\n * `forbidden` (403, not admin on one of the servers).\n */\n update: (\n source: string,\n plugin: string,\n request: StoreUpdateRequest,\n options?: CallOptions,\n ): Promise<StoreUpdateResult> =>\n this.#api<StoreUpdateResult>(\"POST\", `/store/${seg(source)}/${seg(plugin)}/update`, {\n body: request,\n ...options,\n }),\n };\n\n readonly registries = {\n /**\n * `POST /registries` (bearer, or admin of every server): adds a registry to\n * `cicord.yaml`. Rejects with `invalid` (400 bad name / URL, 422 unreachable index) or\n * `forbidden` (403).\n */\n add: (request: AddRegistryRequest, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"POST\", \"/registries\", { body: request, ...options }),\n /** `DELETE /registries/{name}`. Rejects with `not_found` (404) or `in_use` (409). */\n remove: (name: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"DELETE\", `/registries/${seg(name)}`, options),\n /**\n * `PUT /registries/{name}/token`: stores the access token of a private registry (checked\n * against its index first). Rejects with `invalid` (422, the index cannot be read with it),\n * `not_found` (404) or `unavailable` (503, no secret store).\n */\n setToken: (name: string, token: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"PUT\", `/registries/${seg(name)}/token`, {\n body: { token },\n ...options,\n }),\n /** `DELETE /registries/{name}/token`: makes the registry public again. */\n removeToken: (name: string, options?: CallOptions): Promise<WriteResult> =>\n this.#api<WriteResult>(\"DELETE\", `/registries/${seg(name)}/token`, options),\n };\n\n // ─────────────────────────────────────────────────────────── machine (§7)\n\n readonly machine = {\n /** `POST /api/v1/sync` — fetch the source now and sync (202). */\n sync: async (options?: CallOptions): Promise<void> => {\n await this.#api<void>(\"POST\", \"/sync\", options);\n },\n /** `POST /api/v1/plan` with a `.tar.gz` of a repository. */\n plan: (\n archive: Blob | ArrayBuffer | Uint8Array,\n options?: CallOptions,\n ): Promise<RemotePlanResult> =>\n this.#api<RemotePlanResult>(\"POST\", \"/plan\", {\n body: archive,\n contentType: \"application/gzip\",\n ...options,\n }),\n /** `GET /healthz` → true when the process is up. */\n healthz: (options?: CallOptions): Promise<boolean> => this.#probe(\"/healthz\", options),\n /** `GET /readyz` → true once a revision is active. */\n readyz: (options?: CallOptions): Promise<boolean> => this.#probe(\"/readyz\", options),\n };\n\n async #probe(path: string, options?: CallOptions): Promise<boolean> {\n try {\n await this.request(\"GET\", path, {\n ...options,\n headers: { Accept: \"text/plain, application/json\" },\n });\n return true;\n } catch (error) {\n if (error instanceof CicordApiError) return false;\n throw error;\n }\n }\n\n // ─────────────────────────────────────────────────────────── simulator (§8)\n\n readonly sim = {\n /** `GET /sim/state`. */\n state: (options?: CallOptions): Promise<SimState> =>\n this.#api<SimState>(\"GET\", \"/sim/state\", options),\n /** `POST /sim/users` — creates a simulated user. */\n createUser: (username: string, options?: CallOptions): Promise<User> =>\n this.#api<User>(\"POST\", \"/sim/users\", { body: { username }, ...options }),\n /** `POST /sim/servers/{id}/members` — the user joins the server. */\n join: async (serverId: string, userId: string, options?: CallOptions): Promise<void> => {\n await this.#api<void>(\"POST\", `/sim/servers/${seg(serverId)}/members`, {\n body: { userId },\n ...options,\n });\n },\n /** `DELETE /sim/servers/{id}/members/{userId}` — the user leaves. */\n leave: async (serverId: string, userId: string, options?: CallOptions): Promise<void> => {\n await this.#api<void>(\n \"DELETE\",\n `/sim/servers/${seg(serverId)}/members/${seg(userId)}`,\n options,\n );\n },\n /** `GET /sim/channels/{id}/messages?limit=` — oldest first. */\n messages: async (\n channelId: string,\n query: { limit?: number } = {},\n options?: CallOptions,\n ): Promise<Message[]> =>\n (\n await this.#api<Items<Message>>(\"GET\", `/sim/channels/${seg(channelId)}/messages`, {\n query,\n ...options,\n })\n ).items,\n /** `GET /sim/users/{id}/dms?limit=` — DMs received by the user from bots, oldest first. */\n dms: async (\n userId: string,\n { limit, ...options }: CallOptions & { limit?: number } = {},\n ): Promise<Message[]> =>\n (\n await this.#api<Items<Message>>(\"GET\", `/sim/users/${seg(userId)}/dms`, {\n query: { limit },\n ...options,\n })\n ).items,\n /** `POST /sim/messages`. */\n sendMessage: (request: SimSendMessageRequest, options?: CallOptions): Promise<Message> =>\n this.#api<Message>(\"POST\", \"/sim/messages\", { body: request, ...options }),\n /** `POST /sim/commands` — runs a slash command (waits up to 5 s for the answer). */\n command: (request: SimCommandRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/commands\", {\n body: { options: {}, ...request },\n ...options,\n }),\n /** `POST /sim/components` — clicks a button / picks select values. */\n component: (request: SimComponentRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/components\", {\n body: { values: [], ...request },\n ...options,\n }),\n /**\n * `POST /sim/modals` — submits a modal shown by a previous interaction\n * (`InteractionResult.modal`); `fields` maps text input ids to values.\n */\n modal: (request: SimModalRequest, options?: CallOptions): Promise<InteractionResult> =>\n this.#api<InteractionResult>(\"POST\", \"/sim/modals\", { body: request, ...options }),\n /** `GET /sim/commands?serverId=` — registered commands (all simulated servers by default). */\n commands: async (serverId?: string, options?: CallOptions): Promise<SimCommand[]> =>\n (\n await this.#api<Items<SimCommand>>(\"GET\", \"/sim/commands\", {\n query: { serverId },\n ...options,\n })\n ).items,\n /**\n * Subscribes to `GET /sim/events` (SSE). `onChange` fires for every `event: change`\n * (a hint to refresh); reconnects automatically. Call `close()` to stop.\n */\n subscribe: (\n onChange: (event: ServerSentEvent) => void,\n options: Omit<EventStreamOptions, \"onEvent\"> = {},\n ): EventStream =>\n this.events(\"/sim/events\", {\n ...options,\n onEvent: (e) => e.event === \"change\" && onChange(e),\n }),\n };\n\n /** Opens a Server-Sent Events stream on an API path (fetch-based, sends credentials/token). */\n events(path: string, options: EventStreamOptions): EventStream {\n return openEventStream(\n this.#fetch,\n this.apiUrl(path),\n {\n method: \"GET\",\n headers: this.#headers(),\n credentials: this.#credentials(),\n },\n options,\n );\n }\n}\n\nasync function readBody(response: Response): Promise<Json | string | undefined> {\n if (response.status === 204 || response.status === 205 || response.status === 304)\n return undefined;\n const text = await response.text();\n if (text === \"\") return undefined;\n const type = response.headers.get(\"Content-Type\") ?? \"\";\n if (type.includes(\"json\") || /^\\s*[[{]/.test(text)) {\n try {\n return JSON.parse(text) as Json;\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction resolveStore(store: CicordClientOptions[\"tokenStore\"], key: string): TokenStore {\n if (store && typeof store === \"object\") return store;\n if (store === \"memory\") return memoryTokenStore();\n const storage = (name: \"localStorage\" | \"sessionStorage\") => {\n try {\n return (globalThis as Record<string, unknown>)[name] as Storage | undefined;\n } catch {\n return undefined;\n }\n };\n return webStorageTokenStore(\n storage(store === \"session\" ? \"sessionStorage\" : \"localStorage\"),\n key,\n );\n}\n\nfunction globalLocation(): LocationLike | undefined {\n return typeof location === \"undefined\" ? undefined : location;\n}\n\nfunction globalHistory(): HistoryLike | undefined {\n return typeof history === \"undefined\" ? undefined : history;\n}\n\nfunction currentPath(): string | undefined {\n const loc = globalLocation();\n if (!loc) return undefined;\n const url = new URL(loc.href);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\n/** Creates a client. See `CicordClientOptions`. */\nexport function createCicordClient(options?: CicordClientOptions): CicordClient {\n return new CicordClient(options);\n}\n","/**\n * Contract of the `onboarding` plugin's portal routes\n * (examples/basic/plugins/onboarding — `GET /steps`, `POST /complete`).\n */\nimport type { PluginRoutes } from \"./client.ts\";\n\n/** A role a member can pick, resolved by the plugin from the server's roles. */\nexport interface OnboardingOption {\n /** Role key (servers/<server>.yaml). Used in answers. */\n role: string;\n /** Label shown in the portal (config `label`, defaults to the role name). */\n label: string;\n emoji: string;\n description: string;\n /** Discord role name and color (\"\" when the role has none). */\n name: string;\n color: string;\n}\n\nexport interface OnboardingStep {\n id: string;\n title: string;\n description: string;\n /** Several options may be selected. */\n multiple: boolean;\n /** At least one option must be selected. */\n required: boolean;\n options: OnboardingOption[];\n /** Role keys of this step the member currently has. */\n selected: string[];\n}\n\nexport interface OnboardingRole {\n key: string;\n id: string;\n name: string;\n color: string;\n}\n\n/** `GET /steps` */\nexport interface OnboardingSteps {\n title: string;\n intro: string;\n steps: OnboardingStep[];\n /** Role given when the flow is completed, if configured. */\n completedRole: OnboardingRole | null;\n completed: boolean;\n completedAt: string | null;\n}\n\n/** Answers: step id → selected role keys. */\nexport type OnboardingAnswers = Record<string, string[]>;\n\n/** `POST /complete` body. */\nexport interface OnboardingCompleteRequest {\n answers: OnboardingAnswers;\n}\n\n/** `POST /complete` response (200). Errors use the API error shape (`invalid`, 422/400). */\nexport interface OnboardingCompleteResponse {\n completed: true;\n completedAt: string;\n /** Member roles after the update. */\n roles: OnboardingRole[];\n /** Role keys added / removed by this call. */\n added: string[];\n removed: string[];\n /** Success message configured by the server. */\n message: string;\n}\n\n/** Typed wrapper over the onboarding plugin routes. */\nexport function onboardingApi(routes: PluginRoutes) {\n return {\n steps: (init?: { signal?: AbortSignal }) =>\n routes.get<OnboardingSteps>(\"/steps\", undefined, init),\n complete: (answers: OnboardingAnswers, init?: { signal?: AbortSignal }) =>\n routes.post<OnboardingCompleteResponse>(\n \"/complete\",\n { answers } satisfies OnboardingCompleteRequest,\n init,\n ),\n };\n}\n\nexport type OnboardingApi = ReturnType<typeof onboardingApi>;\n","/**\n * Contracts of the showcase plugins' portal routes (examples/showcase): `tickets` and\n * `levels`. They illustrate typing a plugin's routes on top of `client.plugin(...)`; extra\n * fields sent by a plugin are kept as is.\n */\nimport type { CallOptions, PluginRoutes } from \"./client.ts\";\n\nexport type TicketStatus = \"open\" | \"closed\";\n\nexport interface Ticket {\n /** Ticket number, as a string. */\n id: string;\n subject: string;\n status: TicketStatus;\n author: { id: string; displayName: string };\n createdAt: string;\n}\n\n/** tickets `GET /tickets` (moderator), newest first. */\nexport interface TicketList {\n items: Ticket[];\n}\n\nexport interface LeaderboardEntry {\n /** From 1. */\n rank: number;\n userId: string;\n displayName: string;\n avatarUrl: string | null;\n level: number;\n xp: number;\n}\n\n/** levels `GET /leaderboard` (public). */\nexport interface Leaderboard {\n items: LeaderboardEntry[];\n}\n\n/** Typed wrapper over the `tickets` plugin routes. */\nexport function ticketsApi(routes: PluginRoutes) {\n return {\n list: (query: { status?: TicketStatus } = {}, options?: CallOptions) =>\n routes.get<TicketList>(\"/tickets\", query, options),\n };\n}\n\n/** Typed wrapper over the `levels` plugin routes. */\nexport function levelsApi(routes: PluginRoutes) {\n return {\n leaderboard: (query: { limit?: number } = {}, options?: CallOptions) =>\n routes.get<Leaderboard>(\"/leaderboard\", query, options),\n /** levels `GET /me` (member): the viewer's own entry (shape owned by the plugin). */\n me: <T = LeaderboardEntry>(options?: CallOptions) => routes.get<T>(\"/me\", undefined, options),\n };\n}\n"],"mappings":";AAEA,MAAM,iBAA+C;CACnD,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;AACP;;AAGA,SAAgB,cAAc,QAA8B;CAC1D,OAAO,eAAe,YAAY,UAAU,MAAM,aAAa,QAAQ;AACzE;;;;;AAMA,IAAa,iBAAb,MAAa,uBAAuB,MAAM;;CAExC;;CAEA;;CAEA;;CAEA;;CAEA;;CAEA;;CAEA;CAEA,YAAY,MAUT;EACD,MAAM,KAAK,SAAS,KAAK,UAAU,KAAA,IAAY,KAAA,IAAY,EAA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,YAA0B,OAAO,IAAO,OAAO,KAAA,GAAW,OAAO;CAC9F;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cicord/client",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Typed, framework-agnostic client for the Cicord runtime HTTP API v1.",
5
5
  "keywords": [
6
6
  "api-client",