@easy-cms/core 0.14.0 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +980 -881
  2. package/dist/index.js +285 -17
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -56,14 +56,6 @@ declare const anyone: Access;
56
56
  declare const isLoggedIn: Access;
57
57
  declare const isAdmin: Access;
58
58
 
59
- /** What a preview token opens: one document of a collection, or one global. */
60
- type PreviewTarget = {
61
- readonly collection: string;
62
- readonly id: string;
63
- } | {
64
- readonly global: string;
65
- };
66
-
67
59
  interface Logger {
68
60
  info(message: string): void;
69
61
  warn(message: string): void;
@@ -335,959 +327,1056 @@ type Field = TextField | TextareaField | NumberField | BooleanField | DateField
335
327
  type FieldType = Field['type'];
336
328
  declare const FIELD_TYPES: readonly ["text", "textarea", "number", "boolean", "date", "email", "json", "select", "slug", "richText", "upload", "relationship", "array", "group", "blocks"];
337
329
 
338
- interface StoredFile {
339
- readonly body: Uint8Array;
340
- readonly size: number;
330
+ /** What a preview token opens: one document of a collection, or one global. */
331
+ type PreviewTarget = {
332
+ readonly collection: string;
333
+ readonly id: string;
334
+ } | {
335
+ readonly global: string;
336
+ };
337
+
338
+ interface LoginArgs {
339
+ readonly email: string;
340
+ readonly password: string;
341
+ /** Client IP, used together with the email for rate limiting. */
342
+ readonly ip?: string | undefined;
341
343
  }
342
- /** Where uploaded files live. Keys are generated by Easy CMS: `<name>-<random>.<ext>`. */
343
- interface StorageAdapter {
344
- readonly name: string;
345
- /** Called once with the project root, before any other method. */
346
- init?(args: {
347
- cwd: string;
348
- }): void | Promise<void>;
349
- put(key: string, data: Uint8Array, options: {
350
- contentType: string;
351
- }): Promise<void>;
352
- get(key: string): Promise<StoredFile | null>;
353
- delete(key: string): Promise<void>;
344
+ interface Session {
345
+ readonly user: AuthUser;
346
+ /** Signed session token, the value of the session cookie. */
347
+ readonly token: string;
348
+ /** Send back in the `X-CSRF-Token` header on cookie-authenticated writes. */
349
+ readonly csrfToken: string;
350
+ readonly expiresAt: string;
351
+ }
352
+ /** Login, logout and session verification. Available as `cms.auth`. */
353
+ declare class Auth {
354
+ private readonly cms;
355
+ constructor(cms: EasyCMS);
356
+ private get db();
357
+ private get config();
358
+ /** Checks credentials and starts a session. Throws `UnauthorizedError` or `TooManyRequestsError`. */
359
+ login(args: LoginArgs): Promise<Session>;
360
+ /** Creates the first admin. Only works while there are no users. */
361
+ registerFirstUser(args: {
362
+ email: string;
363
+ password: string;
364
+ name?: string;
365
+ }): Promise<Session>;
366
+ hasUsers(): Promise<boolean>;
367
+ /** Ends the session for a signed token. Unknown tokens are ignored. */
368
+ logout(signedToken: string): Promise<void>;
354
369
  /**
355
- * Public URL of a file, or `undefined` to serve it through the REST API
356
- * (`<api>/media/file/<key>`), as the local adapter does.
370
+ * Returns the user for a signed session token, or for an API key (`ecms_…`, with `apiKey` set
371
+ * on the user), or `null` if it is invalid or expired.
357
372
  */
358
- url?(key: string): string | undefined;
359
- }
360
- interface LocalStorageOptions {
361
- /** Directory, relative to the project root. Default `uploads`. */
362
- readonly dir?: string;
373
+ verify(signedToken: string | undefined | null): Promise<AuthUser | null>;
374
+ /** The CSRF token clients must echo for a signed session token. */
375
+ csrfFor(signedToken: string): string | undefined;
376
+ /** Starts a new session for a user, e.g. after they changed their own password. */
377
+ createSession(userId: ID): Promise<Session>;
378
+ /** Signs a user out everywhere. */
379
+ revokeSessions(userId: ID): Promise<void>;
380
+ /** The owner of an API key, limited by the key; `null` when unknown, expired or disabled. */
381
+ private verifyApiKey;
382
+ private startSession;
383
+ private findSession;
384
+ private toAuthUser;
385
+ private deleteExpiredSessions;
386
+ private windowStart;
387
+ private checkRateLimit;
388
+ private recordFailure;
389
+ private clearFailures;
363
390
  }
364
- /** Stores files on the local disk. Suitable for servers with a persistent filesystem. */
365
- declare function localStorage(options?: LocalStorageOptions): StorageAdapter;
366
391
 
367
- declare const WEBHOOK_EVENTS: readonly ["create", "update", "delete", "publish", "unpublish", "draft"];
368
- /**
369
- * `create`, `update`, `delete`: the stored document changed. `publish` / `unpublish`: its status
370
- * changed (sent with `create` or `update`). `draft`: only a draft was saved; what is live did not
371
- * change (collections with versions and drafts).
372
- */
373
- type WebhookEvent = (typeof WEBHOOK_EVENTS)[number];
374
- interface WebhookConfig {
375
- /** Where to POST events. */
376
- readonly url: string;
377
- /** Events to send. Default: all. */
378
- readonly events?: readonly WebhookEvent[];
379
- /** Collections to send events for. Default: all; `[]` for none. */
380
- readonly collections?: readonly string[];
381
- /** Globals to send events for. Default: all; `[]` for none. */
382
- readonly globals?: readonly string[];
383
- /** Signs each body: `x-easy-cms-signature: sha256=<hex HMAC-SHA256 of the body>`. */
384
- readonly secret?: string;
385
- /** Extra request headers, e.g. a token the receiver checks. */
386
- readonly headers?: Readonly<Record<string, string>>;
387
- }
388
- /** What a webhook receives as JSON. */
389
- interface WebhookPayload {
390
- readonly event: WebhookEvent;
391
- readonly collection?: string;
392
- readonly global?: string;
393
- readonly id?: ID;
394
- /** The stored document (every locale, no hidden fields); for `delete`, as it was. */
395
- readonly doc: Record<string, unknown>;
396
- /** ISO time of the change. */
397
- readonly timestamp: string;
392
+ type Simplify<T> = {
393
+ [K in keyof T]: T[K];
394
+ } & {};
395
+ type OptionValue<O> = O extends string ? O : O extends {
396
+ readonly value: infer V;
397
+ } ? V : never;
398
+ type SelectValue<F> = F extends {
399
+ readonly options: readonly (infer O extends SelectOption)[];
400
+ } ? F extends {
401
+ readonly hasMany: true;
402
+ } ? OptionValue<O>[] : OptionValue<O> : never;
403
+ /** The built-in users collection as seen by the type system (hidden fields left out). */
404
+ interface BuiltinUsersCollection {
405
+ readonly slug: 'users';
406
+ readonly fields: readonly [
407
+ {
408
+ readonly name: 'email';
409
+ readonly type: 'email';
410
+ readonly required: true;
411
+ },
412
+ {
413
+ readonly name: 'name';
414
+ readonly type: 'text';
415
+ },
416
+ {
417
+ readonly name: 'role';
418
+ readonly type: 'select';
419
+ readonly options: readonly string[];
420
+ readonly required: true;
421
+ },
422
+ {
423
+ readonly name: 'active';
424
+ readonly type: 'boolean';
425
+ }
426
+ ];
398
427
  }
399
-
400
- type Data$2 = Record<string, unknown>;
401
- type MaybePromise<T> = T | Promise<T>;
402
- type Operation = 'create' | 'update';
403
- interface HookBase {
404
- /** The user the operation runs for; `null` for anonymous or trusted Local API calls. */
405
- readonly user: AuthUser | null;
406
- /** The Local API, e.g. to query other collections or trigger a revalidation. */
407
- readonly cms: EasyCMS;
408
- /** Slug of the collection or global. */
409
- readonly slug: string;
428
+ /** The built-in API keys collection (`apiKeys: true`); the key's hash is left out. */
429
+ interface BuiltinApiKeysCollection {
430
+ readonly slug: 'api-keys';
431
+ readonly fields: readonly [
432
+ {
433
+ readonly name: 'name';
434
+ readonly type: 'text';
435
+ readonly required: true;
436
+ },
437
+ {
438
+ readonly name: 'permissions';
439
+ readonly type: 'json';
440
+ },
441
+ {
442
+ readonly name: 'expiresAt';
443
+ readonly type: 'date';
444
+ },
445
+ {
446
+ readonly name: 'prefix';
447
+ readonly type: 'text';
448
+ },
449
+ {
450
+ readonly name: 'user';
451
+ readonly type: 'relationship';
452
+ readonly to: 'users';
453
+ },
454
+ {
455
+ readonly name: 'lastUsedAt';
456
+ readonly type: 'date';
457
+ }
458
+ ];
410
459
  }
411
- type BeforeValidateHook = (args: HookBase & {
412
- data: Data$2;
413
- operation: Operation;
414
- originalDoc?: Data$2;
415
- }) => MaybePromise<Data$2 | undefined>;
416
- type BeforeChangeHook = (args: HookBase & {
417
- data: Data$2;
418
- operation: Operation;
419
- originalDoc?: Data$2;
420
- }) => MaybePromise<Data$2 | undefined>;
421
- type AfterChangeHook = (args: HookBase & {
422
- doc: Data$2;
423
- operation: Operation;
424
- previousDoc?: Data$2;
425
- }) => MaybePromise<void>;
426
- type BeforeDeleteHook = (args: HookBase & {
427
- id: ID;
428
- }) => MaybePromise<void>;
429
- type AfterDeleteHook = (args: HookBase & {
430
- id: ID;
431
- doc: Data$2;
432
- }) => MaybePromise<void>;
433
- type AfterReadHook = (args: HookBase & {
434
- doc: Data$2;
435
- }) => MaybePromise<Data$2 | undefined>;
436
- interface CollectionHooks {
437
- readonly beforeValidate?: readonly BeforeValidateHook[];
438
- readonly beforeChange?: readonly BeforeChangeHook[];
439
- readonly afterChange?: readonly AfterChangeHook[];
440
- readonly beforeDelete?: readonly BeforeDeleteHook[];
441
- readonly afterDelete?: readonly AfterDeleteHook[];
442
- readonly afterRead?: readonly AfterReadHook[];
460
+ /** `api-keys` when the config turns API keys on. */
461
+ type ApiKeysOf<C extends Config> = C extends {
462
+ readonly apiKeys: true;
463
+ } ? BuiltinApiKeysCollection : never;
464
+ /** Every collection of a config, including the built-in ones. */
465
+ type AllCollections<C extends Config> = NonNullable<C['collections']>[number] | BuiltinUsersCollection | BuiltinMediaCollection | ApiKeysOf<C>;
466
+ /** The built-in media collection; its documents are typed as `MediaDocument`. */
467
+ interface BuiltinMediaCollection {
468
+ readonly slug: 'media';
469
+ readonly fields: readonly [];
443
470
  }
444
- interface GlobalHooks {
445
- readonly beforeChange?: readonly BeforeChangeHook[];
446
- readonly afterChange?: readonly AfterChangeHook[];
447
- readonly afterRead?: readonly AfterReadHook[];
471
+ type CollectionBySlug<C extends Config, S> = Extract<AllCollections<C>, {
472
+ readonly slug: S;
473
+ }>;
474
+ /** Relationships are ids at depth 0 and documents when populated. */
475
+ type RelationValue<C extends Config, S> = [CollectionBySlug<C, S>] extends [never] ? ID | Record<string, unknown> : ID | CollectionDocument<C, S & string>;
476
+ interface MediaSize {
477
+ filename: string;
478
+ width: number;
479
+ height: number;
480
+ filesize: number;
481
+ url: string;
448
482
  }
449
- interface LocalizationConfig {
450
- /** Content locales, e.g. `['th', 'en']`. */
451
- readonly locales: readonly string[];
452
- /** The locale used when none is given; its values also fill empty ones. Default: the first. */
453
- readonly defaultLocale?: string;
454
- /** Reads return the default locale's value when a locale's value is empty. Default true. */
455
- readonly fallback?: boolean;
483
+ /** A document of the built-in `media` collection, as returned by the API. */
484
+ interface MediaDocument {
485
+ id: ID;
486
+ filename: string;
487
+ originalName?: string | null;
488
+ mimeType: string;
489
+ filesize: number;
490
+ width?: number | null;
491
+ height?: number | null;
492
+ alt?: string | null;
493
+ /** Public URL of the file. */
494
+ url: string;
495
+ /** Resized copies, when `upload.imageSizes` is set and sharp is installed. */
496
+ sizes: Record<string, MediaSize>;
497
+ createdAt: string;
498
+ updatedAt: string;
499
+ [field: string]: unknown;
456
500
  }
457
- /**
458
- * Where a document is shown on the site, for live preview in the admin: an absolute URL or a
459
- * path on the site's origin. Return `null` when the document has no page.
460
- */
461
- type PreviewURL = (args: {
462
- readonly doc: Record<string, unknown>;
463
- /** The content locale being edited (with `localization`), otherwise the admin locale. */
464
- readonly locale: string;
465
- }) => string | null | undefined;
466
- interface VersionsConfig {
467
- /** Versions kept per document; older ones are deleted. Default 50. */
468
- readonly max?: number;
469
- }
470
- /** Custom admin components for a collection's or global's edit page. */
471
- interface ContainerAdmin {
472
- /** Panels in the edit page's side column, below publishing (components from admin modules). */
473
- readonly sidebar?: readonly AdminComponent[];
474
- }
475
- interface CollectionConfig {
476
- /** URL and table name. Lowercase letters, digits, `-` and `_`. */
477
- readonly slug: string;
478
- readonly labels?: {
479
- readonly singular?: Label;
480
- readonly plural?: Label;
481
- };
482
- /** Icon in the admin menu. Default `file-text`. */
483
- readonly icon?: AdminIcon;
484
- /**
485
- * How the admin opens documents from the list: `drawer` slides a panel over the list, handy
486
- * for small collections (categories, tags). Default `page`. Collections with drafts, versions
487
- * or live preview always use the page.
488
- */
489
- readonly editIn?: 'page' | 'drawer';
490
- readonly fields: readonly Field[];
491
- /** Top-level field shown as the document title in the admin UI. */
492
- readonly useAsTitle?: string;
493
- /** Adds a `status` field (`draft` | `published`). */
501
+ type FieldValue<F extends Field, C extends Config = Config> = F extends {
502
+ readonly type: 'text' | 'textarea' | 'email' | 'slug' | 'date';
503
+ } ? string : F extends {
504
+ readonly type: 'number';
505
+ } ? number : F extends {
506
+ readonly type: 'boolean';
507
+ } ? boolean : F extends {
508
+ readonly type: 'json';
509
+ } ? unknown : F extends {
510
+ readonly type: 'select';
511
+ } ? SelectValue<F> : F extends {
512
+ readonly type: 'richText';
513
+ } ? RichTextDocument : F extends {
514
+ readonly type: 'upload';
515
+ } ? ID | MediaDocument : F extends {
516
+ readonly type: 'relationship';
517
+ readonly to: infer S;
518
+ } ? F extends {
519
+ readonly hasMany: true;
520
+ } ? RelationValue<C, S>[] : RelationValue<C, S> : F extends {
521
+ readonly type: 'array';
522
+ readonly fields: infer Sub extends readonly Field[];
523
+ } ? Simplify<FieldsValue<Sub, C> & {
524
+ id: string;
525
+ }>[] : F extends {
526
+ readonly type: 'group';
527
+ readonly fields: infer Sub extends readonly Field[];
528
+ } ? FieldsValue<Sub, C> : F extends {
529
+ readonly type: 'blocks';
530
+ readonly blocks: infer B extends readonly Block[];
531
+ } ? BlockValue<B[number], C>[] : never;
532
+ /** One row of a `blocks` field: the block's fields plus `id` and `blockType` (distributes over kinds). */
533
+ type BlockValue<B, C extends Config> = B extends {
534
+ readonly slug: infer S;
535
+ readonly fields: infer Sub extends readonly Field[];
536
+ } ? Simplify<FieldsValue<Sub, C> & {
537
+ id: string;
538
+ blockType: S;
539
+ }> : never;
540
+ type BlockInput<B> = B extends {
541
+ readonly slug: infer S;
542
+ readonly fields: infer Sub extends readonly Field[];
543
+ } ? Simplify<FieldsInput<Sub> & {
544
+ id?: string;
545
+ blockType: S;
546
+ }> : never;
547
+ type Visible<Fs extends readonly Field[]> = Exclude<Fs[number], {
548
+ readonly hidden: true;
549
+ }>;
550
+ /** Always set when read: required fields, and lists and groups (empty `[]` / `{}` otherwise). */
551
+ type Present = {
552
+ readonly required: true;
553
+ } | {
554
+ readonly type: 'array' | 'blocks' | 'group';
555
+ } | {
556
+ readonly hasMany: true;
557
+ };
558
+ type RequiredFields<Fs extends readonly Field[]> = Extract<Visible<Fs>, Present>;
559
+ type OptionalFields<Fs extends readonly Field[]> = Exclude<Visible<Fs>, Present>;
560
+ /** The shape of the data described by a list of fields. */
561
+ type FieldsValue<Fs extends readonly Field[], C extends Config = Config> = Simplify<{
562
+ -readonly [F in RequiredFields<Fs> as F['name']]: FieldValue<F, C>;
563
+ } & {
564
+ -readonly [F in OptionalFields<Fs> as F['name']]?: FieldValue<F, C> | null;
565
+ }>;
566
+ type SystemFields<T extends {
494
567
  readonly drafts?: boolean;
568
+ }> = {
569
+ id: ID;
570
+ createdAt: string;
571
+ updatedAt: string;
572
+ } & (T extends {
573
+ readonly drafts: true;
574
+ } ? {
575
+ status: 'draft' | 'published';
576
+ } : unknown);
577
+ type InferCollection<T extends CollectionConfig, C extends Config = Config> = Simplify<SystemFields<T> & FieldsValue<T['fields'], C>>;
578
+ type InferGlobal<T extends GlobalConfig, C extends Config = Config> = Simplify<
579
+ /** `null` until the global is saved for the first time. */
580
+ {
581
+ updatedAt: string | null;
582
+ } & (T extends {
583
+ readonly drafts: true;
584
+ } ? {
585
+ status: 'draft' | 'published';
586
+ } : unknown) & FieldsValue<T['fields'], C>>;
587
+ type CollectionSlug<C extends Config> = NonNullable<C['collections']>[number]['slug'] | 'users' | 'media' | ApiKeysOf<C>['slug'];
588
+ type GlobalSlug<C extends Config> = NonNullable<C['globals']>[number]['slug'];
589
+ /** Document type of a collection, e.g. `CollectionDocument<typeof config, 'posts'>`. */
590
+ type CollectionDocument<C extends Config, S extends CollectionSlug<C>> = S extends 'media' ? MediaDocument : InferCollection<CollectionBySlug<C, S>, C>;
591
+ /** Data type of a global, e.g. `GlobalDocument<typeof config, 'site'>`. */
592
+ type GlobalDocument<C extends Config, S extends GlobalSlug<C>> = InferGlobal<Extract<NonNullable<C['globals']>[number], {
593
+ readonly slug: S;
594
+ }>, C>;
595
+ type InputValue<F extends Field> = F extends {
596
+ readonly type: 'relationship';
597
+ } ? F extends {
598
+ readonly hasMany: true;
599
+ } ? readonly ID[] : ID : F extends {
600
+ readonly type: 'select';
601
+ readonly hasMany: true;
602
+ } ? Readonly<SelectValue<F>> : F extends {
603
+ readonly type: 'upload';
604
+ } ? ID : F extends {
605
+ readonly type: 'date';
606
+ } ? string | Date : F extends {
607
+ readonly type: 'array';
608
+ readonly fields: infer Sub extends readonly Field[];
609
+ } ? readonly Simplify<FieldsInput<Sub> & {
610
+ id?: string;
611
+ }>[] : F extends {
612
+ readonly type: 'group';
613
+ readonly fields: infer Sub extends readonly Field[];
614
+ } ? FieldsInput<Sub> : F extends {
615
+ readonly type: 'blocks';
616
+ readonly blocks: infer B extends readonly Block[];
617
+ } ? readonly BlockInput<B[number]>[] : FieldValue<F>;
618
+ /** Required fields must be given, unless Easy CMS can fill them (default value, slug from another field). */
619
+ type NeedsInput<F extends Field> = F extends {
620
+ readonly required: true;
621
+ } ? F extends {
622
+ readonly defaultValue: unknown;
623
+ } ? never : F extends {
624
+ readonly type: 'slug';
625
+ readonly from: string;
626
+ } ? never : F : never;
627
+ type FieldsInput<Fs extends readonly Field[]> = Simplify<{
628
+ -readonly [F in NeedsInput<Visible<Fs>> as F['name']]: InputValue<F>;
629
+ } & {
630
+ -readonly [F in Exclude<Visible<Fs>, NeedsInput<Visible<Fs>>> as F['name']]?: InputValue<F> | null;
631
+ }>;
632
+ type StatusInput<T> = T extends {
633
+ readonly drafts: true;
634
+ } ? {
635
+ status?: 'draft' | 'published';
636
+ } : unknown;
637
+ /** Users are created with a password, which is hashed and never returned. */
638
+ type PasswordInput<S, Required extends boolean> = S extends 'users' ? Required extends true ? {
639
+ password: string;
640
+ } : {
641
+ password?: string;
642
+ } : unknown;
643
+ /** Data accepted by `create`, e.g. `CreateInput<typeof config, 'posts'>`. */
644
+ type CreateInput<C extends Config, S extends CollectionSlug<C>> = Simplify<FieldsInput<CollectionBySlug<C, S>['fields']> & StatusInput<CollectionBySlug<C, S>> & PasswordInput<S, true>>;
645
+ /** Data accepted by `update`: any subset of `CreateInput`. */
646
+ type UpdateInput<C extends Config, S extends CollectionSlug<C>> = Partial<CreateInput<C, S>>;
647
+ /** Data accepted by `updateGlobal`. */
648
+ type GlobalInput<C extends Config, S extends GlobalSlug<C>> = Partial<Simplify<FieldsInput<Extract<NonNullable<C['globals']>[number], {
649
+ readonly slug: S;
650
+ }>['fields']> & StatusInput<Extract<NonNullable<C['globals']>[number], {
651
+ readonly slug: S;
652
+ }>>>>;
653
+
654
+ interface StoredFile {
655
+ readonly body: Uint8Array;
656
+ readonly size: number;
657
+ }
658
+ /** Where uploaded files live. Keys are generated by Easy CMS: `<name>-<random>.<ext>`. */
659
+ interface StorageAdapter {
660
+ readonly name: string;
661
+ /** Called once with the project root, before any other method. */
662
+ init?(args: {
663
+ cwd: string;
664
+ }): void | Promise<void>;
665
+ put(key: string, data: Uint8Array, options: {
666
+ contentType: string;
667
+ }): Promise<void>;
668
+ get(key: string): Promise<StoredFile | null>;
669
+ delete(key: string): Promise<void>;
495
670
  /**
496
- * Keep a snapshot of every save, to view history and restore. With `drafts`, a draft saved
497
- * on a published document is kept as a version and the published document stays live until
498
- * it is published again.
671
+ * Public URL of a file, or `undefined` to serve it through the REST API
672
+ * (`<api>/media/file/<key>`), as the local adapter does.
499
673
  */
500
- readonly versions?: boolean | VersionsConfig;
501
- /** Allow scheduling publish/unpublish for a later time (needs `drafts`). */
502
- readonly schedule?: boolean;
503
- /** Live preview: the page that shows a document, e.g. `({ doc }) => \`/posts/${doc.slug}\``. */
504
- readonly preview?: PreviewURL;
505
- readonly access?: CollectionAccess;
506
- readonly hooks?: CollectionHooks;
507
- /** Custom admin components. */
508
- readonly admin?: ContainerAdmin;
674
+ url?(key: string): string | undefined;
509
675
  }
510
- interface GlobalConfig {
511
- readonly slug: string;
512
- readonly label?: Label;
513
- /** Icon in the admin menu. Default `settings`. */
514
- readonly icon?: AdminIcon;
515
- readonly fields: readonly Field[];
516
- readonly drafts?: boolean;
517
- /** Keep a snapshot of every save. See `CollectionConfig.versions`. */
518
- readonly versions?: boolean | VersionsConfig;
519
- /** Allow scheduling publish/unpublish for a later time (needs `drafts`). */
520
- readonly schedule?: boolean;
521
- /** Live preview: the page that shows the global. See `CollectionConfig.preview`. */
522
- readonly preview?: PreviewURL;
523
- readonly access?: GlobalAccess;
524
- readonly hooks?: GlobalHooks;
525
- /** Custom admin components. */
526
- readonly admin?: ContainerAdmin;
676
+ interface LocalStorageOptions {
677
+ /** Directory, relative to the project root. Default `uploads`. */
678
+ readonly dir?: string;
527
679
  }
528
- type AdminLocale = 'en' | 'th';
529
- /** Icons a collection or global can show in the admin menu ([Lucide](https://lucide.dev) names). */
530
- declare const ADMIN_ICONS: readonly ["file-text", "newspaper", "book-open", "notebook", "folder", "tag", "tags", "image", "images", "video", "music", "file", "users", "user", "building", "store", "shopping-bag", "shopping-cart", "package", "box", "calendar", "calendar-days", "map-pin", "globe", "house", "layout-grid", "layers", "star", "heart", "message-square", "mail", "phone", "briefcase", "graduation-cap", "utensils", "car", "settings", "sliders-horizontal", "palette", "megaphone", "bell", "link", "quote", "circle-help", "award", "ticket", "camera"];
531
- type AdminIcon = (typeof ADMIN_ICONS)[number];
532
- /** Your or your client's brand in the admin UI. */
533
- interface AdminBrand {
534
- /** Shown in the menu, on the login page and in the browser tab. Default "Easy CMS". */
535
- readonly name?: string;
536
- /** Logo URL: a path on your site (`/logo.svg`) or an `https://` address. */
537
- readonly logo?: string;
538
- /** Main color as `#rrggbb`; lighter and darker shades are derived from it. */
539
- readonly color?: string;
680
+ /** Stores files on the local disk. Suitable for servers with a persistent filesystem. */
681
+ declare function localStorage(options?: LocalStorageOptions): StorageAdapter;
682
+
683
+ declare const DEFAULT_MAX_VERSIONS = 50;
684
+ /** One saved state of a document or global. */
685
+ interface VersionSummary {
686
+ readonly id: ID;
687
+ /** `draft` or `published` with drafts enabled, otherwise `null`. */
688
+ readonly status: 'draft' | 'published' | null;
689
+ /** The newest version: the document's current editable state. */
690
+ readonly latest: boolean;
691
+ /** Who saved it (user id), or `null` for saves without a user (scripts, seeds). */
692
+ readonly author: ID | null;
693
+ readonly createdAt: string;
540
694
  }
541
- interface AdminConfig {
542
- /** Where the admin UI is served. Default `/admin`. */
543
- readonly path?: string;
544
- /** Default admin UI language. Default `en`. */
545
- readonly locale?: AdminLocale;
546
- /** Name, logo and color of the admin UI. */
547
- readonly brand?: AdminBrand;
695
+ interface Version<T = Record<string, unknown>> extends VersionSummary {
696
+ /** The document as it was saved (hidden fields such as password hashes are never kept). */
697
+ readonly data: T;
698
+ }
699
+
700
+ type Data$2 = Record<string, unknown>;
701
+ type Slug<C extends Config> = string extends CollectionSlug<C> ? string : CollectionSlug<C>;
702
+ type GSlug<C extends Config> = string extends GlobalSlug<C> ? string : GlobalSlug<C>;
703
+ type Doc<C extends Config, S> = string extends CollectionSlug<C> ? RawDocument : CollectionDocument<C, S & CollectionSlug<C>>;
704
+ type Create<C extends Config, S> = string extends CollectionSlug<C> ? Data$2 : CreateInput<C, S & CollectionSlug<C>>;
705
+ type Update<C extends Config, S> = string extends CollectionSlug<C> ? Data$2 : UpdateInput<C, S & CollectionSlug<C>>;
706
+ type GDoc<C extends Config, S> = string extends GlobalSlug<C> ? Data$2 : GlobalDocument<C, S & GlobalSlug<C>>;
707
+ type GInput<C extends Config, S> = string extends GlobalSlug<C> ? Data$2 : GlobalInput<C, S & GlobalSlug<C>>;
708
+ interface AccessOptions {
548
709
  /**
549
- * The public site, for the admin's "View site" link: a path (`/`) or an `https://` URL.
550
- * Default `/` with Nuxt and Next.js; none with the standalone server.
710
+ * The Local API trusts its caller and skips access rules by default.
711
+ * Pass `false` (with `user`) to apply them, as the REST API does.
551
712
  */
552
- readonly siteUrl?: string;
713
+ readonly overrideAccess?: boolean;
714
+ /** The user to check access for. `null` = not logged in. */
715
+ readonly user?: AuthUser | null;
716
+ }
717
+ interface DepthOptions extends AccessOptions {
718
+ /** How many levels of relationships to populate. Default 1, maximum 3. */
719
+ readonly depth?: number;
553
720
  /**
554
- * Order of collections in the admin menu, by slug, e.g. `['posts', 'categories', 'media']`.
555
- * Collections not listed follow in config order, with the media library last.
721
+ * With `localization`: the locale to read, and for writes the locale the data is in. Default:
722
+ * the default locale. `'all'` reads (and writes) localized fields as `{ [locale]: value }`.
556
723
  */
557
- readonly menu?: readonly string[];
724
+ readonly locale?: string;
725
+ }
726
+ interface ReadOptions extends DepthOptions {
558
727
  /**
559
- * JavaScript modules the admin loads after login, which define Web Components used by
560
- * fields (`admin.component`, `admin.after`) and edit pages (`admin.sidebar`). Each entry is a
561
- * package export (`'@easy-cms/plugin-seo/admin'`) or a file path relative to the project root
562
- * (`'./admin/color-picker.js'`), resolved on the server. A module must be one self-contained ES
563
- * module file. Remote URLs are not allowed.
728
+ * Include drafts. By default only published documents of collections with
729
+ * `drafts: true` are returned, including when populating relationships (FR-DRF-04).
564
730
  */
565
- readonly modules?: readonly string[];
566
- }
567
- interface ImageSize {
568
- /** Key in `media.sizes`, e.g. `thumbnail`. */
569
- readonly name: string;
570
- readonly width: number;
571
- readonly height?: number;
572
- /** How to fit when both width and height are set. Default `cover`. */
573
- readonly fit?: 'cover' | 'contain' | 'inside';
574
- }
575
- interface UploadConfig {
576
- /** Directory for uploaded files with the default local storage, relative to the project root. Default `uploads`. */
577
- readonly dir?: string;
578
- /** Maximum file size in bytes. Default 10 MB. */
579
- readonly maxFileSize?: number;
580
- /** Allowed MIME types, detected from file contents. `image/*` style wildcards are allowed. */
581
- readonly mimeTypes?: readonly string[];
582
- /** Where files are stored. Default: local disk in `dir`. */
583
- readonly storage?: StorageAdapter;
584
- /** Resized copies generated for images when `sharp` is installed. */
585
- readonly imageSizes?: readonly ImageSize[];
731
+ readonly draft?: boolean;
732
+ /** Use the default locale's value when a localized value is empty. Default: `localization.fallback`. */
733
+ readonly fallbackLocale?: boolean;
586
734
  }
587
- interface RoutesConfig {
588
- /** Where the REST API is served. Default `/api/cms`. */
589
- readonly api?: string;
735
+ interface FindOptions extends ReadOptions {
736
+ readonly where?: Where;
737
+ /** Field path, `-` prefix for descending. Default `-createdAt`. */
738
+ readonly sort?: string | readonly string[];
739
+ /** Default 10. `0` returns every document. */
740
+ readonly limit?: number;
741
+ /** 1-based. Default 1. */
742
+ readonly page?: number;
590
743
  }
591
- interface AuthConfig {
592
- /** Roles a user can have. Must include `admin`. Default `['admin', 'editor']`. */
593
- readonly roles?: readonly string[];
594
- /** Session lifetime in seconds. Default 7 days. */
595
- readonly tokenExpiration?: number;
596
- /** Failed logins allowed per email (and IP) within `lockWindow`. Default 5. */
597
- readonly maxLoginAttempts?: number;
598
- /** Window for `maxLoginAttempts`, in seconds. Default 15 minutes. */
599
- readonly lockWindow?: number;
744
+ interface CreateEasyCMSOptions {
745
+ /** Project root. Default `process.cwd()`. */
746
+ readonly cwd?: string;
600
747
  /**
601
- * Origins allowed to send cookie-authenticated requests, besides the API's own origin.
602
- * Needed when the admin or frontend is served from another origin, or behind a proxy that rewrites the host.
748
+ * Run due scheduled jobs and webhook retries every minute in this process. Default: on when
749
+ * a collection or global has `schedule`, or `webhooks` is set. Turn it off where a cron calls
750
+ * `runJobs` (or `GET <api>/jobs/run`) instead.
603
751
  */
604
- readonly trustedOrigins?: readonly string[];
752
+ readonly scheduler?: boolean;
753
+ /** Default `verify` when `NODE_ENV=production`, otherwise `push`. */
754
+ readonly schema?: SchemaMode;
755
+ readonly logger?: Logger;
756
+ readonly interactive?: boolean;
605
757
  }
606
- /** What an endpoint's handler receives. */
607
- interface EndpointRequest {
608
- readonly request: Request;
609
- readonly url: URL;
610
- /** Values of `:name` segments in the endpoint's path. */
611
- readonly params: Readonly<Record<string, string>>;
612
- /** The logged-in user (session cookie or Bearer token), or `null`. */
613
- readonly user: AuthUser | null;
614
- /** The Local API. Pass `{ user, overrideAccess: false }` to apply the user's access rules. */
615
- readonly cms: EasyCMS;
616
- /** The request's JSON body, which must be an object (at most 1 MB). */
617
- json(): Promise<Record<string, unknown>>;
758
+ /** Connects to the database and returns the Local API. */
759
+ declare function createEasyCMS<const C extends Config>(config: C, options?: CreateEasyCMSOptions): Promise<EasyCMS<C>>;
760
+ /** A scheduled publish or unpublish. */
761
+ interface ScheduledJob {
762
+ readonly id: ID;
763
+ readonly action: 'publish' | 'unpublish';
764
+ /** ISO time the job runs at (or after). */
765
+ readonly runAt: string;
766
+ readonly state: 'pending' | 'done' | 'failed';
767
+ readonly error: string | null;
768
+ readonly author: ID | null;
618
769
  }
619
- /**
620
- * A custom REST endpoint, served under `routes.api`. Writes from the browser pass the same
621
- * CSRF check as the built-in endpoints.
622
- */
623
- interface Endpoint {
770
+ declare class EasyCMS<C extends Config = Config> {
771
+ readonly config: ResolvedConfig;
772
+ readonly db: Database;
773
+ readonly logger: Logger;
774
+ /** Login, logout and session checks. */
775
+ readonly auth: Auth;
776
+ /** Where uploaded files are stored. */
777
+ readonly storage: StorageAdapter;
778
+ /** Project root: relative paths in the config (e.g. `admin.modules`) start here. */
779
+ readonly cwd: string;
780
+ private readonly versions;
781
+ private readonly webhooks;
782
+ constructor(config: ResolvedConfig, db: Database, logger?: Logger, storage?: StorageAdapter, cwd?: string);
783
+ find<S extends Slug<C>>(collection: S, options?: FindOptions): Promise<PaginatedDocs<Doc<C, S>>>;
784
+ findById<S extends Slug<C>>(collection: S, id: ID, options?: ReadOptions): Promise<Doc<C, S> | null>;
785
+ count<S extends Slug<C>>(collection: S, options?: {
786
+ where?: Where;
787
+ draft?: boolean;
788
+ locale?: string;
789
+ } & AccessOptions): Promise<number>;
790
+ create<S extends Slug<C>>(collection: S, data: Create<C, S>, options?: DepthOptions): Promise<Doc<C, S>>;
791
+ /**
792
+ * Stores a file and creates its `media` document (FR-UPL). The type is detected from
793
+ * the contents; images get width/height, and resized copies when `sharp` is installed.
794
+ */
795
+ upload(file: {
796
+ data: Uint8Array;
797
+ name: string;
798
+ }, data?: Record<string, unknown>, options?: DepthOptions): Promise<MediaDocument>;
799
+ /**
800
+ * Creates an API key (needs `apiKeys: true`) and returns it once: only a hash is stored.
801
+ * With access enforced the key belongs to `user`; trusted calls name the owner in `data.user`.
802
+ */
803
+ createApiKey(data: {
804
+ name: string;
805
+ permissions?: ApiKeyPermissions;
806
+ expiresAt?: string | Date | null;
807
+ user?: ID;
808
+ }, options?: AccessOptions): Promise<{
809
+ key: string;
810
+ doc: Record<string, unknown>;
811
+ }>;
812
+ /** Public URL of a stored file. */
813
+ mediaURL(key: string): string;
814
+ update<S extends Slug<C>>(collection: S, id: ID, data: Update<C, S>, options?: DepthOptions): Promise<Doc<C, S>>;
815
+ /**
816
+ * Takes a document off the site: its status becomes `draft`. With versions and drafts, a plain
817
+ * `update` with `status: 'draft'` only saves a draft and leaves the published document live;
818
+ * this is how to unpublish it.
819
+ */
820
+ unpublish<S extends Slug<C>>(collection: S, id: ID, options?: DepthOptions): Promise<Doc<C, S>>;
821
+ /** Throws away the unpublished draft of a published document, going back to what is live. */
822
+ discardDraft<S extends Slug<C>>(collection: S, id: ID, options?: DepthOptions): Promise<Doc<C, S>>;
823
+ /** Saved versions of a document, newest first. Needs update access to the document. */
824
+ findVersions<S extends Slug<C>>(collection: S, id: ID, options?: AccessOptions & {
825
+ limit?: number;
826
+ page?: number;
827
+ }): Promise<PaginatedDocs<VersionSummary>>;
828
+ /** One saved version with the document as it was then. */
829
+ findVersion<S extends Slug<C>>(collection: S, id: ID, versionId: ID, options?: DepthOptions): Promise<Version<Doc<C, S>> | null>;
830
+ /**
831
+ * Makes an old version the current content, as a new version. With drafts it is restored as
832
+ * a draft (publish it to put it live); access, hooks and validation run as for `update`.
833
+ */
834
+ restoreVersion<S extends Slug<C>>(collection: S, id: ID, versionId: ID, options?: DepthOptions): Promise<Doc<C, S>>;
835
+ /**
836
+ * Live preview: the document as it would be read if `data` were saved on top of its current
837
+ * state (or as a new document when `id` is `null`), with relationships populated and
838
+ * `afterRead` hooks applied. Nothing is written. Also returns the page URL from `preview`.
839
+ */
840
+ preview<S extends Slug<C>>(collection: S, id: ID | null, data: Record<string, unknown>, options?: DepthOptions): Promise<LivePreview<Doc<C, S>>>;
841
+ /**
842
+ * A token that lets a page read one document's current draft for a while (default one hour),
843
+ * without a login: `GET /api/cms/:collection/:id?preview=<token>`. The admin adds one to the
844
+ * preview URL as `easy-cms-preview`, for sites on another origin.
845
+ */
846
+ createPreviewToken(target: {
847
+ collection: string;
848
+ id: ID;
849
+ } | {
850
+ global: string;
851
+ }, options?: {
852
+ expiresIn?: number;
853
+ }): string;
854
+ /** What a preview token opens, or `null` when it is invalid or expired. */
855
+ verifyPreviewToken(token: string | null | undefined): (PreviewTarget & {
856
+ expiresAt: number;
857
+ }) | null;
858
+ /** Live preview of a global. See `preview`. */
859
+ previewGlobal<S extends GSlug<C>>(slug: S, data: Record<string, unknown>, options?: DepthOptions): Promise<LivePreview<GDoc<C, S>>>;
860
+ /** Coerces preview input like a save would, keeping values that would fail validation. */
861
+ private previewDoc;
862
+ private previewURL;
863
+ private versionTarget;
864
+ private updateDocument;
865
+ delete<S extends Slug<C>>(collection: S, id: ID, options?: AccessOptions): Promise<Doc<C, S>>;
866
+ findGlobal<S extends GSlug<C>>(slug: S, options?: ReadOptions): Promise<GDoc<C, S>>;
867
+ updateGlobal<S extends GSlug<C>>(slug: S, data: GInput<C, S>, options?: DepthOptions): Promise<GDoc<C, S>>;
868
+ /** Takes a global off the site (`status: 'draft'`). See `unpublish`. */
869
+ unpublishGlobal<S extends GSlug<C>>(slug: S, options?: DepthOptions): Promise<GDoc<C, S>>;
870
+ /** Throws away the unpublished draft of a published global. */
871
+ discardGlobalDraft<S extends GSlug<C>>(slug: S, options?: DepthOptions): Promise<GDoc<C, S>>;
872
+ /** Saved versions of a global, newest first. Needs update access. */
873
+ findGlobalVersions<S extends GSlug<C>>(slug: S, options?: AccessOptions & {
874
+ limit?: number;
875
+ page?: number;
876
+ }): Promise<PaginatedDocs<VersionSummary>>;
877
+ findGlobalVersion<S extends GSlug<C>>(slug: S, versionId: ID, options?: DepthOptions): Promise<Version<GDoc<C, S>> | null>;
878
+ /** Makes an old version of a global current (as a draft when the global has drafts). */
879
+ restoreGlobalVersion<S extends GSlug<C>>(slug: S, versionId: ID, options?: DepthOptions): Promise<GDoc<C, S>>;
880
+ private globalVersionTarget;
881
+ /** The global's pending draft when it has one (see `withDrafts`), otherwise `saved`. */
882
+ private globalDraft;
883
+ private saveGlobal;
624
884
  /**
625
- * Path under the API, e.g. `/seo/generate` or `/stats/:collection`. The first segment must
626
- * not be a collection slug or one of `users`, `globals`, `admin`, `jobs`.
885
+ * What `user` may do with one document. Resolves `where`-style access
886
+ * against the document, so the admin UI can hide actions precisely.
627
887
  */
628
- readonly path: string;
629
- readonly method: 'get' | 'post' | 'put' | 'patch' | 'delete';
888
+ documentPermissions(collection: Slug<C>, id: ID, user: AuthUser | null): Promise<{
889
+ update: boolean;
890
+ delete: boolean;
891
+ }>;
892
+ /** Closes the database connection. */
630
893
  /**
631
- * Returns a `Response`, or a value that is sent as JSON. Throw an Easy CMS error
632
- * (`UnauthorizedError`, `ForbiddenError`, `ValidationError`, `NotFoundError`) for error responses.
894
+ * Waits until webhook deliveries in progress are done. Call it before a serverless function
895
+ * returns, which may otherwise stop them.
633
896
  */
634
- readonly handler: (request: EndpointRequest) => MaybePromise<unknown>;
635
- }
636
- /** Receives the config and returns a modified copy. Runs before validation. */
637
- type Plugin = (config: Config) => MaybePromise<Config>;
638
- interface Config {
639
- /** Signs sessions. At least 32 characters; read it from `process.env.EASY_CMS_SECRET`. */
640
- readonly secret: string;
641
- readonly db: DatabaseAdapter;
897
+ flushWebhooks(): Promise<void>;
898
+ destroy(): Promise<void>;
899
+ private schedulerTimer;
900
+ private running;
901
+ /** Runs `runJobs` every `interval` ms in this process (`createEasyCMS` does this by default). */
902
+ startScheduler(interval?: number): void;
642
903
  /**
643
- * Public origin of the app, e.g. `https://example.com`. When set, media URLs are absolute
644
- * so frontends on other origins can use them. Default: relative URLs.
904
+ * Runs due scheduled publishes and unpublishes, and retries failed webhook deliveries. What the
905
+ * scheduler and the cron endpoint (`GET <api>/jobs/run`) call.
645
906
  */
646
- readonly serverURL?: string;
907
+ runJobs(now?: Date): Promise<{
908
+ ran: number;
909
+ failed: number;
910
+ webhooks: {
911
+ sent: number;
912
+ failed: number;
913
+ };
914
+ }>;
647
915
  /**
648
- * Origins whose browser code may call the REST API (CORS), e.g. a Vite or React app on
649
- * another origin. `'*'` allows any origin for anonymous requests. Origins in
650
- * `auth.trustedOrigins` are always allowed, with cookies. Default: none.
916
+ * Tries webhook deliveries that are due for another attempt. Deliveries are kept in the
917
+ * database until they succeed, so they survive restarts.
651
918
  */
652
- readonly cors?: readonly string[] | '*';
919
+ retryWebhooks(now?: Date): Promise<{
920
+ sent: number;
921
+ failed: number;
922
+ }>;
923
+ /** Webhook deliveries until they succeed, stored in `webhook-deliveries`. */
924
+ private webhookQueue;
653
925
  /**
654
- * Lets a cron service run due scheduled jobs: `GET <api>/jobs/run` with
655
- * `Authorization: Bearer <cronSecret>`. Default: the `CRON_SECRET` environment variable (the
656
- * convention of Vercel Cron). Logged-in admins can always run jobs.
926
+ * Publishes or unpublishes documents whose scheduled time has come. Safe to call often, e.g.
927
+ * from a cron job (`GET <api>/jobs/run`) where no process keeps running.
657
928
  */
658
- readonly cronSecret?: string;
659
- /** Endpoints notified when content changes, e.g. to rebuild a static site. */
660
- readonly webhooks?: readonly WebhookConfig[];
661
- /** Content in several languages: fields with `localized: true` hold one value per locale. */
662
- readonly localization?: LocalizationConfig | null;
663
- readonly routes?: RoutesConfig;
664
- readonly admin?: AdminConfig;
665
- readonly upload?: UploadConfig;
666
- readonly auth?: AuthConfig;
929
+ runScheduled(now?: Date): Promise<{
930
+ ran: number;
931
+ failed: number;
932
+ }>;
933
+ /** Schedules a publish or unpublish, replacing a pending job with the same action. */
934
+ schedule<S extends Slug<C>>(collection: S, id: ID, job: {
935
+ action: 'publish' | 'unpublish';
936
+ at: Date | string;
937
+ }, options?: AccessOptions): Promise<ScheduledJob>;
938
+ /** Pending jobs of a document, soonest first. */
939
+ scheduled<S extends Slug<C>>(collection: S, id: ID, options?: AccessOptions): Promise<ScheduledJob[]>;
940
+ cancelSchedule<S extends Slug<C>>(collection: S, id: ID, jobId: ID, options?: AccessOptions): Promise<void>;
941
+ scheduleGlobal<S extends GSlug<C>>(slug: S, job: {
942
+ action: 'publish' | 'unpublish';
943
+ at: Date | string;
944
+ }, options?: AccessOptions): Promise<ScheduledJob>;
945
+ scheduledGlobal<S extends GSlug<C>>(slug: S, options?: AccessOptions): Promise<ScheduledJob[]>;
946
+ cancelGlobalSchedule<S extends GSlug<C>>(slug: S, jobId: ID, options?: AccessOptions): Promise<void>;
947
+ private scheduleTarget;
948
+ private globalScheduleTarget;
949
+ private addJob;
667
950
  /**
668
- * Collections. A collection with slug `users` adds fields, access or hooks
669
- * to the built-in users collection.
951
+ * The next pending jobs across all collections and globals, soonest first; with access
952
+ * enforced, only those the user may update.
670
953
  */
671
- readonly collections?: readonly CollectionConfig[];
672
- readonly globals?: readonly GlobalConfig[];
673
- /** Custom REST endpoints, e.g. from plugins. */
674
- readonly endpoints?: readonly Endpoint[];
675
- readonly plugins?: readonly Plugin[];
676
- }
677
- /** The config after plugins ran, validation passed and defaults were applied. */
678
- interface ResolvedConfig extends Omit<Config, 'cors' | 'localization' | 'routes' | 'admin' | 'upload' | 'auth' | 'collections' | 'globals' | 'endpoints' | 'plugins'> {
679
- readonly cors: readonly string[] | '*';
680
- /** `null` without localization. */
681
- readonly localization: Required<LocalizationConfig> | null;
682
- readonly routes: Required<RoutesConfig>;
683
- readonly admin: Required<AdminConfig>;
684
- readonly upload: Required<Omit<UploadConfig, 'storage'>> & Pick<UploadConfig, 'storage'>;
685
- readonly auth: Required<AuthConfig>;
686
- readonly collections: readonly CollectionConfig[];
687
- readonly globals: readonly GlobalConfig[];
688
- readonly endpoints: readonly Endpoint[];
689
- }
690
- /**
691
- * Declares the Easy CMS config. Returns it unchanged, keeping literal types
692
- * so document types can be inferred from it.
693
- */
694
- declare function defineConfig<const TConfig extends Config>(config: TConfig): TConfig;
695
-
696
- type Simplify<T> = {
697
- [K in keyof T]: T[K];
698
- } & {};
699
- type OptionValue<O> = O extends string ? O : O extends {
700
- readonly value: infer V;
701
- } ? V : never;
702
- type SelectValue<F> = F extends {
703
- readonly options: readonly (infer O extends SelectOption)[];
704
- } ? F extends {
705
- readonly hasMany: true;
706
- } ? OptionValue<O>[] : OptionValue<O> : never;
707
- /** The built-in users collection as seen by the type system (hidden fields left out). */
708
- interface BuiltinUsersCollection {
709
- readonly slug: 'users';
710
- readonly fields: readonly [
711
- {
712
- readonly name: 'email';
713
- readonly type: 'email';
714
- readonly required: true;
715
- },
716
- {
717
- readonly name: 'name';
718
- readonly type: 'text';
719
- },
720
- {
721
- readonly name: 'role';
722
- readonly type: 'select';
723
- readonly options: readonly string[];
724
- readonly required: true;
725
- },
726
- {
727
- readonly name: 'active';
728
- readonly type: 'boolean';
729
- }
730
- ];
731
- }
732
- /** Every collection of a config, including the built-in users collection. */
733
- type AllCollections<C extends Config> = NonNullable<C['collections']>[number] | BuiltinUsersCollection | BuiltinMediaCollection;
734
- /** The built-in media collection; its documents are typed as `MediaDocument`. */
735
- interface BuiltinMediaCollection {
736
- readonly slug: 'media';
737
- readonly fields: readonly [];
738
- }
739
- type CollectionBySlug<C extends Config, S> = Extract<AllCollections<C>, {
740
- readonly slug: S;
741
- }>;
742
- /** Relationships are ids at depth 0 and documents when populated. */
743
- type RelationValue<C extends Config, S> = [CollectionBySlug<C, S>] extends [never] ? ID | Record<string, unknown> : ID | CollectionDocument<C, S & string>;
744
- interface MediaSize {
745
- filename: string;
746
- width: number;
747
- height: number;
748
- filesize: number;
749
- url: string;
954
+ upcomingJobs(options?: AccessOptions & {
955
+ limit?: number;
956
+ }): Promise<(ScheduledJob & {
957
+ collection?: string;
958
+ global?: string;
959
+ doc: ID;
960
+ })[]>;
961
+ private pendingJobs;
962
+ private removeJob;
963
+ /** @internal */
964
+ collection(slug: string): CollectionConfig;
965
+ private global;
966
+ /** Refuses what a request's API key does not allow (see `ApiKeyPermissions`). */
967
+ private checkKey;
968
+ /** The query constraint read access adds, or `undefined` when there is none. Throws when denied. */
969
+ private readWhere;
970
+ private checkDocumentAccess;
971
+ private checkGlobalAccess;
972
+ private fieldChecker;
973
+ /** Runs afterRead hooks, populates relationships and removes what the caller may not see. */
974
+ private output;
975
+ /** Creates a document: access, input filtering, hooks, validation, then afterChange. */
976
+ private createDocument;
977
+ /** The locale for an operation; `undefined` without localization. Throws on unknown locales. */
978
+ private localeOf;
979
+ /** Stored localized maps → the values of the requested locale. */
980
+ private pick;
981
+ /** Input for one locale → stored localized maps, keeping the other locales from `current`. */
982
+ private toMaps;
983
+ /** Makes `where` match localized fields in the operation's locale. */
984
+ private whereFor;
985
+ /** Drafts are kept as versions (instead of unpublishing) when both are enabled. */
986
+ private separateDrafts;
987
+ /** Replaces published documents that have a newer draft with that draft. */
988
+ private withDrafts;
989
+ /** Sends webhook events for a change; `before` is the stored status before it, if any. */
990
+ private emit;
991
+ /** Records a version after a save, when the collection or global keeps versions. */
992
+ private saveVersion;
993
+ private hookArgs;
994
+ /**
995
+ * Runs hooks that may replace a value, passed as `data` (before hooks) or `doc` (afterRead).
996
+ * Returning `undefined` keeps the value; a throw cancels the operation.
997
+ */
998
+ private transform;
999
+ /** Runs hooks after the change is saved: failures are logged, never undo the save (NFR-REL-03). */
1000
+ private notify;
1001
+ /** Writes resized copies with sharp, when installed and configured. */
1002
+ private resizeImage;
1003
+ /** Validates, checks uniqueness and references. Returns clean data or throws `ValidationError`. */
1004
+ private prepare;
1005
+ /** Refuses changes that would leave no active admin (and lock everyone out). */
1006
+ private guardLastAdmin;
1007
+ private makeSlugsUnique;
1008
+ private checkUnique;
1009
+ private isTaken;
1010
+ private checkReferences;
750
1011
  }
751
- /** A document of the built-in `media` collection, as returned by the API. */
752
- interface MediaDocument {
753
- id: ID;
754
- filename: string;
755
- originalName?: string | null;
756
- mimeType: string;
757
- filesize: number;
758
- width?: number | null;
759
- height?: number | null;
760
- alt?: string | null;
761
- /** Public URL of the file. */
762
- url: string;
763
- /** Resized copies, when `upload.imageSizes` is set and sharp is installed. */
764
- sizes: Record<string, MediaSize>;
765
- createdAt: string;
766
- updatedAt: string;
767
- [field: string]: unknown;
1012
+ /** A document as live preview shows it, and the page to show it on. */
1013
+ interface LivePreview<T> {
1014
+ readonly doc: T;
1015
+ /** From the collection's `preview` function; `null` without one. */
1016
+ readonly url: string | null;
768
1017
  }
769
- type FieldValue<F extends Field, C extends Config = Config> = F extends {
770
- readonly type: 'text' | 'textarea' | 'email' | 'slug' | 'date';
771
- } ? string : F extends {
772
- readonly type: 'number';
773
- } ? number : F extends {
774
- readonly type: 'boolean';
775
- } ? boolean : F extends {
776
- readonly type: 'json';
777
- } ? unknown : F extends {
778
- readonly type: 'select';
779
- } ? SelectValue<F> : F extends {
780
- readonly type: 'richText';
781
- } ? RichTextDocument : F extends {
782
- readonly type: 'upload';
783
- } ? ID | MediaDocument : F extends {
784
- readonly type: 'relationship';
785
- readonly to: infer S;
786
- } ? F extends {
787
- readonly hasMany: true;
788
- } ? RelationValue<C, S>[] : RelationValue<C, S> : F extends {
789
- readonly type: 'array';
790
- readonly fields: infer Sub extends readonly Field[];
791
- } ? Simplify<FieldsValue<Sub, C> & {
792
- id: string;
793
- }>[] : F extends {
794
- readonly type: 'group';
795
- readonly fields: infer Sub extends readonly Field[];
796
- } ? FieldsValue<Sub, C> : F extends {
797
- readonly type: 'blocks';
798
- readonly blocks: infer B extends readonly Block[];
799
- } ? BlockValue<B[number], C>[] : never;
800
- /** One row of a `blocks` field: the block's fields plus `id` and `blockType` (distributes over kinds). */
801
- type BlockValue<B, C extends Config> = B extends {
802
- readonly slug: infer S;
803
- readonly fields: infer Sub extends readonly Field[];
804
- } ? Simplify<FieldsValue<Sub, C> & {
805
- id: string;
806
- blockType: S;
807
- }> : never;
808
- type BlockInput<B> = B extends {
809
- readonly slug: infer S;
810
- readonly fields: infer Sub extends readonly Field[];
811
- } ? Simplify<FieldsInput<Sub> & {
812
- id?: string;
813
- blockType: S;
814
- }> : never;
815
- type Visible<Fs extends readonly Field[]> = Exclude<Fs[number], {
816
- readonly hidden: true;
817
- }>;
818
- /** Always set when read: required fields, and lists and groups (empty `[]` / `{}` otherwise). */
819
- type Present = {
820
- readonly required: true;
821
- } | {
822
- readonly type: 'array' | 'blocks' | 'group';
823
- } | {
824
- readonly hasMany: true;
825
- };
826
- type RequiredFields<Fs extends readonly Field[]> = Extract<Visible<Fs>, Present>;
827
- type OptionalFields<Fs extends readonly Field[]> = Exclude<Visible<Fs>, Present>;
828
- /** The shape of the data described by a list of fields. */
829
- type FieldsValue<Fs extends readonly Field[], C extends Config = Config> = Simplify<{
830
- -readonly [F in RequiredFields<Fs> as F['name']]: FieldValue<F, C>;
831
- } & {
832
- -readonly [F in OptionalFields<Fs> as F['name']]?: FieldValue<F, C> | null;
833
- }>;
834
- type SystemFields<T extends {
835
- readonly drafts?: boolean;
836
- }> = {
837
- id: ID;
838
- createdAt: string;
839
- updatedAt: string;
840
- } & (T extends {
841
- readonly drafts: true;
842
- } ? {
843
- status: 'draft' | 'published';
844
- } : unknown);
845
- type InferCollection<T extends CollectionConfig, C extends Config = Config> = Simplify<SystemFields<T> & FieldsValue<T['fields'], C>>;
846
- type InferGlobal<T extends GlobalConfig, C extends Config = Config> = Simplify<
847
- /** `null` until the global is saved for the first time. */
848
- {
849
- updatedAt: string | null;
850
- } & (T extends {
851
- readonly drafts: true;
852
- } ? {
853
- status: 'draft' | 'published';
854
- } : unknown) & FieldsValue<T['fields'], C>>;
855
- type CollectionSlug<C extends Config> = NonNullable<C['collections']>[number]['slug'] | 'users' | 'media';
856
- type GlobalSlug<C extends Config> = NonNullable<C['globals']>[number]['slug'];
857
- /** Document type of a collection, e.g. `CollectionDocument<typeof config, 'posts'>`. */
858
- type CollectionDocument<C extends Config, S extends CollectionSlug<C>> = S extends 'media' ? MediaDocument : InferCollection<CollectionBySlug<C, S>, C>;
859
- /** Data type of a global, e.g. `GlobalDocument<typeof config, 'site'>`. */
860
- type GlobalDocument<C extends Config, S extends GlobalSlug<C>> = InferGlobal<Extract<NonNullable<C['globals']>[number], {
861
- readonly slug: S;
862
- }>, C>;
863
- type InputValue<F extends Field> = F extends {
864
- readonly type: 'relationship';
865
- } ? F extends {
866
- readonly hasMany: true;
867
- } ? readonly ID[] : ID : F extends {
868
- readonly type: 'select';
869
- readonly hasMany: true;
870
- } ? Readonly<SelectValue<F>> : F extends {
871
- readonly type: 'upload';
872
- } ? ID : F extends {
873
- readonly type: 'date';
874
- } ? string | Date : F extends {
875
- readonly type: 'array';
876
- readonly fields: infer Sub extends readonly Field[];
877
- } ? readonly Simplify<FieldsInput<Sub> & {
878
- id?: string;
879
- }>[] : F extends {
880
- readonly type: 'group';
881
- readonly fields: infer Sub extends readonly Field[];
882
- } ? FieldsInput<Sub> : F extends {
883
- readonly type: 'blocks';
884
- readonly blocks: infer B extends readonly Block[];
885
- } ? readonly BlockInput<B[number]>[] : FieldValue<F>;
886
- /** Required fields must be given, unless Easy CMS can fill them (default value, slug from another field). */
887
- type NeedsInput<F extends Field> = F extends {
888
- readonly required: true;
889
- } ? F extends {
890
- readonly defaultValue: unknown;
891
- } ? never : F extends {
892
- readonly type: 'slug';
893
- readonly from: string;
894
- } ? never : F : never;
895
- type FieldsInput<Fs extends readonly Field[]> = Simplify<{
896
- -readonly [F in NeedsInput<Visible<Fs>> as F['name']]: InputValue<F>;
897
- } & {
898
- -readonly [F in Exclude<Visible<Fs>, NeedsInput<Visible<Fs>>> as F['name']]?: InputValue<F> | null;
899
- }>;
900
- type StatusInput<T> = T extends {
901
- readonly drafts: true;
902
- } ? {
903
- status?: 'draft' | 'published';
904
- } : unknown;
905
- /** Users are created with a password, which is hashed and never returned. */
906
- type PasswordInput<S, Required extends boolean> = S extends 'users' ? Required extends true ? {
907
- password: string;
908
- } : {
909
- password?: string;
910
- } : unknown;
911
- /** Data accepted by `create`, e.g. `CreateInput<typeof config, 'posts'>`. */
912
- type CreateInput<C extends Config, S extends CollectionSlug<C>> = Simplify<FieldsInput<CollectionBySlug<C, S>['fields']> & StatusInput<CollectionBySlug<C, S>> & PasswordInput<S, true>>;
913
- /** Data accepted by `update`: any subset of `CreateInput`. */
914
- type UpdateInput<C extends Config, S extends CollectionSlug<C>> = Partial<CreateInput<C, S>>;
915
- /** Data accepted by `updateGlobal`. */
916
- type GlobalInput<C extends Config, S extends GlobalSlug<C>> = Partial<Simplify<FieldsInput<Extract<NonNullable<C['globals']>[number], {
917
- readonly slug: S;
918
- }>['fields']> & StatusInput<Extract<NonNullable<C['globals']>[number], {
919
- readonly slug: S;
920
- }>>>>;
921
1018
 
922
- declare const DEFAULT_MAX_VERSIONS = 50;
923
- /** One saved state of a document or global. */
924
- interface VersionSummary {
925
- readonly id: ID;
926
- /** `draft` or `published` with drafts enabled, otherwise `null`. */
927
- readonly status: 'draft' | 'published' | null;
928
- /** The newest version: the document's current editable state. */
929
- readonly latest: boolean;
930
- /** Who saved it (user id), or `null` for saves without a user (scripts, seeds). */
931
- readonly author: ID | null;
932
- readonly createdAt: string;
1019
+ declare const WEBHOOK_EVENTS: readonly ["create", "update", "delete", "publish", "unpublish", "draft"];
1020
+ /**
1021
+ * `create`, `update`, `delete`: the stored document changed. `publish` / `unpublish`: its status
1022
+ * changed (sent with `create` or `update`). `draft`: only a draft was saved; what is live did not
1023
+ * change (collections with versions and drafts).
1024
+ */
1025
+ type WebhookEvent = (typeof WEBHOOK_EVENTS)[number];
1026
+ interface WebhookConfig {
1027
+ /** Where to POST events. */
1028
+ readonly url: string;
1029
+ /** Events to send. Default: all. */
1030
+ readonly events?: readonly WebhookEvent[];
1031
+ /** Collections to send events for. Default: all; `[]` for none. */
1032
+ readonly collections?: readonly string[];
1033
+ /** Globals to send events for. Default: all; `[]` for none. */
1034
+ readonly globals?: readonly string[];
1035
+ /** Signs each body: `x-easy-cms-signature: sha256=<hex HMAC-SHA256 of the body>`. */
1036
+ readonly secret?: string;
1037
+ /** Extra request headers, e.g. a token the receiver checks. */
1038
+ readonly headers?: Readonly<Record<string, string>>;
933
1039
  }
934
- interface Version<T = Record<string, unknown>> extends VersionSummary {
935
- /** The document as it was saved (hidden fields such as password hashes are never kept). */
936
- readonly data: T;
1040
+ /** What a webhook receives as JSON. */
1041
+ interface WebhookPayload {
1042
+ readonly event: WebhookEvent;
1043
+ readonly collection?: string;
1044
+ readonly global?: string;
1045
+ readonly id?: ID;
1046
+ /** The stored document (every locale, no hidden fields); for `delete`, as it was. */
1047
+ readonly doc: Record<string, unknown>;
1048
+ /** ISO time of the change. */
1049
+ readonly timestamp: string;
937
1050
  }
938
1051
 
939
1052
  type Data$1 = Record<string, unknown>;
940
- type Slug<C extends Config> = string extends CollectionSlug<C> ? string : CollectionSlug<C>;
941
- type GSlug<C extends Config> = string extends GlobalSlug<C> ? string : GlobalSlug<C>;
942
- type Doc<C extends Config, S> = string extends CollectionSlug<C> ? RawDocument : CollectionDocument<C, S & CollectionSlug<C>>;
943
- type Create<C extends Config, S> = string extends CollectionSlug<C> ? Data$1 : CreateInput<C, S & CollectionSlug<C>>;
944
- type Update<C extends Config, S> = string extends CollectionSlug<C> ? Data$1 : UpdateInput<C, S & CollectionSlug<C>>;
945
- type GDoc<C extends Config, S> = string extends GlobalSlug<C> ? Data$1 : GlobalDocument<C, S & GlobalSlug<C>>;
946
- type GInput<C extends Config, S> = string extends GlobalSlug<C> ? Data$1 : GlobalInput<C, S & GlobalSlug<C>>;
947
- interface AccessOptions {
948
- /**
949
- * The Local API trusts its caller and skips access rules by default.
950
- * Pass `false` (with `user`) to apply them, as the REST API does.
951
- */
952
- readonly overrideAccess?: boolean;
953
- /** The user to check access for. `null` = not logged in. */
954
- readonly user?: AuthUser | null;
1053
+ type MaybePromise<T> = T | Promise<T>;
1054
+ type Operation = 'create' | 'update';
1055
+ interface HookBase {
1056
+ /** The user the operation runs for; `null` for anonymous or trusted Local API calls. */
1057
+ readonly user: AuthUser | null;
1058
+ /** The Local API, e.g. to query other collections or trigger a revalidation. */
1059
+ readonly cms: EasyCMS;
1060
+ /** Slug of the collection or global. */
1061
+ readonly slug: string;
955
1062
  }
956
- interface DepthOptions extends AccessOptions {
957
- /** How many levels of relationships to populate. Default 1, maximum 3. */
958
- readonly depth?: number;
959
- /**
960
- * With `localization`: the locale to read, and for writes the locale the data is in. Default:
961
- * the default locale. `'all'` reads (and writes) localized fields as `{ [locale]: value }`.
962
- */
963
- readonly locale?: string;
1063
+ type BeforeValidateHook = (args: HookBase & {
1064
+ data: Data$1;
1065
+ operation: Operation;
1066
+ originalDoc?: Data$1;
1067
+ }) => MaybePromise<Data$1 | undefined>;
1068
+ type BeforeChangeHook = (args: HookBase & {
1069
+ data: Data$1;
1070
+ operation: Operation;
1071
+ originalDoc?: Data$1;
1072
+ }) => MaybePromise<Data$1 | undefined>;
1073
+ type AfterChangeHook = (args: HookBase & {
1074
+ doc: Data$1;
1075
+ operation: Operation;
1076
+ previousDoc?: Data$1;
1077
+ }) => MaybePromise<void>;
1078
+ type BeforeDeleteHook = (args: HookBase & {
1079
+ id: ID;
1080
+ }) => MaybePromise<void>;
1081
+ type AfterDeleteHook = (args: HookBase & {
1082
+ id: ID;
1083
+ doc: Data$1;
1084
+ }) => MaybePromise<void>;
1085
+ type AfterReadHook = (args: HookBase & {
1086
+ doc: Data$1;
1087
+ }) => MaybePromise<Data$1 | undefined>;
1088
+ interface CollectionHooks {
1089
+ readonly beforeValidate?: readonly BeforeValidateHook[];
1090
+ readonly beforeChange?: readonly BeforeChangeHook[];
1091
+ readonly afterChange?: readonly AfterChangeHook[];
1092
+ readonly beforeDelete?: readonly BeforeDeleteHook[];
1093
+ readonly afterDelete?: readonly AfterDeleteHook[];
1094
+ readonly afterRead?: readonly AfterReadHook[];
964
1095
  }
965
- interface ReadOptions extends DepthOptions {
966
- /**
967
- * Include drafts. By default only published documents of collections with
968
- * `drafts: true` are returned, including when populating relationships (FR-DRF-04).
969
- */
970
- readonly draft?: boolean;
971
- /** Use the default locale's value when a localized value is empty. Default: `localization.fallback`. */
972
- readonly fallbackLocale?: boolean;
1096
+ interface GlobalHooks {
1097
+ readonly beforeChange?: readonly BeforeChangeHook[];
1098
+ readonly afterChange?: readonly AfterChangeHook[];
1099
+ readonly afterRead?: readonly AfterReadHook[];
973
1100
  }
974
- interface FindOptions extends ReadOptions {
975
- readonly where?: Where;
976
- /** Field path, `-` prefix for descending. Default `-createdAt`. */
977
- readonly sort?: string | readonly string[];
978
- /** Default 10. `0` returns every document. */
979
- readonly limit?: number;
980
- /** 1-based. Default 1. */
981
- readonly page?: number;
1101
+ interface LocalizationConfig {
1102
+ /** Content locales, e.g. `['th', 'en']`. */
1103
+ readonly locales: readonly string[];
1104
+ /** The locale used when none is given; its values also fill empty ones. Default: the first. */
1105
+ readonly defaultLocale?: string;
1106
+ /** Reads return the default locale's value when a locale's value is empty. Default true. */
1107
+ readonly fallback?: boolean;
982
1108
  }
983
- interface CreateEasyCMSOptions {
984
- /** Project root. Default `process.cwd()`. */
985
- readonly cwd?: string;
986
- /**
987
- * Run due scheduled jobs and webhook retries every minute in this process. Default: on when
988
- * a collection or global has `schedule`, or `webhooks` is set. Turn it off where a cron calls
989
- * `runJobs` (or `GET <api>/jobs/run`) instead.
990
- */
991
- readonly scheduler?: boolean;
992
- /** Default `verify` when `NODE_ENV=production`, otherwise `push`. */
993
- readonly schema?: SchemaMode;
994
- readonly logger?: Logger;
995
- readonly interactive?: boolean;
1109
+ /**
1110
+ * Where a document is shown on the site, for live preview in the admin: an absolute URL or a
1111
+ * path on the site's origin. Return `null` when the document has no page.
1112
+ */
1113
+ type PreviewURL = (args: {
1114
+ readonly doc: Record<string, unknown>;
1115
+ /** The content locale being edited (with `localization`), otherwise the admin locale. */
1116
+ readonly locale: string;
1117
+ }) => string | null | undefined;
1118
+ interface VersionsConfig {
1119
+ /** Versions kept per document; older ones are deleted. Default 50. */
1120
+ readonly max?: number;
996
1121
  }
997
- /** Connects to the database and returns the Local API. */
998
- declare function createEasyCMS<const C extends Config>(config: C, options?: CreateEasyCMSOptions): Promise<EasyCMS<C>>;
999
- /** A scheduled publish or unpublish. */
1000
- interface ScheduledJob {
1001
- readonly id: ID;
1002
- readonly action: 'publish' | 'unpublish';
1003
- /** ISO time the job runs at (or after). */
1004
- readonly runAt: string;
1005
- readonly state: 'pending' | 'done' | 'failed';
1006
- readonly error: string | null;
1007
- readonly author: ID | null;
1122
+ /** Custom admin components for a collection's or global's edit page. */
1123
+ interface ContainerAdmin {
1124
+ /** Panels in the edit page's side column, below publishing (components from admin modules). */
1125
+ readonly sidebar?: readonly AdminComponent[];
1008
1126
  }
1009
- declare class EasyCMS<C extends Config = Config> {
1010
- readonly config: ResolvedConfig;
1011
- readonly db: Database;
1012
- readonly logger: Logger;
1013
- /** Login, logout and session checks. */
1014
- readonly auth: Auth;
1015
- /** Where uploaded files are stored. */
1016
- readonly storage: StorageAdapter;
1017
- /** Project root: relative paths in the config (e.g. `admin.modules`) start here. */
1018
- readonly cwd: string;
1019
- private readonly versions;
1020
- private readonly webhooks;
1021
- constructor(config: ResolvedConfig, db: Database, logger?: Logger, storage?: StorageAdapter, cwd?: string);
1022
- find<S extends Slug<C>>(collection: S, options?: FindOptions): Promise<PaginatedDocs<Doc<C, S>>>;
1023
- findById<S extends Slug<C>>(collection: S, id: ID, options?: ReadOptions): Promise<Doc<C, S> | null>;
1024
- count<S extends Slug<C>>(collection: S, options?: {
1025
- where?: Where;
1026
- draft?: boolean;
1027
- locale?: string;
1028
- } & AccessOptions): Promise<number>;
1029
- create<S extends Slug<C>>(collection: S, data: Create<C, S>, options?: DepthOptions): Promise<Doc<C, S>>;
1127
+ interface CollectionConfig {
1128
+ /** URL and table name. Lowercase letters, digits, `-` and `_`. */
1129
+ readonly slug: string;
1130
+ readonly labels?: {
1131
+ readonly singular?: Label;
1132
+ readonly plural?: Label;
1133
+ };
1134
+ /** Icon in the admin menu. Default `file-text`. */
1135
+ readonly icon?: AdminIcon;
1030
1136
  /**
1031
- * Stores a file and creates its `media` document (FR-UPL). The type is detected from
1032
- * the contents; images get width/height, and resized copies when `sharp` is installed.
1137
+ * How the admin opens documents from the list: `drawer` slides a panel over the list, handy
1138
+ * for small collections (categories, tags). Default `page`. Collections with drafts, versions
1139
+ * or live preview always use the page.
1033
1140
  */
1034
- upload(file: {
1035
- data: Uint8Array;
1036
- name: string;
1037
- }, data?: Record<string, unknown>, options?: DepthOptions): Promise<MediaDocument>;
1038
- /** Public URL of a stored file. */
1039
- mediaURL(key: string): string;
1040
- update<S extends Slug<C>>(collection: S, id: ID, data: Update<C, S>, options?: DepthOptions): Promise<Doc<C, S>>;
1141
+ readonly editIn?: 'page' | 'drawer';
1142
+ readonly fields: readonly Field[];
1143
+ /** Top-level field shown as the document title in the admin UI. */
1144
+ readonly useAsTitle?: string;
1145
+ /** Adds a `status` field (`draft` | `published`). */
1146
+ readonly drafts?: boolean;
1041
1147
  /**
1042
- * Takes a document off the site: its status becomes `draft`. With versions and drafts, a plain
1043
- * `update` with `status: 'draft'` only saves a draft and leaves the published document live;
1044
- * this is how to unpublish it.
1148
+ * Keep a snapshot of every save, to view history and restore. With `drafts`, a draft saved
1149
+ * on a published document is kept as a version and the published document stays live until
1150
+ * it is published again.
1045
1151
  */
1046
- unpublish<S extends Slug<C>>(collection: S, id: ID, options?: DepthOptions): Promise<Doc<C, S>>;
1047
- /** Throws away the unpublished draft of a published document, going back to what is live. */
1048
- discardDraft<S extends Slug<C>>(collection: S, id: ID, options?: DepthOptions): Promise<Doc<C, S>>;
1049
- /** Saved versions of a document, newest first. Needs update access to the document. */
1050
- findVersions<S extends Slug<C>>(collection: S, id: ID, options?: AccessOptions & {
1051
- limit?: number;
1052
- page?: number;
1053
- }): Promise<PaginatedDocs<VersionSummary>>;
1054
- /** One saved version with the document as it was then. */
1055
- findVersion<S extends Slug<C>>(collection: S, id: ID, versionId: ID, options?: DepthOptions): Promise<Version<Doc<C, S>> | null>;
1152
+ readonly versions?: boolean | VersionsConfig;
1153
+ /** Allow scheduling publish/unpublish for a later time (needs `drafts`). */
1154
+ readonly schedule?: boolean;
1155
+ /** Live preview: the page that shows a document, e.g. `({ doc }) => \`/posts/${doc.slug}\``. */
1156
+ readonly preview?: PreviewURL;
1157
+ readonly access?: CollectionAccess;
1158
+ readonly hooks?: CollectionHooks;
1159
+ /** Custom admin components. */
1160
+ readonly admin?: ContainerAdmin;
1161
+ }
1162
+ interface GlobalConfig {
1163
+ readonly slug: string;
1164
+ readonly label?: Label;
1165
+ /** Icon in the admin menu. Default `settings`. */
1166
+ readonly icon?: AdminIcon;
1167
+ readonly fields: readonly Field[];
1168
+ readonly drafts?: boolean;
1169
+ /** Keep a snapshot of every save. See `CollectionConfig.versions`. */
1170
+ readonly versions?: boolean | VersionsConfig;
1171
+ /** Allow scheduling publish/unpublish for a later time (needs `drafts`). */
1172
+ readonly schedule?: boolean;
1173
+ /** Live preview: the page that shows the global. See `CollectionConfig.preview`. */
1174
+ readonly preview?: PreviewURL;
1175
+ readonly access?: GlobalAccess;
1176
+ readonly hooks?: GlobalHooks;
1177
+ /** Custom admin components. */
1178
+ readonly admin?: ContainerAdmin;
1179
+ }
1180
+ type AdminLocale = 'en' | 'th';
1181
+ /** Icons a collection or global can show in the admin menu ([Lucide](https://lucide.dev) names). */
1182
+ declare const ADMIN_ICONS: readonly ["file-text", "newspaper", "book-open", "notebook", "folder", "tag", "tags", "image", "images", "video", "music", "file", "users", "user", "building", "store", "shopping-bag", "shopping-cart", "package", "box", "calendar", "calendar-days", "map-pin", "globe", "house", "layout-grid", "layers", "star", "heart", "message-square", "mail", "phone", "briefcase", "graduation-cap", "utensils", "car", "settings", "sliders-horizontal", "palette", "megaphone", "bell", "link", "quote", "circle-help", "award", "ticket", "camera", "key"];
1183
+ type AdminIcon = (typeof ADMIN_ICONS)[number];
1184
+ /** Your or your client's brand in the admin UI. */
1185
+ interface AdminBrand {
1186
+ /** Shown in the menu, on the login page and in the browser tab. Default "Easy CMS". */
1187
+ readonly name?: string;
1188
+ /** Logo URL: a path on your site (`/logo.svg`) or an `https://` address. */
1189
+ readonly logo?: string;
1190
+ /** Main color as `#rrggbb`; lighter and darker shades are derived from it. */
1191
+ readonly color?: string;
1192
+ }
1193
+ interface AdminConfig {
1194
+ /** Where the admin UI is served. Default `/admin`. */
1195
+ readonly path?: string;
1196
+ /** Default admin UI language. Default `en`. */
1197
+ readonly locale?: AdminLocale;
1198
+ /** Name, logo and color of the admin UI. */
1199
+ readonly brand?: AdminBrand;
1056
1200
  /**
1057
- * Makes an old version the current content, as a new version. With drafts it is restored as
1058
- * a draft (publish it to put it live); access, hooks and validation run as for `update`.
1201
+ * The public site, for the admin's "View site" link: a path (`/`) or an `https://` URL.
1202
+ * Default `/` with Nuxt and Next.js; none with the standalone server.
1059
1203
  */
1060
- restoreVersion<S extends Slug<C>>(collection: S, id: ID, versionId: ID, options?: DepthOptions): Promise<Doc<C, S>>;
1204
+ readonly siteUrl?: string;
1061
1205
  /**
1062
- * Live preview: the document as it would be read if `data` were saved on top of its current
1063
- * state (or as a new document when `id` is `null`), with relationships populated and
1064
- * `afterRead` hooks applied. Nothing is written. Also returns the page URL from `preview`.
1206
+ * Order of collections in the admin menu, by slug, e.g. `['posts', 'categories', 'media']`.
1207
+ * Collections not listed follow in config order, with the media library last.
1065
1208
  */
1066
- preview<S extends Slug<C>>(collection: S, id: ID | null, data: Record<string, unknown>, options?: DepthOptions): Promise<LivePreview<Doc<C, S>>>;
1209
+ readonly menu?: readonly string[];
1067
1210
  /**
1068
- * A token that lets a page read one document's current draft for a while (default one hour),
1069
- * without a login: `GET /api/cms/:collection/:id?preview=<token>`. The admin adds one to the
1070
- * preview URL as `easy-cms-preview`, for sites on another origin.
1211
+ * JavaScript modules the admin loads after login, which define Web Components used by
1212
+ * fields (`admin.component`, `admin.after`) and edit pages (`admin.sidebar`). Each entry is a
1213
+ * package export (`'@easy-cms/plugin-seo/admin'`) or a file path relative to the project root
1214
+ * (`'./admin/color-picker.js'`), resolved on the server. A module must be one self-contained ES
1215
+ * module file. Remote URLs are not allowed.
1071
1216
  */
1072
- createPreviewToken(target: {
1073
- collection: string;
1074
- id: ID;
1075
- } | {
1076
- global: string;
1077
- }, options?: {
1078
- expiresIn?: number;
1079
- }): string;
1080
- /** What a preview token opens, or `null` when it is invalid or expired. */
1081
- verifyPreviewToken(token: string | null | undefined): (PreviewTarget & {
1082
- expiresAt: number;
1083
- }) | null;
1084
- /** Live preview of a global. See `preview`. */
1085
- previewGlobal<S extends GSlug<C>>(slug: S, data: Record<string, unknown>, options?: DepthOptions): Promise<LivePreview<GDoc<C, S>>>;
1086
- /** Coerces preview input like a save would, keeping values that would fail validation. */
1087
- private previewDoc;
1088
- private previewURL;
1089
- private versionTarget;
1090
- private updateDocument;
1091
- delete<S extends Slug<C>>(collection: S, id: ID, options?: AccessOptions): Promise<Doc<C, S>>;
1092
- findGlobal<S extends GSlug<C>>(slug: S, options?: ReadOptions): Promise<GDoc<C, S>>;
1093
- updateGlobal<S extends GSlug<C>>(slug: S, data: GInput<C, S>, options?: DepthOptions): Promise<GDoc<C, S>>;
1094
- /** Takes a global off the site (`status: 'draft'`). See `unpublish`. */
1095
- unpublishGlobal<S extends GSlug<C>>(slug: S, options?: DepthOptions): Promise<GDoc<C, S>>;
1096
- /** Throws away the unpublished draft of a published global. */
1097
- discardGlobalDraft<S extends GSlug<C>>(slug: S, options?: DepthOptions): Promise<GDoc<C, S>>;
1098
- /** Saved versions of a global, newest first. Needs update access. */
1099
- findGlobalVersions<S extends GSlug<C>>(slug: S, options?: AccessOptions & {
1100
- limit?: number;
1101
- page?: number;
1102
- }): Promise<PaginatedDocs<VersionSummary>>;
1103
- findGlobalVersion<S extends GSlug<C>>(slug: S, versionId: ID, options?: DepthOptions): Promise<Version<GDoc<C, S>> | null>;
1104
- /** Makes an old version of a global current (as a draft when the global has drafts). */
1105
- restoreGlobalVersion<S extends GSlug<C>>(slug: S, versionId: ID, options?: DepthOptions): Promise<GDoc<C, S>>;
1106
- private globalVersionTarget;
1107
- /** The global's pending draft when it has one (see `withDrafts`), otherwise `saved`. */
1108
- private globalDraft;
1109
- private saveGlobal;
1217
+ readonly modules?: readonly string[];
1218
+ }
1219
+ interface ImageSize {
1220
+ /** Key in `media.sizes`, e.g. `thumbnail`. */
1221
+ readonly name: string;
1222
+ readonly width: number;
1223
+ readonly height?: number;
1224
+ /** How to fit when both width and height are set. Default `cover`. */
1225
+ readonly fit?: 'cover' | 'contain' | 'inside';
1226
+ }
1227
+ interface UploadConfig {
1228
+ /** Directory for uploaded files with the default local storage, relative to the project root. Default `uploads`. */
1229
+ readonly dir?: string;
1230
+ /** Maximum file size in bytes. Default 10 MB. */
1231
+ readonly maxFileSize?: number;
1232
+ /** Allowed MIME types, detected from file contents. `image/*` style wildcards are allowed. */
1233
+ readonly mimeTypes?: readonly string[];
1234
+ /** Where files are stored. Default: local disk in `dir`. */
1235
+ readonly storage?: StorageAdapter;
1236
+ /** Resized copies generated for images when `sharp` is installed. */
1237
+ readonly imageSizes?: readonly ImageSize[];
1238
+ }
1239
+ interface RoutesConfig {
1240
+ /** Where the REST API is served. Default `/api/cms`. */
1241
+ readonly api?: string;
1242
+ }
1243
+ interface AuthConfig {
1244
+ /** Roles a user can have. Must include `admin`. Default `['admin', 'editor']`. */
1245
+ readonly roles?: readonly string[];
1246
+ /** Session lifetime in seconds. Default 7 days. */
1247
+ readonly tokenExpiration?: number;
1248
+ /** Failed logins allowed per email (and IP) within `lockWindow`. Default 5. */
1249
+ readonly maxLoginAttempts?: number;
1250
+ /** Window for `maxLoginAttempts`, in seconds. Default 15 minutes. */
1251
+ readonly lockWindow?: number;
1110
1252
  /**
1111
- * What `user` may do with one document. Resolves `where`-style access
1112
- * against the document, so the admin UI can hide actions precisely.
1253
+ * Origins allowed to send cookie-authenticated requests, besides the API's own origin.
1254
+ * Needed when the admin or frontend is served from another origin, or behind a proxy that rewrites the host.
1113
1255
  */
1114
- documentPermissions(collection: Slug<C>, id: ID, user: AuthUser | null): Promise<{
1115
- update: boolean;
1116
- delete: boolean;
1117
- }>;
1118
- /** Closes the database connection. */
1256
+ readonly trustedOrigins?: readonly string[];
1257
+ }
1258
+ /** What an endpoint's handler receives. */
1259
+ interface EndpointRequest {
1260
+ readonly request: Request;
1261
+ readonly url: URL;
1262
+ /** Values of `:name` segments in the endpoint's path. */
1263
+ readonly params: Readonly<Record<string, string>>;
1264
+ /** The logged-in user (session cookie or Bearer token), or `null`. */
1265
+ readonly user: AuthUser | null;
1266
+ /** The Local API. Pass `{ user, overrideAccess: false }` to apply the user's access rules. */
1267
+ readonly cms: EasyCMS;
1268
+ /** The request's JSON body, which must be an object (at most 1 MB). */
1269
+ json(): Promise<Record<string, unknown>>;
1270
+ }
1271
+ /**
1272
+ * A custom REST endpoint, served under `routes.api`. Writes from the browser pass the same
1273
+ * CSRF check as the built-in endpoints.
1274
+ */
1275
+ interface Endpoint {
1119
1276
  /**
1120
- * Waits until webhook deliveries in progress are done. Call it before a serverless function
1121
- * returns, which may otherwise stop them.
1277
+ * Path under the API, e.g. `/seo/generate` or `/stats/:collection`. The first segment must
1278
+ * not be a collection slug or one of `users`, `globals`, `admin`, `jobs`.
1122
1279
  */
1123
- flushWebhooks(): Promise<void>;
1124
- destroy(): Promise<void>;
1125
- private schedulerTimer;
1126
- private running;
1127
- /** Runs `runJobs` every `interval` ms in this process (`createEasyCMS` does this by default). */
1128
- startScheduler(interval?: number): void;
1280
+ readonly path: string;
1281
+ readonly method: 'get' | 'post' | 'put' | 'patch' | 'delete';
1129
1282
  /**
1130
- * Runs due scheduled publishes and unpublishes, and retries failed webhook deliveries. What the
1131
- * scheduler and the cron endpoint (`GET <api>/jobs/run`) call.
1283
+ * Returns a `Response`, or a value that is sent as JSON. Throw an Easy CMS error
1284
+ * (`UnauthorizedError`, `ForbiddenError`, `ValidationError`, `NotFoundError`) for error responses.
1132
1285
  */
1133
- runJobs(now?: Date): Promise<{
1134
- ran: number;
1135
- failed: number;
1136
- webhooks: {
1137
- sent: number;
1138
- failed: number;
1139
- };
1140
- }>;
1286
+ readonly handler: (request: EndpointRequest) => MaybePromise<unknown>;
1287
+ }
1288
+ /** Receives the config and returns a modified copy. Runs before validation. */
1289
+ type Plugin = (config: Config) => MaybePromise<Config>;
1290
+ interface Config {
1291
+ /** Signs sessions. At least 32 characters; read it from `process.env.EASY_CMS_SECRET`. */
1292
+ readonly secret: string;
1293
+ readonly db: DatabaseAdapter;
1141
1294
  /**
1142
- * Tries webhook deliveries that are due for another attempt. Deliveries are kept in the
1143
- * database until they succeed, so they survive restarts.
1295
+ * Public origin of the app, e.g. `https://example.com`. When set, media URLs are absolute
1296
+ * so frontends on other origins can use them. Default: relative URLs.
1144
1297
  */
1145
- retryWebhooks(now?: Date): Promise<{
1146
- sent: number;
1147
- failed: number;
1148
- }>;
1149
- /** Webhook deliveries until they succeed, stored in `webhook-deliveries`. */
1150
- private webhookQueue;
1298
+ readonly serverURL?: string;
1151
1299
  /**
1152
- * Publishes or unpublishes documents whose scheduled time has come. Safe to call often, e.g.
1153
- * from a cron job (`GET <api>/jobs/run`) where no process keeps running.
1300
+ * Origins whose browser code may call the REST API (CORS), e.g. a Vite or React app on
1301
+ * another origin. `'*'` allows any origin for anonymous requests. Origins in
1302
+ * `auth.trustedOrigins` are always allowed, with cookies. Default: none.
1154
1303
  */
1155
- runScheduled(now?: Date): Promise<{
1156
- ran: number;
1157
- failed: number;
1158
- }>;
1159
- /** Schedules a publish or unpublish, replacing a pending job with the same action. */
1160
- schedule<S extends Slug<C>>(collection: S, id: ID, job: {
1161
- action: 'publish' | 'unpublish';
1162
- at: Date | string;
1163
- }, options?: AccessOptions): Promise<ScheduledJob>;
1164
- /** Pending jobs of a document, soonest first. */
1165
- scheduled<S extends Slug<C>>(collection: S, id: ID, options?: AccessOptions): Promise<ScheduledJob[]>;
1166
- cancelSchedule<S extends Slug<C>>(collection: S, id: ID, jobId: ID, options?: AccessOptions): Promise<void>;
1167
- scheduleGlobal<S extends GSlug<C>>(slug: S, job: {
1168
- action: 'publish' | 'unpublish';
1169
- at: Date | string;
1170
- }, options?: AccessOptions): Promise<ScheduledJob>;
1171
- scheduledGlobal<S extends GSlug<C>>(slug: S, options?: AccessOptions): Promise<ScheduledJob[]>;
1172
- cancelGlobalSchedule<S extends GSlug<C>>(slug: S, jobId: ID, options?: AccessOptions): Promise<void>;
1173
- private scheduleTarget;
1174
- private globalScheduleTarget;
1175
- private addJob;
1304
+ readonly cors?: readonly string[] | '*';
1176
1305
  /**
1177
- * The next pending jobs across all collections and globals, soonest first; with access
1178
- * enforced, only those the user may update.
1306
+ * Lets a cron service run due scheduled jobs: `GET <api>/jobs/run` with
1307
+ * `Authorization: Bearer <cronSecret>`. Default: the `CRON_SECRET` environment variable (the
1308
+ * convention of Vercel Cron). Logged-in admins can always run jobs.
1179
1309
  */
1180
- upcomingJobs(options?: AccessOptions & {
1181
- limit?: number;
1182
- }): Promise<(ScheduledJob & {
1183
- collection?: string;
1184
- global?: string;
1185
- doc: ID;
1186
- })[]>;
1187
- private pendingJobs;
1188
- private removeJob;
1189
- /** @internal */
1190
- collection(slug: string): CollectionConfig;
1191
- private global;
1192
- /** The query constraint read access adds, or `undefined` when there is none. Throws when denied. */
1193
- private readWhere;
1194
- private checkDocumentAccess;
1195
- private checkGlobalAccess;
1196
- private fieldChecker;
1197
- /** Runs afterRead hooks, populates relationships and removes what the caller may not see. */
1198
- private output;
1199
- /** Creates a document: access, input filtering, hooks, validation, then afterChange. */
1200
- private createDocument;
1201
- /** The locale for an operation; `undefined` without localization. Throws on unknown locales. */
1202
- private localeOf;
1203
- /** Stored localized maps → the values of the requested locale. */
1204
- private pick;
1205
- /** Input for one locale → stored localized maps, keeping the other locales from `current`. */
1206
- private toMaps;
1207
- /** Makes `where` match localized fields in the operation's locale. */
1208
- private whereFor;
1209
- /** Drafts are kept as versions (instead of unpublishing) when both are enabled. */
1210
- private separateDrafts;
1211
- /** Replaces published documents that have a newer draft with that draft. */
1212
- private withDrafts;
1213
- /** Sends webhook events for a change; `before` is the stored status before it, if any. */
1214
- private emit;
1215
- /** Records a version after a save, when the collection or global keeps versions. */
1216
- private saveVersion;
1217
- private hookArgs;
1310
+ readonly cronSecret?: string;
1311
+ /** Endpoints notified when content changes, e.g. to rebuild a static site. */
1312
+ readonly webhooks?: readonly WebhookConfig[];
1313
+ /** Content in several languages: fields with `localized: true` hold one value per locale. */
1314
+ readonly localization?: LocalizationConfig | null;
1315
+ readonly routes?: RoutesConfig;
1316
+ readonly admin?: AdminConfig;
1317
+ readonly upload?: UploadConfig;
1318
+ readonly auth?: AuthConfig;
1218
1319
  /**
1219
- * Runs hooks that may replace a value, passed as `data` (before hooks) or `doc` (afterRead).
1220
- * Returning `undefined` keeps the value; a throw cancels the operation.
1320
+ * Collections. A collection with slug `users` adds fields, access or hooks
1321
+ * to the built-in users collection.
1221
1322
  */
1222
- private transform;
1223
- /** Runs hooks after the change is saved: failures are logged, never undo the save (NFR-REL-03). */
1224
- private notify;
1225
- /** Writes resized copies with sharp, when installed and configured. */
1226
- private resizeImage;
1227
- /** Validates, checks uniqueness and references. Returns clean data or throws `ValidationError`. */
1228
- private prepare;
1229
- /** Refuses changes that would leave no active admin (and lock everyone out). */
1230
- private guardLastAdmin;
1231
- private makeSlugsUnique;
1232
- private checkUnique;
1233
- private isTaken;
1234
- private checkReferences;
1323
+ readonly collections?: readonly CollectionConfig[];
1324
+ readonly globals?: readonly GlobalConfig[];
1325
+ /** Custom REST endpoints, e.g. from plugins. */
1326
+ readonly endpoints?: readonly Endpoint[];
1327
+ /**
1328
+ * API keys for scripts and other apps (`Authorization: Bearer ecms_…`), managed in the admin
1329
+ * under Settings. A key acts as its owner, limited to the collections and operations it lists.
1330
+ */
1331
+ readonly apiKeys?: boolean;
1332
+ readonly plugins?: readonly Plugin[];
1235
1333
  }
1236
- /** A document as live preview shows it, and the page to show it on. */
1237
- interface LivePreview<T> {
1238
- readonly doc: T;
1239
- /** From the collection's `preview` function; `null` without one. */
1240
- readonly url: string | null;
1334
+ /** The config after plugins ran, validation passed and defaults were applied. */
1335
+ interface ResolvedConfig extends Omit<Config, 'cors' | 'localization' | 'routes' | 'admin' | 'upload' | 'auth' | 'collections' | 'globals' | 'endpoints' | 'plugins'> {
1336
+ readonly cors: readonly string[] | '*';
1337
+ /** `null` without localization. */
1338
+ readonly localization: Required<LocalizationConfig> | null;
1339
+ readonly routes: Required<RoutesConfig>;
1340
+ readonly admin: Required<AdminConfig>;
1341
+ readonly upload: Required<Omit<UploadConfig, 'storage'>> & Pick<UploadConfig, 'storage'>;
1342
+ readonly auth: Required<AuthConfig>;
1343
+ readonly collections: readonly CollectionConfig[];
1344
+ readonly globals: readonly GlobalConfig[];
1345
+ readonly endpoints: readonly Endpoint[];
1241
1346
  }
1347
+ /**
1348
+ * Declares the Easy CMS config. Returns it unchanged, keeping literal types
1349
+ * so document types can be inferred from it.
1350
+ */
1351
+ declare function defineConfig<const TConfig extends Config>(config: TConfig): TConfig;
1242
1352
 
1243
- interface LoginArgs {
1244
- readonly email: string;
1245
- readonly password: string;
1246
- /** Client IP, used together with the email for rate limiting. */
1247
- readonly ip?: string | undefined;
1248
- }
1249
- interface Session {
1250
- readonly user: AuthUser;
1251
- /** Signed session token, the value of the session cookie. */
1252
- readonly token: string;
1253
- /** Send back in the `X-CSRF-Token` header on cookie-authenticated writes. */
1254
- readonly csrfToken: string;
1255
- readonly expiresAt: string;
1256
- }
1257
- /** Login, logout and session verification. Available as `cms.auth`. */
1258
- declare class Auth {
1259
- private readonly cms;
1260
- constructor(cms: EasyCMS);
1261
- private get db();
1262
- private get config();
1263
- /** Checks credentials and starts a session. Throws `UnauthorizedError` or `TooManyRequestsError`. */
1264
- login(args: LoginArgs): Promise<Session>;
1265
- /** Creates the first admin. Only works while there are no users. */
1266
- registerFirstUser(args: {
1267
- email: string;
1268
- password: string;
1269
- name?: string;
1270
- }): Promise<Session>;
1271
- hasUsers(): Promise<boolean>;
1272
- /** Ends the session for a signed token. Unknown tokens are ignored. */
1273
- logout(signedToken: string): Promise<void>;
1274
- /** Returns the user for a signed session token, or `null` if it is invalid or expired. */
1275
- verify(signedToken: string | undefined | null): Promise<AuthUser | null>;
1276
- /** The CSRF token clients must echo for a signed session token. */
1277
- csrfFor(signedToken: string): string | undefined;
1278
- /** Starts a new session for a user, e.g. after they changed their own password. */
1279
- createSession(userId: ID): Promise<Session>;
1280
- /** Signs a user out everywhere. */
1281
- revokeSessions(userId: ID): Promise<void>;
1282
- private startSession;
1283
- private findSession;
1284
- private toAuthUser;
1285
- private deleteExpiredSessions;
1286
- private windowStart;
1287
- private checkRateLimit;
1288
- private recordFailure;
1289
- private clearFailures;
1353
+ declare const API_KEYS = "api-keys";
1354
+ /** What a key may do with a collection. `create` on `media` means uploading. */
1355
+ declare const API_KEY_OPERATIONS: readonly ["read", "create", "update", "delete", "publish"];
1356
+ type ApiKeyOperation = (typeof API_KEY_OPERATIONS)[number];
1357
+ /** What a key may do with a global. */
1358
+ declare const API_KEY_GLOBAL_OPERATIONS: readonly ["read", "update", "publish"];
1359
+ type ApiKeyGlobalOperation = (typeof API_KEY_GLOBAL_OPERATIONS)[number];
1360
+ /** Stored in the key's `permissions` field. Anything not listed is not allowed. */
1361
+ interface ApiKeyPermissions {
1362
+ readonly collections?: Readonly<Record<string, readonly ApiKeyOperation[]>>;
1363
+ readonly globals?: Readonly<Record<string, readonly ApiKeyGlobalOperation[]>>;
1364
+ }
1365
+ /** Set on `AuthUser.apiKey` when a request authenticated with an API key. */
1366
+ interface ApiKeyContext {
1367
+ readonly id: number | string;
1368
+ readonly name: string;
1369
+ readonly permissions: ApiKeyPermissions;
1290
1370
  }
1371
+ /**
1372
+ * Whether a request's API key allows an operation. Always true without a key (sessions are
1373
+ * governed by access rules alone); a key only narrows what its user may do.
1374
+ */
1375
+ declare function keyAllows(user: AuthUser | null, target: {
1376
+ collection: string;
1377
+ } | {
1378
+ global: string;
1379
+ }, operation: ApiKeyOperation): boolean;
1291
1380
 
1292
1381
  declare const MIN_PASSWORD_LENGTH = 8;
1293
1382
  /** Hashes a password as `scrypt$N$r$p$salt$hash` (base64url). */
@@ -1299,6 +1388,16 @@ declare const MEDIA = "media";
1299
1388
  /** Collections Easy CMS uses internally. Not exposed over REST or in the admin UI. */
1300
1389
  declare const INTERNAL_COLLECTIONS: ReadonlySet<string>;
1301
1390
 
1391
+ /**
1392
+ * A string that is the same for configs with the same structure: collections, fields, options
1393
+ * and every other plain value. Functions count only by where they are, not by their code, since
1394
+ * bundlers rename variables differently each time they compile the same source.
1395
+ *
1396
+ * Frameworks may load the config module more than once (Next.js bundles it into each server
1397
+ * layer), which gives different objects for the same config; this tells those apart from edits.
1398
+ */
1399
+ declare function configSignature(config: Config): string;
1400
+
1302
1401
  interface CopyProgress {
1303
1402
  readonly table: string;
1304
1403
  readonly rows: number;
@@ -1616,4 +1715,4 @@ declare const BUILTIN_COLLECTIONS: readonly ["users", "media"];
1616
1715
  /** Checks a config and returns every problem found. An empty array means it is valid. */
1617
1716
  declare function validateConfig(config: Config): ConfigIssue[];
1618
1717
 
1619
- export { ADMIN_ICONS, type Access, type AccessArgs, type AccessOptions, type AdminBrand, type AdminCollection, type AdminComponent, type AdminComponentRef, type AdminConfig, type AdminField, type AdminGlobal, type AdminIcon, type AdminLocale, type AdminSchema, type AfterChangeHook, type AfterDeleteHook, type AfterReadHook, type ArrayField, Auth, type AuthConfig, type AuthUser, BUILTIN_COLLECTIONS, type BeforeChangeHook, type BeforeDeleteHook, type BeforeValidateHook, type Block, type BlocksField, type BooleanField, type BuiltinMediaCollection, type BuiltinUsersCollection, type BundleHints, CONFIG_FILE_NAMES, CSRF_COOKIE, CSRF_HEADER, type CollectionAccess, type CollectionConfig, type CollectionDocument, type CollectionHooks, type CollectionSlug, type Config, ConfigError, type ConfigIssue, type ContainerAdmin, type CopyProgress, type CopyResult, type CreateEasyCMSOptions, type CreateInput, type CreateMigrationResult, DEFAULT_ADMIN_PATH, DEFAULT_API_PATH, DEFAULT_DEPTH, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_VERSIONS, DEFAULT_TOKEN_EXPIRATION, type Database, type DatabaseAdapter, type DatabaseInitArgs, type DatabaseTransfer, type DateField, type DepthOptions, EXTENSIONS, EasyCMS, EasyCMSError, type EmailField, type Endpoint, type EndpointRequest, FIELD_TYPES, type Field, type FieldAccess, type FieldAccessFn, type FieldAdmin, type FieldError, type FieldType, type FieldValidate, type FieldValidateContext, type FieldValue, type FieldsInput, type FieldsValue, type FindArgs, type FindOptions, ForbiddenError, type GlobalAccess, type GlobalConfig, type GlobalDocument, type GlobalHooks, type GlobalInput, type GlobalSlug, type GroupField, type ID, INTERNAL_COLLECTIONS, type ImageSize, type InferCollection, type InferGlobal, type JsonField, type Label, type LivePreview, type LoadConfigOptions, type LocalStorageOptions, type LocalizationConfig, type Logger, type LoginArgs, MAX_DEPTH, MEDIA, MIN_PASSWORD_LENGTH, MIN_SECRET_LENGTH, type MediaDocument, type MediaSize, type MigrationInfo, NotFoundError, type NumberField, type Operation, type PaginatedDocs, PayloadTooLargeError, type Plugin, type PreviewTarget, type PreviewURL, QueryError, type RawDocument, type ReadOptions, type RelationshipField, type ResolvedConfig, type RestHandler, type RestHandlerOptions, type RichTextDocument, type RichTextField, type Role, type RoutesConfig, SESSION_COOKIE, type ScheduledJob, SchemaError, type SchemaMode, type SelectField, type SelectOption, type Session, type SlugField, type StorageAdapter, type StoredFile, type TextField, type TextareaField, TooManyRequestsError, UnauthorizedError, type UpdateInput, type UploadConfig, type UploadField, ValidationError, type Version, type VersionSummary, type VersionsConfig, WEBHOOK_EVENTS, type WebhookConfig, type WebhookEvent, type WebhookPayload, type Where, type WhereOperators, anyone, applyDefaults, applyPlugins, consoleLogger, copyDatabase, createEasyCMS, createRestHandler, defineConfig, fillMissing, findConfigFile, generateSlugs, generateTypes, hasRows, hashPassword, imageDimensions, importConfig, isAdmin, isLoggedIn, loadConfig, localStorage, mergeForUpdate, mimeAllowed, parseId, populate, readCookie, resolveAdminModule, resolveConfig, rowFields, silentLogger, singularize, slugify, sniffMimeType, validateConfig, validateFields, verifyPassword };
1718
+ export { ADMIN_ICONS, API_KEYS, API_KEY_GLOBAL_OPERATIONS, API_KEY_OPERATIONS, type Access, type AccessArgs, type AccessOptions, type AdminBrand, type AdminCollection, type AdminComponent, type AdminComponentRef, type AdminConfig, type AdminField, type AdminGlobal, type AdminIcon, type AdminLocale, type AdminSchema, type AfterChangeHook, type AfterDeleteHook, type AfterReadHook, type ApiKeyContext, type ApiKeyGlobalOperation, type ApiKeyOperation, type ApiKeyPermissions, type ArrayField, Auth, type AuthConfig, type AuthUser, BUILTIN_COLLECTIONS, type BeforeChangeHook, type BeforeDeleteHook, type BeforeValidateHook, type Block, type BlocksField, type BooleanField, type BuiltinApiKeysCollection, type BuiltinMediaCollection, type BuiltinUsersCollection, type BundleHints, CONFIG_FILE_NAMES, CSRF_COOKIE, CSRF_HEADER, type CollectionAccess, type CollectionConfig, type CollectionDocument, type CollectionHooks, type CollectionSlug, type Config, ConfigError, type ConfigIssue, type ContainerAdmin, type CopyProgress, type CopyResult, type CreateEasyCMSOptions, type CreateInput, type CreateMigrationResult, DEFAULT_ADMIN_PATH, DEFAULT_API_PATH, DEFAULT_DEPTH, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_VERSIONS, DEFAULT_TOKEN_EXPIRATION, type Database, type DatabaseAdapter, type DatabaseInitArgs, type DatabaseTransfer, type DateField, type DepthOptions, EXTENSIONS, EasyCMS, EasyCMSError, type EmailField, type Endpoint, type EndpointRequest, FIELD_TYPES, type Field, type FieldAccess, type FieldAccessFn, type FieldAdmin, type FieldError, type FieldType, type FieldValidate, type FieldValidateContext, type FieldValue, type FieldsInput, type FieldsValue, type FindArgs, type FindOptions, ForbiddenError, type GlobalAccess, type GlobalConfig, type GlobalDocument, type GlobalHooks, type GlobalInput, type GlobalSlug, type GroupField, type ID, INTERNAL_COLLECTIONS, type ImageSize, type InferCollection, type InferGlobal, type JsonField, type Label, type LivePreview, type LoadConfigOptions, type LocalStorageOptions, type LocalizationConfig, type Logger, type LoginArgs, MAX_DEPTH, MEDIA, MIN_PASSWORD_LENGTH, MIN_SECRET_LENGTH, type MediaDocument, type MediaSize, type MigrationInfo, NotFoundError, type NumberField, type Operation, type PaginatedDocs, PayloadTooLargeError, type Plugin, type PreviewTarget, type PreviewURL, QueryError, type RawDocument, type ReadOptions, type RelationshipField, type ResolvedConfig, type RestHandler, type RestHandlerOptions, type RichTextDocument, type RichTextField, type Role, type RoutesConfig, SESSION_COOKIE, type ScheduledJob, SchemaError, type SchemaMode, type SelectField, type SelectOption, type Session, type SlugField, type StorageAdapter, type StoredFile, type TextField, type TextareaField, TooManyRequestsError, UnauthorizedError, type UpdateInput, type UploadConfig, type UploadField, ValidationError, type Version, type VersionSummary, type VersionsConfig, WEBHOOK_EVENTS, type WebhookConfig, type WebhookEvent, type WebhookPayload, type Where, type WhereOperators, anyone, applyDefaults, applyPlugins, configSignature, consoleLogger, copyDatabase, createEasyCMS, createRestHandler, defineConfig, fillMissing, findConfigFile, generateSlugs, generateTypes, hasRows, hashPassword, imageDimensions, importConfig, isAdmin, isLoggedIn, keyAllows, loadConfig, localStorage, mergeForUpdate, mimeAllowed, parseId, populate, readCookie, resolveAdminModule, resolveConfig, rowFields, silentLogger, singularize, slugify, sniffMimeType, validateConfig, validateFields, verifyPassword };