@easy-cms/core 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +170 -10
  2. package/dist/index.js +593 -79
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -263,9 +263,32 @@ interface ArrayField extends BaseField<'array', never> {
263
263
  interface GroupField extends BaseField<'group', never> {
264
264
  readonly fields: readonly Field[];
265
265
  }
266
- type Field = TextField | TextareaField | NumberField | BooleanField | DateField | EmailField | JsonField | SelectField | SlugField | RichTextField | UploadField | RelationshipField | ArrayField | GroupField;
266
+ /** One kind of block in a `blocks` field. */
267
+ interface Block {
268
+ /** Stored in each row as `blockType`. */
269
+ readonly slug: string;
270
+ readonly labels?: {
271
+ readonly singular?: Label;
272
+ readonly plural?: Label;
273
+ };
274
+ readonly fields: readonly Field[];
275
+ }
276
+ /**
277
+ * A list of rows, each one of several block kinds (e.g. hero, text, gallery), for pages that
278
+ * editors lay out themselves. Rows are `{ id, blockType, ...fields }`, stored as JSON.
279
+ */
280
+ interface BlocksField extends BaseField<'blocks', never> {
281
+ readonly blocks: readonly Block[];
282
+ readonly minRows?: number;
283
+ readonly maxRows?: number;
284
+ }
285
+ /** Fields whose value is a list of rows: `array` and `blocks`. */
286
+ declare const hasRows: (field: Field) => field is ArrayField | BlocksField;
287
+ /** The fields of one row of an `array` or `blocks` field (`undefined` for an unknown block). */
288
+ declare function rowFields(field: ArrayField | BlocksField, row: unknown): readonly Field[] | undefined;
289
+ type Field = TextField | TextareaField | NumberField | BooleanField | DateField | EmailField | JsonField | SelectField | SlugField | RichTextField | UploadField | RelationshipField | ArrayField | GroupField | BlocksField;
267
290
  type FieldType = Field['type'];
268
- declare const FIELD_TYPES: readonly ["text", "textarea", "number", "boolean", "date", "email", "json", "select", "slug", "richText", "upload", "relationship", "array", "group"];
291
+ declare const FIELD_TYPES: readonly ["text", "textarea", "number", "boolean", "date", "email", "json", "select", "slug", "richText", "upload", "relationship", "array", "group", "blocks"];
269
292
 
270
293
  interface StoredFile {
271
294
  readonly body: Uint8Array;
@@ -296,6 +319,39 @@ interface LocalStorageOptions {
296
319
  /** Stores files on the local disk. Suitable for servers with a persistent filesystem. */
297
320
  declare function localStorage(options?: LocalStorageOptions): StorageAdapter;
298
321
 
322
+ declare const WEBHOOK_EVENTS: readonly ["create", "update", "delete", "publish", "unpublish", "draft"];
323
+ /**
324
+ * `create`, `update`, `delete`: the stored document changed. `publish` / `unpublish`: its status
325
+ * changed (sent with `create` or `update`). `draft`: only a draft was saved; what is live did not
326
+ * change (collections with versions and drafts).
327
+ */
328
+ type WebhookEvent = (typeof WEBHOOK_EVENTS)[number];
329
+ interface WebhookConfig {
330
+ /** Where to POST events. */
331
+ readonly url: string;
332
+ /** Events to send. Default: all. */
333
+ readonly events?: readonly WebhookEvent[];
334
+ /** Collections to send events for. Default: all; `[]` for none. */
335
+ readonly collections?: readonly string[];
336
+ /** Globals to send events for. Default: all; `[]` for none. */
337
+ readonly globals?: readonly string[];
338
+ /** Signs each body: `x-easy-cms-signature: sha256=<hex HMAC-SHA256 of the body>`. */
339
+ readonly secret?: string;
340
+ /** Extra request headers, e.g. a token the receiver checks. */
341
+ readonly headers?: Readonly<Record<string, string>>;
342
+ }
343
+ /** What a webhook receives as JSON. */
344
+ interface WebhookPayload {
345
+ readonly event: WebhookEvent;
346
+ readonly collection?: string;
347
+ readonly global?: string;
348
+ readonly id?: ID;
349
+ /** The stored document (every locale, no hidden fields); for `delete`, as it was. */
350
+ readonly doc: Record<string, unknown>;
351
+ /** ISO time of the change. */
352
+ readonly timestamp: string;
353
+ }
354
+
299
355
  type Data$2 = Record<string, unknown>;
300
356
  type MaybePromise<T> = T | Promise<T>;
301
357
  type Operation = 'create' | 'update';
@@ -384,6 +440,8 @@ interface CollectionConfig {
384
440
  * it is published again.
385
441
  */
386
442
  readonly versions?: boolean | VersionsConfig;
443
+ /** Allow scheduling publish/unpublish for a later time (needs `drafts`). */
444
+ readonly schedule?: boolean;
387
445
  /** Live preview: the page that shows a document, e.g. `({ doc }) => \`/posts/${doc.slug}\``. */
388
446
  readonly preview?: PreviewURL;
389
447
  readonly access?: CollectionAccess;
@@ -396,6 +454,8 @@ interface GlobalConfig {
396
454
  readonly drafts?: boolean;
397
455
  /** Keep a snapshot of every save. See `CollectionConfig.versions`. */
398
456
  readonly versions?: boolean | VersionsConfig;
457
+ /** Allow scheduling publish/unpublish for a later time (needs `drafts`). */
458
+ readonly schedule?: boolean;
399
459
  /** Live preview: the page that shows the global. See `CollectionConfig.preview`. */
400
460
  readonly preview?: PreviewURL;
401
461
  readonly access?: GlobalAccess;
@@ -464,6 +524,14 @@ interface Config {
464
524
  * `auth.trustedOrigins` are always allowed, with cookies. Default: none.
465
525
  */
466
526
  readonly cors?: readonly string[] | '*';
527
+ /**
528
+ * Lets a cron service run due scheduled jobs: `GET <api>/jobs/run` with
529
+ * `Authorization: Bearer <cronSecret>`. Default: the `CRON_SECRET` environment variable (the
530
+ * convention of Vercel Cron). Logged-in admins can always run jobs.
531
+ */
532
+ readonly cronSecret?: string;
533
+ /** Endpoints notified when content changes, e.g. to rebuild a static site. */
534
+ readonly webhooks?: readonly WebhookConfig[];
467
535
  /** Content in several languages: fields with `localized: true` hold one value per locale. */
468
536
  readonly localization?: LocalizationConfig | null;
469
537
  readonly routes?: RoutesConfig;
@@ -596,16 +664,38 @@ type FieldValue<F extends Field, C extends Config = Config> = F extends {
596
664
  }>[] : F extends {
597
665
  readonly type: 'group';
598
666
  readonly fields: infer Sub extends readonly Field[];
599
- } ? FieldsValue<Sub, C> : never;
667
+ } ? FieldsValue<Sub, C> : F extends {
668
+ readonly type: 'blocks';
669
+ readonly blocks: infer B extends readonly Block[];
670
+ } ? BlockValue<B[number], C>[] : never;
671
+ /** One row of a `blocks` field: the block's fields plus `id` and `blockType` (distributes over kinds). */
672
+ type BlockValue<B, C extends Config> = B extends {
673
+ readonly slug: infer S;
674
+ readonly fields: infer Sub extends readonly Field[];
675
+ } ? Simplify<FieldsValue<Sub, C> & {
676
+ id: string;
677
+ blockType: S;
678
+ }> : never;
679
+ type BlockInput<B> = B extends {
680
+ readonly slug: infer S;
681
+ readonly fields: infer Sub extends readonly Field[];
682
+ } ? Simplify<FieldsInput<Sub> & {
683
+ id?: string;
684
+ blockType: S;
685
+ }> : never;
600
686
  type Visible<Fs extends readonly Field[]> = Exclude<Fs[number], {
601
687
  readonly hidden: true;
602
688
  }>;
603
- type RequiredFields<Fs extends readonly Field[]> = Extract<Visible<Fs>, {
689
+ /** Always set when read: required fields, and lists and groups (empty `[]` / `{}` otherwise). */
690
+ type Present = {
604
691
  readonly required: true;
605
- }>;
606
- type OptionalFields<Fs extends readonly Field[]> = Exclude<Visible<Fs>, {
607
- readonly required: true;
608
- }>;
692
+ } | {
693
+ readonly type: 'array' | 'blocks' | 'group';
694
+ } | {
695
+ readonly hasMany: true;
696
+ };
697
+ type RequiredFields<Fs extends readonly Field[]> = Extract<Visible<Fs>, Present>;
698
+ type OptionalFields<Fs extends readonly Field[]> = Exclude<Visible<Fs>, Present>;
609
699
  /** The shape of the data described by a list of fields. */
610
700
  type FieldsValue<Fs extends readonly Field[], C extends Config = Config> = Simplify<{
611
701
  -readonly [F in RequiredFields<Fs> as F['name']]: FieldValue<F, C>;
@@ -660,7 +750,10 @@ type InputValue<F extends Field> = F extends {
660
750
  }>[] : F extends {
661
751
  readonly type: 'group';
662
752
  readonly fields: infer Sub extends readonly Field[];
663
- } ? FieldsInput<Sub> : FieldValue<F>;
753
+ } ? FieldsInput<Sub> : F extends {
754
+ readonly type: 'blocks';
755
+ readonly blocks: infer B extends readonly Block[];
756
+ } ? readonly BlockInput<B[number]>[] : FieldValue<F>;
664
757
  /** Required fields must be given, unless Easy CMS can fill them (default value, slug from another field). */
665
758
  type NeedsInput<F extends Field> = F extends {
666
759
  readonly required: true;
@@ -761,6 +854,11 @@ interface FindOptions extends ReadOptions {
761
854
  interface CreateEasyCMSOptions {
762
855
  /** Project root. Default `process.cwd()`. */
763
856
  readonly cwd?: string;
857
+ /**
858
+ * Run due scheduled jobs every minute in this process. Default: on when a collection or
859
+ * global has `schedule`. Turn it off where a cron calls `runScheduled` instead.
860
+ */
861
+ readonly scheduler?: boolean;
764
862
  /** Default `verify` when `NODE_ENV=production`, otherwise `push`. */
765
863
  readonly schema?: SchemaMode;
766
864
  readonly logger?: Logger;
@@ -768,6 +866,16 @@ interface CreateEasyCMSOptions {
768
866
  }
769
867
  /** Connects to the database and returns the Local API. */
770
868
  declare function createEasyCMS<const C extends Config>(config: C, options?: CreateEasyCMSOptions): Promise<EasyCMS<C>>;
869
+ /** A scheduled publish or unpublish. */
870
+ interface ScheduledJob {
871
+ readonly id: ID;
872
+ readonly action: 'publish' | 'unpublish';
873
+ /** ISO time the job runs at (or after). */
874
+ readonly runAt: string;
875
+ readonly state: 'pending' | 'done' | 'failed';
876
+ readonly error: string | null;
877
+ readonly author: ID | null;
878
+ }
771
879
  declare class EasyCMS<C extends Config = Config> {
772
880
  readonly config: ResolvedConfig;
773
881
  readonly db: Database;
@@ -777,6 +885,7 @@ declare class EasyCMS<C extends Config = Config> {
777
885
  /** Where uploaded files are stored. */
778
886
  readonly storage: StorageAdapter;
779
887
  private readonly versions;
888
+ private readonly webhooks;
780
889
  constructor(config: ResolvedConfig, db: Database, logger?: Logger, storage?: StorageAdapter);
781
890
  find<S extends Slug<C>>(collection: S, options?: FindOptions): Promise<PaginatedDocs<Doc<C, S>>>;
782
891
  findById<S extends Slug<C>>(collection: S, id: ID, options?: ReadOptions): Promise<Doc<C, S> | null>;
@@ -875,7 +984,43 @@ declare class EasyCMS<C extends Config = Config> {
875
984
  delete: boolean;
876
985
  }>;
877
986
  /** Closes the database connection. */
987
+ /**
988
+ * Waits until webhook deliveries in progress are done. Call it before a serverless function
989
+ * returns, which may otherwise stop them.
990
+ */
991
+ flushWebhooks(): Promise<void>;
878
992
  destroy(): Promise<void>;
993
+ private schedulerTimer;
994
+ private running;
995
+ /** Runs due jobs every `interval` ms in this process (`createEasyCMS` does this by default). */
996
+ startScheduler(interval?: number): void;
997
+ /**
998
+ * Publishes or unpublishes documents whose scheduled time has come. Safe to call often, e.g.
999
+ * from a cron job (`GET <api>/jobs/run`) where no process keeps running.
1000
+ */
1001
+ runScheduled(now?: Date): Promise<{
1002
+ ran: number;
1003
+ failed: number;
1004
+ }>;
1005
+ /** Schedules a publish or unpublish, replacing a pending job with the same action. */
1006
+ schedule<S extends Slug<C>>(collection: S, id: ID, job: {
1007
+ action: 'publish' | 'unpublish';
1008
+ at: Date | string;
1009
+ }, options?: AccessOptions): Promise<ScheduledJob>;
1010
+ /** Pending jobs of a document, soonest first. */
1011
+ scheduled<S extends Slug<C>>(collection: S, id: ID, options?: AccessOptions): Promise<ScheduledJob[]>;
1012
+ cancelSchedule<S extends Slug<C>>(collection: S, id: ID, jobId: ID, options?: AccessOptions): Promise<void>;
1013
+ scheduleGlobal<S extends GSlug<C>>(slug: S, job: {
1014
+ action: 'publish' | 'unpublish';
1015
+ at: Date | string;
1016
+ }, options?: AccessOptions): Promise<ScheduledJob>;
1017
+ scheduledGlobal<S extends GSlug<C>>(slug: S, options?: AccessOptions): Promise<ScheduledJob[]>;
1018
+ cancelGlobalSchedule<S extends GSlug<C>>(slug: S, jobId: ID, options?: AccessOptions): Promise<void>;
1019
+ private scheduleTarget;
1020
+ private globalScheduleTarget;
1021
+ private addJob;
1022
+ private pendingJobs;
1023
+ private removeJob;
879
1024
  /** @internal */
880
1025
  collection(slug: string): CollectionConfig;
881
1026
  private global;
@@ -900,6 +1045,8 @@ declare class EasyCMS<C extends Config = Config> {
900
1045
  private separateDrafts;
901
1046
  /** Replaces published documents that have a newer draft with that draft. */
902
1047
  private withDrafts;
1048
+ /** Sends webhook events for a change; `before` is the stored status before it, if any. */
1049
+ private emit;
903
1050
  /** Records a version after a save, when the collection or global keeps versions. */
904
1051
  private saveVersion;
905
1052
  private hookArgs;
@@ -1161,6 +1308,15 @@ interface AdminField {
1161
1308
  minRows?: number;
1162
1309
  maxRows?: number;
1163
1310
  fields?: AdminField[];
1311
+ /** Block kinds of a `blocks` field. */
1312
+ blocks?: {
1313
+ slug: string;
1314
+ labels?: {
1315
+ singular?: Label;
1316
+ plural?: Label;
1317
+ };
1318
+ fields: AdminField[];
1319
+ }[];
1164
1320
  /** The current user may not change this field. */
1165
1321
  readOnly?: boolean;
1166
1322
  /** One value per content locale. */
@@ -1177,6 +1333,8 @@ interface AdminCollection {
1177
1333
  versions: boolean;
1178
1334
  /** Has live preview (`preview` in the config). */
1179
1335
  preview: boolean;
1336
+ /** Publishing can be scheduled. */
1337
+ schedule: boolean;
1180
1338
  fields: AdminField[];
1181
1339
  permissions: {
1182
1340
  read: boolean;
@@ -1192,6 +1350,8 @@ interface AdminGlobal {
1192
1350
  versions: boolean;
1193
1351
  /** Has live preview (`preview` in the config). */
1194
1352
  preview: boolean;
1353
+ /** Publishing can be scheduled. */
1354
+ schedule: boolean;
1195
1355
  fields: AdminField[];
1196
1356
  permissions: {
1197
1357
  read: boolean;
@@ -1237,4 +1397,4 @@ declare const BUILTIN_COLLECTIONS: readonly ["users", "media"];
1237
1397
  /** Checks a config and returns every problem found. An empty array means it is valid. */
1238
1398
  declare function validateConfig(config: Config): ConfigIssue[];
1239
1399
 
1240
- export { type Access, type AccessArgs, type AccessOptions, type AdminCollection, type AdminConfig, type AdminField, type AdminGlobal, 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 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 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 DateField, type DepthOptions, EXTENSIONS, EasyCMS, EasyCMSError, type EmailField, FIELD_TYPES, type Field, type FieldAccess, type FieldAccessFn, 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, 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, type Where, type WhereOperators, anyone, applyDefaults, consoleLogger, createEasyCMS, createRestHandler, defineConfig, fillMissing, findConfigFile, generateSlugs, generateTypes, hashPassword, imageDimensions, importConfig, isAdmin, isLoggedIn, loadConfig, localStorage, mergeForUpdate, mimeAllowed, parseId, populate, readCookie, resolveConfig, silentLogger, singularize, slugify, sniffMimeType, validateConfig, validateFields, verifyPassword };
1400
+ export { type Access, type AccessArgs, type AccessOptions, type AdminCollection, type AdminConfig, type AdminField, type AdminGlobal, 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 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 DateField, type DepthOptions, EXTENSIONS, EasyCMS, EasyCMSError, type EmailField, FIELD_TYPES, type Field, type FieldAccess, type FieldAccessFn, 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, consoleLogger, createEasyCMS, createRestHandler, defineConfig, fillMissing, findConfigFile, generateSlugs, generateTypes, hasRows, hashPassword, imageDimensions, importConfig, isAdmin, isLoggedIn, loadConfig, localStorage, mergeForUpdate, mimeAllowed, parseId, populate, readCookie, resolveConfig, rowFields, silentLogger, singularize, slugify, sniffMimeType, validateConfig, validateFields, verifyPassword };