payload 3.0.0-alpha.63 → 3.0.0-alpha.64

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 (2) hide show
  1. package/package.json +2 -2
  2. package/src/index.ts +0 -510
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "payload",
3
- "version": "3.0.0-alpha.63",
3
+ "version": "3.0.0-alpha.64",
4
4
  "description": "Node, React and MongoDB Headless CMS and Application Framework",
5
5
  "license": "MIT",
6
6
  "main": "./dist/index.js",
@@ -50,7 +50,7 @@
50
50
  "scheduler": "0.23.0",
51
51
  "scmp": "2.1.0",
52
52
  "uuid": "^9.0.1",
53
- "@payloadcms/translations": "3.0.0-alpha.63"
53
+ "@payloadcms/translations": "3.0.0-alpha.64"
54
54
  },
55
55
  "peerDependencies": {
56
56
  "@swc/core": "^1.4.13"
package/src/index.ts DELETED
@@ -1,510 +0,0 @@
1
- import type { ExecutionResult, GraphQLSchema, ValidationRule } from 'graphql'
2
- import type { OperationArgs, Request as graphQLRequest } from 'graphql-http'
3
- import type pino from 'pino'
4
-
5
- import crypto from 'crypto'
6
-
7
- import type { AuthArgs } from './auth/operations/auth.js'
8
- import type { Result as ForgotPasswordResult } from './auth/operations/forgotPassword.js'
9
- import type { Options as ForgotPasswordOptions } from './auth/operations/local/forgotPassword.js'
10
- import type { Options as LoginOptions } from './auth/operations/local/login.js'
11
- import type { Options as ResetPasswordOptions } from './auth/operations/local/resetPassword.js'
12
- import type { Options as UnlockOptions } from './auth/operations/local/unlock.js'
13
- import type { Options as VerifyEmailOptions } from './auth/operations/local/verifyEmail.js'
14
- import type { Result as LoginResult } from './auth/operations/login.js'
15
- import type { Result as ResetPasswordResult } from './auth/operations/resetPassword.js'
16
- import type { AuthStrategy } from './auth/types.js'
17
- import type { BulkOperationResult, Collection, TypeWithID } from './collections/config/types.js'
18
- import type { Options as CountOptions } from './collections/operations/local/count.js'
19
- import type { Options as CreateOptions } from './collections/operations/local/create.js'
20
- import type {
21
- ByIDOptions as DeleteByIDOptions,
22
- ManyOptions as DeleteManyOptions,
23
- Options as DeleteOptions,
24
- } from './collections/operations/local/delete.js'
25
- import type { Options as DuplicateOptions } from './collections/operations/local/duplicate.js'
26
- import type { Options as FindOptions } from './collections/operations/local/find.js'
27
- import type { Options as FindByIDOptions } from './collections/operations/local/findByID.js'
28
- import type { Options as FindVersionByIDOptions } from './collections/operations/local/findVersionByID.js'
29
- import type { Options as FindVersionsOptions } from './collections/operations/local/findVersions.js'
30
- import type { Options as RestoreVersionOptions } from './collections/operations/local/restoreVersion.js'
31
- import type {
32
- ByIDOptions as UpdateByIDOptions,
33
- ManyOptions as UpdateManyOptions,
34
- Options as UpdateOptions,
35
- } from './collections/operations/local/update.js'
36
- import type { InitOptions, SanitizedConfig } from './config/types.js'
37
- import type { BaseDatabaseAdapter, PaginatedDocs } from './database/types.js'
38
- import type { InitializedEmailAdapter } from './email/types.js'
39
- import type { TypeWithID as GlobalTypeWithID, Globals } from './globals/config/types.js'
40
- import type { Options as FindGlobalOptions } from './globals/operations/local/findOne.js'
41
- import type { Options as FindGlobalVersionByIDOptions } from './globals/operations/local/findVersionByID.js'
42
- import type { Options as FindGlobalVersionsOptions } from './globals/operations/local/findVersions.js'
43
- import type { Options as RestoreGlobalVersionOptions } from './globals/operations/local/restoreVersion.js'
44
- import type { Options as UpdateGlobalOptions } from './globals/operations/local/update.js'
45
- import type { TypeWithVersion } from './versions/types.js'
46
-
47
- import { decrypt, encrypt } from './auth/crypto.js'
48
- import { APIKeyAuthentication } from './auth/strategies/apiKey.js'
49
- import { JWTAuthentication } from './auth/strategies/jwt.js'
50
- import localOperations from './collections/operations/local/index.js'
51
- import { validateSchema } from './config/validate.js'
52
- import { consoleEmailAdapter } from './email/consoleEmailAdapter.js'
53
- import { fieldAffectsData } from './exports/types.js'
54
- import localGlobalOperations from './globals/operations/local/index.js'
55
- import flattenFields from './utilities/flattenTopLevelFields.js'
56
- import Logger from './utilities/logger.js'
57
- import { serverInit as serverInitTelemetry } from './utilities/telemetry/events/serverInit.js'
58
-
59
- /**
60
- * @description Payload
61
- */
62
- export class BasePayload<TGeneratedTypes extends GeneratedTypes> {
63
- /**
64
- * @description Authorization and Authentication using headers and cookies to run auth user strategies
65
- * @returns cookies: Map<string, string>
66
- * @returns permissions: Permissions
67
- * @returns user: User
68
- */
69
- auth = async (options: AuthArgs) => {
70
- const { auth } = localOperations.auth
71
- return auth(this, options)
72
- }
73
-
74
- authStrategies: AuthStrategy[]
75
-
76
- collections: {
77
- [slug: number | string | symbol]: Collection
78
- } = {}
79
-
80
- config: SanitizedConfig
81
-
82
- /**
83
- * @description Performs count operation
84
- * @param options
85
- * @returns count of documents satisfying query
86
- */
87
- count = async <T extends keyof TGeneratedTypes['collections']>(
88
- options: CountOptions<T>,
89
- ): Promise<{ totalDocs: number }> => {
90
- const { count } = localOperations
91
- return count(this, options)
92
- }
93
-
94
- /**
95
- * @description Performs create operation
96
- * @param options
97
- * @returns created document
98
- */
99
- create = async <T extends keyof TGeneratedTypes['collections']>(
100
- options: CreateOptions<T>,
101
- ): Promise<TGeneratedTypes['collections'][T]> => {
102
- const { create } = localOperations
103
- return create<T>(this, options)
104
- }
105
- db: DatabaseAdapter
106
-
107
- decrypt = decrypt
108
-
109
- duplicate = async <T extends keyof TGeneratedTypes['collections']>(
110
- options: DuplicateOptions<T>,
111
- ): Promise<TGeneratedTypes['collections'][T]> => {
112
- const { duplicate } = localOperations
113
- return duplicate<T>(this, options)
114
- }
115
-
116
- email: InitializedEmailAdapter
117
-
118
- // TODO: re-implement or remove?
119
- // errorHandler: ErrorHandler
120
-
121
- encrypt = encrypt
122
-
123
- extensions: (args: {
124
- args: OperationArgs<any>
125
- req: graphQLRequest<unknown, unknown>
126
- result: ExecutionResult
127
- }) => Promise<any>
128
-
129
- /**
130
- * @description Find documents with criteria
131
- * @param options
132
- * @returns documents satisfying query
133
- */
134
- find = async <T extends keyof TGeneratedTypes['collections']>(
135
- options: FindOptions<T>,
136
- ): Promise<PaginatedDocs<TGeneratedTypes['collections'][T]>> => {
137
- const { find } = localOperations
138
- return find<T>(this, options)
139
- }
140
-
141
- /**
142
- * @description Find document by ID
143
- * @param options
144
- * @returns document with specified ID
145
- */
146
- findByID = async <T extends keyof TGeneratedTypes['collections']>(
147
- options: FindByIDOptions<T>,
148
- ): Promise<TGeneratedTypes['collections'][T]> => {
149
- const { findByID } = localOperations
150
- return findByID<T>(this, options)
151
- }
152
-
153
- findGlobal = async <T extends keyof TGeneratedTypes['globals']>(
154
- options: FindGlobalOptions<T>,
155
- ): Promise<TGeneratedTypes['globals'][T]> => {
156
- const { findOne } = localGlobalOperations
157
- return findOne<T>(this, options)
158
- }
159
-
160
- /**
161
- * @description Find global version by ID
162
- * @param options
163
- * @returns global version with specified ID
164
- */
165
- findGlobalVersionByID = async <T extends keyof TGeneratedTypes['globals']>(
166
- options: FindGlobalVersionByIDOptions<T>,
167
- ): Promise<TypeWithVersion<TGeneratedTypes['globals'][T]>> => {
168
- const { findVersionByID } = localGlobalOperations
169
- return findVersionByID<T>(this, options)
170
- }
171
-
172
- /**
173
- * @description Find global versions with criteria
174
- * @param options
175
- * @returns versions satisfying query
176
- */
177
- findGlobalVersions = async <T extends keyof TGeneratedTypes['globals']>(
178
- options: FindGlobalVersionsOptions<T>,
179
- ): Promise<PaginatedDocs<TypeWithVersion<TGeneratedTypes['globals'][T]>>> => {
180
- const { findVersions } = localGlobalOperations
181
- return findVersions<T>(this, options)
182
- }
183
-
184
- /**
185
- * @description Find version by ID
186
- * @param options
187
- * @returns version with specified ID
188
- */
189
- findVersionByID = async <T extends keyof TGeneratedTypes['collections']>(
190
- options: FindVersionByIDOptions<T>,
191
- ): Promise<TypeWithVersion<TGeneratedTypes['collections'][T]>> => {
192
- const { findVersionByID } = localOperations
193
- return findVersionByID<T>(this, options)
194
- }
195
-
196
- /**
197
- * @description Find versions with criteria
198
- * @param options
199
- * @returns versions satisfying query
200
- */
201
- findVersions = async <T extends keyof TGeneratedTypes['collections']>(
202
- options: FindVersionsOptions<T>,
203
- ): Promise<PaginatedDocs<TypeWithVersion<TGeneratedTypes['collections'][T]>>> => {
204
- const { findVersions } = localOperations
205
- return findVersions<T>(this, options)
206
- }
207
-
208
- forgotPassword = async <T extends keyof TGeneratedTypes['collections']>(
209
- options: ForgotPasswordOptions<T>,
210
- ): Promise<ForgotPasswordResult> => {
211
- const { forgotPassword } = localOperations.auth
212
- return forgotPassword<T>(this, options)
213
- }
214
-
215
- getAPIURL = (): string => `${this.config.serverURL}${this.config.routes.api}`
216
-
217
- getAdminURL = (): string => `${this.config.serverURL}${this.config.routes.admin}`
218
-
219
- globals: Globals
220
-
221
- logger: pino.Logger
222
-
223
- login = async <T extends keyof TGeneratedTypes['collections']>(
224
- options: LoginOptions<T>,
225
- ): Promise<LoginResult & { user: TGeneratedTypes['collections'][T] }> => {
226
- const { login } = localOperations.auth
227
- return login<T>(this, options)
228
- }
229
-
230
- resetPassword = async <T extends keyof TGeneratedTypes['collections']>(
231
- options: ResetPasswordOptions<T>,
232
- ): Promise<ResetPasswordResult> => {
233
- const { resetPassword } = localOperations.auth
234
- return resetPassword<T>(this, options)
235
- }
236
-
237
- /**
238
- * @description Restore global version by ID
239
- * @param options
240
- * @returns version with specified ID
241
- */
242
- restoreGlobalVersion = async <T extends keyof TGeneratedTypes['globals']>(
243
- options: RestoreGlobalVersionOptions<T>,
244
- ): Promise<TGeneratedTypes['globals'][T]> => {
245
- const { restoreVersion } = localGlobalOperations
246
- return restoreVersion<T>(this, options)
247
- }
248
-
249
- /**
250
- * @description Restore version by ID
251
- * @param options
252
- * @returns version with specified ID
253
- */
254
- restoreVersion = async <T extends keyof TGeneratedTypes['collections']>(
255
- options: RestoreVersionOptions<T>,
256
- ): Promise<TGeneratedTypes['collections'][T]> => {
257
- const { restoreVersion } = localOperations
258
- return restoreVersion<T>(this, options)
259
- }
260
-
261
- schema: GraphQLSchema
262
-
263
- secret: string
264
-
265
- sendEmail: InitializedEmailAdapter['sendEmail']
266
-
267
- types: {
268
- arrayTypes: any
269
- blockInputTypes: any
270
- blockTypes: any
271
- fallbackLocaleInputType?: any
272
- groupTypes: any
273
- localeInputType?: any
274
- tabTypes: any
275
- }
276
-
277
- unlock = async <T extends keyof TGeneratedTypes['collections']>(
278
- options: UnlockOptions<T>,
279
- ): Promise<boolean> => {
280
- const { unlock } = localOperations.auth
281
- return unlock(this, options)
282
- }
283
-
284
- updateGlobal = async <T extends keyof TGeneratedTypes['globals']>(
285
- options: UpdateGlobalOptions<T>,
286
- ): Promise<TGeneratedTypes['globals'][T]> => {
287
- const { update } = localGlobalOperations
288
- return update<T>(this, options)
289
- }
290
-
291
- validationRules: (args: OperationArgs<any>) => ValidationRule[]
292
-
293
- verifyEmail = async <T extends keyof TGeneratedTypes['collections']>(
294
- options: VerifyEmailOptions<T>,
295
- ): Promise<boolean> => {
296
- const { verifyEmail } = localOperations.auth
297
- return verifyEmail(this, options)
298
- }
299
-
300
- versions: {
301
- [slug: string]: any // TODO: Type this
302
- } = {}
303
-
304
- /**
305
- * @description delete one or more documents
306
- * @param options
307
- * @returns Updated document(s)
308
- */
309
- delete<T extends keyof TGeneratedTypes['collections']>(
310
- options: DeleteByIDOptions<T>,
311
- ): Promise<TGeneratedTypes['collections'][T]>
312
-
313
- delete<T extends keyof TGeneratedTypes['collections']>(
314
- options: DeleteManyOptions<T>,
315
- ): Promise<BulkOperationResult<T>>
316
-
317
- delete<T extends keyof TGeneratedTypes['collections']>(
318
- options: DeleteOptions<T>,
319
- ): Promise<BulkOperationResult<T> | TGeneratedTypes['collections'][T]> {
320
- const { deleteLocal } = localOperations
321
- return deleteLocal<T>(this, options)
322
- }
323
-
324
- /**
325
- * @description Initializes Payload
326
- * @param options
327
- */
328
- async init(options: InitOptions): Promise<Payload> {
329
- if (!options?.config) {
330
- throw new Error('Error: the payload config is required to initialize payload.')
331
- }
332
-
333
- this.logger = Logger('payload', options.loggerOptions, options.loggerDestination)
334
-
335
- this.config = await options.config
336
-
337
- if (process.env.NODE_ENV !== 'production') {
338
- validateSchema(this.config, this.logger)
339
- }
340
-
341
- if (!this.config.secret) {
342
- throw new Error('Error: missing secret key. A secret key is needed to secure Payload.')
343
- }
344
-
345
- this.secret = crypto.createHash('sha256').update(this.config.secret).digest('hex').slice(0, 32)
346
-
347
- this.globals = {
348
- config: this.config.globals,
349
- }
350
-
351
- this.config.collections.forEach((collection) => {
352
- const customID = flattenFields(collection.fields).find(
353
- (field) => fieldAffectsData(field) && field.name === 'id',
354
- )
355
-
356
- let customIDType
357
-
358
- if (customID?.type === 'number' || customID?.type === 'text') customIDType = customID.type
359
-
360
- this.collections[collection.slug] = {
361
- config: collection,
362
- customIDType,
363
- }
364
- })
365
-
366
- this.db = this.config.db.init({ payload: this })
367
- this.db.payload = this
368
-
369
- if (this.db?.init) {
370
- await this.db.init()
371
- }
372
-
373
- if (!options.disableDBConnect && this.db.connect) {
374
- await this.db.connect()
375
- }
376
-
377
- // Load email adapter
378
- if (this.config.email instanceof Promise) {
379
- const awaitedAdapter = await this.config.email
380
- this.email = awaitedAdapter({ payload: this })
381
- } else if (this.config.email) {
382
- this.email = this.config.email({ payload: this })
383
- } else {
384
- this.logger.warn(
385
- `No email adapter provided. Email will be written to console. More info at https://payloadcms.com/docs/email/overview.`,
386
- )
387
-
388
- this.email = consoleEmailAdapter({ payload: this })
389
- }
390
-
391
- this.sendEmail = this.email['sendEmail']
392
-
393
- serverInitTelemetry(this)
394
-
395
- // 1. loop over collections, if collection has auth strategy, initialize and push to array
396
- let jwtStrategyEnabled = false
397
- this.authStrategies = this.config.collections.reduce((authStrategies, collection) => {
398
- if (collection?.auth) {
399
- if (collection.auth.strategies.length > 0) {
400
- authStrategies.push(...collection.auth.strategies)
401
- }
402
-
403
- // 2. if api key enabled, push api key strategy into the array
404
- if (collection.auth?.useAPIKey) {
405
- authStrategies.push({
406
- name: `${collection.slug}-api-key`,
407
- authenticate: APIKeyAuthentication(collection),
408
- })
409
- }
410
-
411
- // 3. if localStrategy flag is true
412
- if (!collection.auth.disableLocalStrategy && !jwtStrategyEnabled) {
413
- jwtStrategyEnabled = true
414
- }
415
- }
416
-
417
- return authStrategies
418
- }, [] as AuthStrategy[])
419
-
420
- // 4. if enabled, push jwt strategy into authStrategies last
421
- if (jwtStrategyEnabled) {
422
- this.authStrategies.push({
423
- name: 'local-jwt',
424
- authenticate: JWTAuthentication,
425
- })
426
- }
427
-
428
- if (!options.disableOnInit) {
429
- if (typeof options.onInit === 'function') await options.onInit(this)
430
- if (typeof this.config.onInit === 'function') await this.config.onInit(this)
431
- }
432
-
433
- return this
434
- }
435
-
436
- update<T extends keyof TGeneratedTypes['collections']>(
437
- options: UpdateManyOptions<T>,
438
- ): Promise<BulkOperationResult<T>>
439
-
440
- /**
441
- * @description Update one or more documents
442
- * @param options
443
- * @returns Updated document(s)
444
- */
445
- update<T extends keyof TGeneratedTypes['collections']>(
446
- options: UpdateByIDOptions<T>,
447
- ): Promise<TGeneratedTypes['collections'][T]>
448
-
449
- update<T extends keyof TGeneratedTypes['collections']>(
450
- options: UpdateOptions<T>,
451
- ): Promise<BulkOperationResult<T> | TGeneratedTypes['collections'][T]> {
452
- const { update } = localOperations
453
- return update<T>(this, options)
454
- }
455
- }
456
-
457
- const initialized = new BasePayload()
458
-
459
- export default initialized
460
-
461
- let cached = global._payload
462
-
463
- if (!cached) {
464
- // eslint-disable-next-line no-multi-assign
465
- cached = global._payload = { payload: null, promise: null }
466
- }
467
-
468
- export const getPayload = async (options: InitOptions): Promise<BasePayload<GeneratedTypes>> => {
469
- if (!options?.config) {
470
- throw new Error('Error: the payload config is required for getPayload to work.')
471
- }
472
-
473
- if (cached.payload) {
474
- return cached.payload
475
- }
476
-
477
- if (!cached.promise) {
478
- cached.promise = new BasePayload<GeneratedTypes>().init(options)
479
- }
480
-
481
- try {
482
- cached.payload = await cached.promise
483
- } catch (e) {
484
- cached.promise = null
485
- throw e
486
- }
487
-
488
- return cached.payload
489
- }
490
-
491
- type GeneratedTypes = {
492
- collections: {
493
- [slug: number | string | symbol]: TypeWithID & Record<string, unknown>
494
- }
495
- globals: {
496
- [slug: number | string | symbol]: GlobalTypeWithID & Record<string, unknown>
497
- }
498
- locale: null | string
499
- user: TypeWithID & Record<string, unknown> & { collection: string }
500
- }
501
-
502
- type Payload = BasePayload<GeneratedTypes>
503
-
504
- interface RequestContext {
505
- [key: string]: unknown
506
- }
507
-
508
- type DatabaseAdapter = BaseDatabaseAdapter
509
-
510
- export type { DatabaseAdapter, GeneratedTypes, Payload, RequestContext }