@strapi/core 0.0.0-experimental.a53a4b1c8f7981a689823cdd719105671e1c6392 → 0.0.0-experimental.a9a5a36dd73072c19eadeff5f387e8286b2a4d22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Strapi.d.ts +3 -1
- package/dist/Strapi.d.ts.map +1 -1
- package/dist/Strapi.js +49 -6
- package/dist/Strapi.js.map +1 -1
- package/dist/Strapi.mjs +28 -4
- package/dist/Strapi.mjs.map +1 -1
- package/dist/configuration/get-dirs.js +2 -2
- package/dist/configuration/get-dirs.js.map +1 -1
- package/dist/configuration/index.js +2 -2
- package/dist/configuration/index.js.map +1 -1
- package/dist/core-api/controller/collection-type.js +3 -3
- package/dist/core-api/controller/collection-type.js.map +1 -1
- package/dist/core-api/controller/index.js +2 -2
- package/dist/core-api/controller/index.js.map +1 -1
- package/dist/core-api/controller/single-type.js +2 -2
- package/dist/core-api/controller/single-type.js.map +1 -1
- package/dist/core-api/controller/transform.js +8 -8
- package/dist/core-api/controller/transform.js.map +1 -1
- package/dist/core-api/service/pagination.js +8 -8
- package/dist/core-api/service/pagination.js.map +1 -1
- package/dist/domain/content-type/index.js +4 -4
- package/dist/domain/content-type/index.js.map +1 -1
- package/dist/ee/index.js +3 -3
- package/dist/ee/index.js.map +1 -1
- package/dist/factories.js +4 -4
- package/dist/factories.js.map +1 -1
- package/dist/loaders/apis.js +2 -2
- package/dist/loaders/apis.js.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.js +8 -8
- package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
- package/dist/loaders/plugins/get-user-plugins-config.js +2 -2
- package/dist/loaders/plugins/get-user-plugins-config.js.map +1 -1
- package/dist/loaders/plugins/index.js +6 -6
- package/dist/loaders/plugins/index.js.map +1 -1
- package/dist/middlewares/body.js +2 -2
- package/dist/middlewares/body.js.map +1 -1
- package/dist/middlewares/public.js +2 -2
- package/dist/middlewares/public.js.map +1 -1
- package/dist/middlewares/responses.js +2 -2
- package/dist/middlewares/responses.js.map +1 -1
- package/dist/middlewares/security.js +3 -3
- package/dist/middlewares/security.js.map +1 -1
- package/dist/middlewares/session.js +2 -2
- package/dist/middlewares/session.js.map +1 -1
- package/dist/registries/apis.js +2 -2
- package/dist/registries/apis.js.map +1 -1
- package/dist/registries/components.js +2 -2
- package/dist/registries/components.js.map +1 -1
- package/dist/registries/content-types.js +3 -3
- package/dist/registries/content-types.js.map +1 -1
- package/dist/registries/controllers.js +3 -3
- package/dist/registries/controllers.js.map +1 -1
- package/dist/registries/custom-fields.js +4 -4
- package/dist/registries/custom-fields.js.map +1 -1
- package/dist/registries/hooks.js +2 -2
- package/dist/registries/hooks.js.map +1 -1
- package/dist/registries/middlewares.js +3 -3
- package/dist/registries/middlewares.js.map +1 -1
- package/dist/registries/modules.js +3 -3
- package/dist/registries/modules.js.map +1 -1
- package/dist/registries/plugins.js +2 -2
- package/dist/registries/plugins.js.map +1 -1
- package/dist/registries/policies.js +4 -4
- package/dist/registries/policies.js.map +1 -1
- package/dist/registries/services.js +3 -3
- package/dist/registries/services.js.map +1 -1
- package/dist/services/auth/index.js +3 -3
- package/dist/services/auth/index.js.map +1 -1
- package/dist/services/core-store.js +3 -3
- package/dist/services/core-store.js.map +1 -1
- package/dist/services/cron.js +3 -3
- package/dist/services/cron.js.map +1 -1
- package/dist/services/document-service/attributes/index.js +2 -2
- package/dist/services/document-service/attributes/index.js.map +1 -1
- package/dist/services/document-service/attributes/transforms.js +3 -3
- package/dist/services/document-service/attributes/transforms.js.map +1 -1
- package/dist/services/document-service/components.js +15 -15
- package/dist/services/document-service/components.js.map +1 -1
- package/dist/services/document-service/draft-and-publish.js +16 -16
- package/dist/services/document-service/draft-and-publish.js.map +1 -1
- package/dist/services/document-service/entries.js +5 -5
- package/dist/services/document-service/entries.js.map +1 -1
- package/dist/services/document-service/internationalization.js +9 -9
- package/dist/services/document-service/internationalization.js.map +1 -1
- package/dist/services/document-service/params.js +2 -2
- package/dist/services/document-service/params.js.map +1 -1
- package/dist/services/document-service/repository.js +9 -9
- package/dist/services/document-service/repository.js.map +1 -1
- package/dist/services/document-service/transform/id-transform.js +2 -2
- package/dist/services/document-service/transform/id-transform.js.map +1 -1
- package/dist/services/document-service/transform/query.js +3 -3
- package/dist/services/document-service/transform/query.js.map +1 -1
- package/dist/services/document-service/transform/relations/extract/data-ids.js +2 -2
- package/dist/services/document-service/transform/relations/extract/data-ids.js.map +1 -1
- package/dist/services/document-service/transform/relations/transform/data-ids.js +2 -2
- package/dist/services/document-service/transform/relations/transform/data-ids.js.map +1 -1
- package/dist/services/document-service/transform/relations/utils/dp.js +2 -2
- package/dist/services/document-service/transform/relations/utils/dp.js.map +1 -1
- package/dist/services/document-service/transform/relations/utils/map-relation.js +6 -6
- package/dist/services/document-service/transform/relations/utils/map-relation.js.map +1 -1
- package/dist/services/document-service/utils/populate.d.ts.map +1 -1
- package/dist/services/document-service/utils/populate.js +4 -0
- package/dist/services/document-service/utils/populate.js.map +1 -1
- package/dist/services/document-service/utils/populate.mjs +4 -0
- package/dist/services/document-service/utils/populate.mjs.map +1 -1
- package/dist/services/entity-validator/index.d.ts +14 -1
- package/dist/services/entity-validator/index.d.ts.map +1 -1
- package/dist/services/entity-validator/index.js +106 -49
- package/dist/services/entity-validator/index.js.map +1 -1
- package/dist/services/entity-validator/index.mjs +87 -30
- package/dist/services/entity-validator/index.mjs.map +1 -1
- package/dist/services/entity-validator/validators.d.ts +10 -8
- package/dist/services/entity-validator/validators.d.ts.map +1 -1
- package/dist/services/entity-validator/validators.js +60 -19
- package/dist/services/entity-validator/validators.js.map +1 -1
- package/dist/services/entity-validator/validators.mjs +53 -11
- package/dist/services/entity-validator/validators.mjs.map +1 -1
- package/dist/services/server/compose-endpoint.js +7 -7
- package/dist/services/server/compose-endpoint.js.map +1 -1
- package/dist/services/server/index.js +1 -1
- package/dist/services/server/index.js.map +1 -1
- package/dist/services/server/index.mjs +1 -1
- package/dist/services/server/index.mjs.map +1 -1
- package/dist/services/server/koa.js +3 -3
- package/dist/services/server/koa.js.map +1 -1
- package/dist/services/server/middleware.js +3 -3
- package/dist/services/server/middleware.js.map +1 -1
- package/dist/services/server/routing.js +2 -2
- package/dist/services/server/routing.js.map +1 -1
- package/dist/services/utils/dynamic-zones.js +5 -5
- package/dist/services/utils/dynamic-zones.js.map +1 -1
- package/dist/utils/cron.js +3 -3
- package/dist/utils/cron.js.map +1 -1
- package/dist/utils/fetch.d.ts.map +1 -1
- package/dist/utils/fetch.js +4 -3
- package/dist/utils/fetch.js.map +1 -1
- package/dist/utils/fetch.mjs +4 -3
- package/dist/utils/fetch.mjs.map +1 -1
- package/dist/utils/filepath-to-prop-path.d.ts +1 -1
- package/dist/utils/filepath-to-prop-path.d.ts.map +1 -1
- package/dist/utils/filepath-to-prop-path.js +27 -6
- package/dist/utils/filepath-to-prop-path.js.map +1 -1
- package/dist/utils/filepath-to-prop-path.mjs +25 -5
- package/dist/utils/filepath-to-prop-path.mjs.map +1 -1
- package/dist/utils/is-initialized.js +3 -3
- package/dist/utils/is-initialized.js.map +1 -1
- package/dist/utils/startup-logger.js +4 -4
- package/dist/utils/startup-logger.js.map +1 -1
- package/dist/utils/startup-logger.mjs +3 -3
- package/dist/utils/startup-logger.mjs.map +1 -1
- package/dist/utils/transform-content-types-to-models.d.ts.map +1 -1
- package/dist/utils/transform-content-types-to-models.js +7 -5
- package/dist/utils/transform-content-types-to-models.js.map +1 -1
- package/dist/utils/transform-content-types-to-models.mjs +6 -4
- package/dist/utils/transform-content-types-to-models.mjs.map +1 -1
- package/package.json +16 -14
@@ -1,6 +1,6 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
|
-
const
|
3
|
+
const fp = require("lodash/fp");
|
4
4
|
const strapiUtils = require("@strapi/utils");
|
5
5
|
const createSingleTypeController = ({
|
6
6
|
contentType
|
@@ -23,7 +23,7 @@ const createSingleTypeController = ({
|
|
23
23
|
*/
|
24
24
|
async update(ctx) {
|
25
25
|
const { query, body = {} } = ctx.request;
|
26
|
-
if (!
|
26
|
+
if (!fp.isObject(body.data)) {
|
27
27
|
throw new strapiUtils.errors.ValidationError('Missing "data" payload in the request body');
|
28
28
|
}
|
29
29
|
await this.validateInput(body.data, ctx);
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"single-type.js","sources":["../../../src/core-api/controller/single-type.ts"],"sourcesContent":["import { isObject } from 'lodash/fp';\nimport { errors } from '@strapi/utils';\nimport type { Struct, Core, Utils, UID } from '@strapi/types';\n\ninterface Options {\n contentType: Struct.SingleTypeSchema;\n}\n\n/**\n * Returns a single type controller to handle default core-api actions\n */\nconst createSingleTypeController = ({\n contentType,\n}: Options): Utils.PartialWithThis<Core.CoreAPI.Controller.SingleType> => {\n const uid = contentType.uid as UID.Service;\n\n // TODO: transform into a class\n return {\n /**\n * Retrieve single type content\n *\n */\n async find(ctx) {\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const entity = await strapi.service(uid).find(sanitizedQuery);\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * create or update single type content.\n */\n async update(ctx) {\n const { query, body = {} as any } = ctx.request;\n\n if (!isObject(body.data)) {\n throw new errors.ValidationError('Missing \"data\" payload in the request body');\n }\n\n await this.validateInput(body.data, ctx);\n\n const sanitizedInputData = await this.sanitizeInput(body.data, ctx);\n\n const entity = await strapi.service(uid).createOrUpdate({\n ...query,\n data: sanitizedInputData,\n });\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n async delete(ctx) {\n const { query } = ctx;\n\n await strapi.service(uid).delete(query);\n\n ctx.status = 204;\n },\n };\n};\n\nexport { createSingleTypeController };\n"],"names":["isObject","errors"],"mappings":";;;;AAWA,MAAM,6BAA6B,CAAC;AAAA,EAClC;AACF,MAA0E;AACxE,QAAM,MAAM,YAAY;AAGjB,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKL,MAAM,KAAK,KAAK;AACR,YAAA,KAAK,cAAc,GAAG;AAC5B,YAAM,iBAAiB,MAAM,KAAK,cAAc,GAAG;AAEnD,YAAM,SAAS,MAAM,OAAO,QAAQ,GAAG,EAAE,KAAK,cAAc;AAE5D,YAAM,kBAAkB,MAAM,KAAK,eAAe,QAAQ,GAAG;AAEtD,aAAA,KAAK,kBAAkB,eAAe;AAAA,IAC/C;AAAA;AAAA;AAAA;AAAA,IAKA,MAAM,OAAO,KAAK;AAChB,YAAM,EAAE,OAAO,OAAO,CAAC,EAAA,IAAa,IAAI;AAExC,UAAI,CAACA,
|
1
|
+
{"version":3,"file":"single-type.js","sources":["../../../src/core-api/controller/single-type.ts"],"sourcesContent":["import { isObject } from 'lodash/fp';\nimport { errors } from '@strapi/utils';\nimport type { Struct, Core, Utils, UID } from '@strapi/types';\n\ninterface Options {\n contentType: Struct.SingleTypeSchema;\n}\n\n/**\n * Returns a single type controller to handle default core-api actions\n */\nconst createSingleTypeController = ({\n contentType,\n}: Options): Utils.PartialWithThis<Core.CoreAPI.Controller.SingleType> => {\n const uid = contentType.uid as UID.Service;\n\n // TODO: transform into a class\n return {\n /**\n * Retrieve single type content\n *\n */\n async find(ctx) {\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const entity = await strapi.service(uid).find(sanitizedQuery);\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * create or update single type content.\n */\n async update(ctx) {\n const { query, body = {} as any } = ctx.request;\n\n if (!isObject(body.data)) {\n throw new errors.ValidationError('Missing \"data\" payload in the request body');\n }\n\n await this.validateInput(body.data, ctx);\n\n const sanitizedInputData = await this.sanitizeInput(body.data, ctx);\n\n const entity = await strapi.service(uid).createOrUpdate({\n ...query,\n data: sanitizedInputData,\n });\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n async delete(ctx) {\n const { query } = ctx;\n\n await strapi.service(uid).delete(query);\n\n ctx.status = 204;\n },\n };\n};\n\nexport { createSingleTypeController };\n"],"names":["isObject","errors"],"mappings":";;;;AAWA,MAAM,6BAA6B,CAAC;AAAA,EAClC;AACF,MAA0E;AACxE,QAAM,MAAM,YAAY;AAGjB,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKL,MAAM,KAAK,KAAK;AACR,YAAA,KAAK,cAAc,GAAG;AAC5B,YAAM,iBAAiB,MAAM,KAAK,cAAc,GAAG;AAEnD,YAAM,SAAS,MAAM,OAAO,QAAQ,GAAG,EAAE,KAAK,cAAc;AAE5D,YAAM,kBAAkB,MAAM,KAAK,eAAe,QAAQ,GAAG;AAEtD,aAAA,KAAK,kBAAkB,eAAe;AAAA,IAC/C;AAAA;AAAA;AAAA;AAAA,IAKA,MAAM,OAAO,KAAK;AAChB,YAAM,EAAE,OAAO,OAAO,CAAC,EAAA,IAAa,IAAI;AAExC,UAAI,CAACA,GAAA,SAAS,KAAK,IAAI,GAAG;AAClB,cAAA,IAAIC,YAAO,OAAA,gBAAgB,4CAA4C;AAAA,MAC/E;AAEA,YAAM,KAAK,cAAc,KAAK,MAAM,GAAG;AAEvC,YAAM,qBAAqB,MAAM,KAAK,cAAc,KAAK,MAAM,GAAG;AAElE,YAAM,SAAS,MAAM,OAAO,QAAQ,GAAG,EAAE,eAAe;AAAA,QACtD,GAAG;AAAA,QACH,MAAM;AAAA,MAAA,CACP;AAED,YAAM,kBAAkB,MAAM,KAAK,eAAe,QAAQ,GAAG;AAEtD,aAAA,KAAK,kBAAkB,eAAe;AAAA,IAC/C;AAAA,IAEA,MAAM,OAAO,KAAK;AACV,YAAA,EAAE,MAAU,IAAA;AAElB,YAAM,OAAO,QAAQ,GAAG,EAAE,OAAO,KAAK;AAEtC,UAAI,SAAS;AAAA,IACf;AAAA,EAAA;AAEJ;;"}
|
@@ -1,8 +1,8 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
|
-
const
|
3
|
+
const fp = require("lodash/fp");
|
4
4
|
function isEntry(property) {
|
5
|
-
return property === null ||
|
5
|
+
return property === null || fp.isPlainObject(property) || Array.isArray(property);
|
6
6
|
}
|
7
7
|
function isDZEntries(property) {
|
8
8
|
return Array.isArray(property);
|
@@ -10,10 +10,10 @@ function isDZEntries(property) {
|
|
10
10
|
const transformResponse = (resource, meta = {}, opts = {
|
11
11
|
useJsonAPIFormat: false
|
12
12
|
}) => {
|
13
|
-
if (
|
13
|
+
if (fp.isNil(resource)) {
|
14
14
|
return resource;
|
15
15
|
}
|
16
|
-
if (!
|
16
|
+
if (!fp.isPlainObject(resource) && !Array.isArray(resource)) {
|
17
17
|
throw new Error("Entry must be an object or an array of objects");
|
18
18
|
}
|
19
19
|
return {
|
@@ -26,20 +26,20 @@ function transformComponent(data, component) {
|
|
26
26
|
return data.map((datum) => transformComponent(datum, component));
|
27
27
|
}
|
28
28
|
const res = transformEntry(data, component);
|
29
|
-
if (
|
29
|
+
if (fp.isNil(res)) {
|
30
30
|
return res;
|
31
31
|
}
|
32
32
|
const { id, attributes } = res;
|
33
33
|
return { id, ...attributes };
|
34
34
|
}
|
35
35
|
function transformEntry(entry, type) {
|
36
|
-
if (
|
36
|
+
if (fp.isNil(entry)) {
|
37
37
|
return entry;
|
38
38
|
}
|
39
39
|
if (Array.isArray(entry)) {
|
40
40
|
return entry.map((singleEntry) => transformEntry(singleEntry, type));
|
41
41
|
}
|
42
|
-
if (!
|
42
|
+
if (!fp.isPlainObject(entry)) {
|
43
43
|
throw new Error("Entry must be an object");
|
44
44
|
}
|
45
45
|
const { id, documentId, ...properties } = entry;
|
@@ -53,7 +53,7 @@ function transformEntry(entry, type) {
|
|
53
53
|
} else if (attribute && attribute.type === "component" && isEntry(property)) {
|
54
54
|
attributeValues[key] = transformComponent(property, strapi.components[attribute.component]);
|
55
55
|
} else if (attribute && attribute.type === "dynamiczone" && isDZEntries(property)) {
|
56
|
-
if (
|
56
|
+
if (fp.isNil(property)) {
|
57
57
|
attributeValues[key] = property;
|
58
58
|
}
|
59
59
|
attributeValues[key] = property.map((subProperty) => {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"transform.js","sources":["../../../src/core-api/controller/transform.ts"],"sourcesContent":["import { isNil, isPlainObject } from 'lodash/fp';\nimport type { UID, Struct, Data } from '@strapi/types';\n\ntype TransformedEntry = {\n id: string;\n documentId?: Data.DocumentID | null;\n attributes: Record<string, unknown>;\n};\n\ntype TransformedComponent = {\n id: string;\n [key: string]: unknown;\n};\n\ntype Entry = {\n id: string;\n documentId: Data.DocumentID | null;\n [key: string]: Entry | Entry[] | string | number | null | boolean | Date;\n};\n\nfunction isEntry(property: unknown): property is Entry | Entry[] {\n return property === null || isPlainObject(property) || Array.isArray(property);\n}\n\nfunction isDZEntries(property: unknown): property is (Entry & { __component: UID.Component })[] {\n return Array.isArray(property);\n}\n\ninterface TransformOptions {\n contentType?: Struct.ContentTypeSchema | Struct.ComponentSchema;\n /**\n * @deprecated this option is deprecated and will be removed in the next major version\n */\n useJsonAPIFormat?: boolean;\n}\n\nconst transformResponse = (\n resource: any,\n meta: unknown = {},\n opts: TransformOptions = {\n useJsonAPIFormat: false,\n }\n) => {\n if (isNil(resource)) {\n return resource;\n }\n\n if (!isPlainObject(resource) && !Array.isArray(resource)) {\n throw new Error('Entry must be an object or an array of objects');\n }\n\n return {\n data: opts.useJsonAPIFormat ? transformEntry(resource, opts?.contentType) : resource,\n meta,\n };\n};\n\nfunction transformComponent<T extends Entry | Entry[] | null>(\n data: T,\n component: Struct.ComponentSchema\n): T extends Entry[] ? TransformedComponent[] : T extends Entry ? TransformedComponent : null;\nfunction transformComponent(\n data: Entry | Entry[] | null,\n component: Struct.ComponentSchema\n): TransformedComponent | TransformedComponent[] | null {\n if (Array.isArray(data)) {\n return data.map((datum) => transformComponent(datum, component));\n }\n\n const res = transformEntry(data, component);\n\n if (isNil(res)) {\n return res;\n }\n\n const { id, attributes } = res;\n return { id, ...attributes };\n}\n\nfunction transformEntry<T extends Entry | Entry[] | null>(\n entry: T,\n type?: Struct.Schema\n): T extends Entry[] ? TransformedEntry[] : T extends Entry ? TransformedEntry : null;\nfunction transformEntry(\n entry: Entry | Entry[] | null,\n type?: Struct.Schema\n): TransformedEntry | TransformedEntry[] | null {\n if (isNil(entry)) {\n return entry;\n }\n\n if (Array.isArray(entry)) {\n return entry.map((singleEntry) => transformEntry(singleEntry, type));\n }\n\n if (!isPlainObject(entry)) {\n throw new Error('Entry must be an object');\n }\n\n const { id, documentId, ...properties } = entry;\n\n const attributeValues: Record<string, unknown> = {};\n\n for (const key of Object.keys(properties)) {\n const property = properties[key];\n const attribute = type && type.attributes[key];\n\n if (attribute && attribute.type === 'relation' && isEntry(property) && 'target' in attribute) {\n const data = transformEntry(property, strapi.contentType(attribute.target));\n\n attributeValues[key] = { data };\n } else if (attribute && attribute.type === 'component' && isEntry(property)) {\n attributeValues[key] = transformComponent(property, strapi.components[attribute.component]);\n } else if (attribute && attribute.type === 'dynamiczone' && isDZEntries(property)) {\n if (isNil(property)) {\n attributeValues[key] = property;\n }\n\n attributeValues[key] = property.map((subProperty) => {\n return transformComponent(subProperty, strapi.components[subProperty.__component]);\n });\n } else if (attribute && attribute.type === 'media' && isEntry(property)) {\n const data = transformEntry(property, strapi.contentType('plugin::upload.file'));\n\n attributeValues[key] = { data };\n } else {\n attributeValues[key] = property;\n }\n }\n\n return {\n id,\n documentId,\n attributes: attributeValues,\n };\n}\n\nexport { transformResponse };\n"],"names":["isPlainObject","isNil"],"mappings":";;;AAoBA,SAAS,QAAQ,UAAgD;AAC/D,SAAO,aAAa,QAAQA,
|
1
|
+
{"version":3,"file":"transform.js","sources":["../../../src/core-api/controller/transform.ts"],"sourcesContent":["import { isNil, isPlainObject } from 'lodash/fp';\nimport type { UID, Struct, Data } from '@strapi/types';\n\ntype TransformedEntry = {\n id: string;\n documentId?: Data.DocumentID | null;\n attributes: Record<string, unknown>;\n};\n\ntype TransformedComponent = {\n id: string;\n [key: string]: unknown;\n};\n\ntype Entry = {\n id: string;\n documentId: Data.DocumentID | null;\n [key: string]: Entry | Entry[] | string | number | null | boolean | Date;\n};\n\nfunction isEntry(property: unknown): property is Entry | Entry[] {\n return property === null || isPlainObject(property) || Array.isArray(property);\n}\n\nfunction isDZEntries(property: unknown): property is (Entry & { __component: UID.Component })[] {\n return Array.isArray(property);\n}\n\ninterface TransformOptions {\n contentType?: Struct.ContentTypeSchema | Struct.ComponentSchema;\n /**\n * @deprecated this option is deprecated and will be removed in the next major version\n */\n useJsonAPIFormat?: boolean;\n}\n\nconst transformResponse = (\n resource: any,\n meta: unknown = {},\n opts: TransformOptions = {\n useJsonAPIFormat: false,\n }\n) => {\n if (isNil(resource)) {\n return resource;\n }\n\n if (!isPlainObject(resource) && !Array.isArray(resource)) {\n throw new Error('Entry must be an object or an array of objects');\n }\n\n return {\n data: opts.useJsonAPIFormat ? transformEntry(resource, opts?.contentType) : resource,\n meta,\n };\n};\n\nfunction transformComponent<T extends Entry | Entry[] | null>(\n data: T,\n component: Struct.ComponentSchema\n): T extends Entry[] ? TransformedComponent[] : T extends Entry ? TransformedComponent : null;\nfunction transformComponent(\n data: Entry | Entry[] | null,\n component: Struct.ComponentSchema\n): TransformedComponent | TransformedComponent[] | null {\n if (Array.isArray(data)) {\n return data.map((datum) => transformComponent(datum, component));\n }\n\n const res = transformEntry(data, component);\n\n if (isNil(res)) {\n return res;\n }\n\n const { id, attributes } = res;\n return { id, ...attributes };\n}\n\nfunction transformEntry<T extends Entry | Entry[] | null>(\n entry: T,\n type?: Struct.Schema\n): T extends Entry[] ? TransformedEntry[] : T extends Entry ? TransformedEntry : null;\nfunction transformEntry(\n entry: Entry | Entry[] | null,\n type?: Struct.Schema\n): TransformedEntry | TransformedEntry[] | null {\n if (isNil(entry)) {\n return entry;\n }\n\n if (Array.isArray(entry)) {\n return entry.map((singleEntry) => transformEntry(singleEntry, type));\n }\n\n if (!isPlainObject(entry)) {\n throw new Error('Entry must be an object');\n }\n\n const { id, documentId, ...properties } = entry;\n\n const attributeValues: Record<string, unknown> = {};\n\n for (const key of Object.keys(properties)) {\n const property = properties[key];\n const attribute = type && type.attributes[key];\n\n if (attribute && attribute.type === 'relation' && isEntry(property) && 'target' in attribute) {\n const data = transformEntry(property, strapi.contentType(attribute.target));\n\n attributeValues[key] = { data };\n } else if (attribute && attribute.type === 'component' && isEntry(property)) {\n attributeValues[key] = transformComponent(property, strapi.components[attribute.component]);\n } else if (attribute && attribute.type === 'dynamiczone' && isDZEntries(property)) {\n if (isNil(property)) {\n attributeValues[key] = property;\n }\n\n attributeValues[key] = property.map((subProperty) => {\n return transformComponent(subProperty, strapi.components[subProperty.__component]);\n });\n } else if (attribute && attribute.type === 'media' && isEntry(property)) {\n const data = transformEntry(property, strapi.contentType('plugin::upload.file'));\n\n attributeValues[key] = { data };\n } else {\n attributeValues[key] = property;\n }\n }\n\n return {\n id,\n documentId,\n attributes: attributeValues,\n };\n}\n\nexport { transformResponse };\n"],"names":["isPlainObject","isNil"],"mappings":";;;AAoBA,SAAS,QAAQ,UAAgD;AAC/D,SAAO,aAAa,QAAQA,iBAAc,QAAQ,KAAK,MAAM,QAAQ,QAAQ;AAC/E;AAEA,SAAS,YAAY,UAA2E;AACvF,SAAA,MAAM,QAAQ,QAAQ;AAC/B;AAUA,MAAM,oBAAoB,CACxB,UACA,OAAgB,CAAA,GAChB,OAAyB;AAAA,EACvB,kBAAkB;AACpB,MACG;AACC,MAAAC,GAAAA,MAAM,QAAQ,GAAG;AACZ,WAAA;AAAA,EACT;AAEI,MAAA,CAACD,iBAAc,QAAQ,KAAK,CAAC,MAAM,QAAQ,QAAQ,GAAG;AAClD,UAAA,IAAI,MAAM,gDAAgD;AAAA,EAClE;AAEO,SAAA;AAAA,IACL,MAAM,KAAK,mBAAm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AAM,QAAQ,GAAG;AACnB,wBAAgB,GAAG,IAAI;AAAA,MACzB;AAEA,sBAAgB,GAAG,IAAI,SAAS,IAAI,CAAC,gBAAgB;AACnD,eAAO,mBAAmB,aAAa,OAAO,WAAW,YAAY,WAAW,CAAC;AAAA,MAAA,CAClF;AAAA,IAAA,WACQ,aAAa,UAAU,SAAS,WAAW,QAAQ,QAAQ,GAAG;AACvE,YAAM,OAAO,eAAe,UAAU,OAAO,YAAY,qBAAqB,CAAC;AAE/D,sBAAA,GAAG,IAAI,EAAE;IAAK,OACzB;AACL,sBAAgB,GAAG,IAAI;AAAA,IACzB;AAAA,EACF;AAEO,SAAA;AAAA,IACL;AAAA,IACA;AAAA,IACA,YAAY;AAAA,EAAA;AAEhB;;"}
|
@@ -1,15 +1,15 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
|
-
const
|
3
|
+
const fp = require("lodash/fp");
|
4
4
|
const strapiUtils = require("@strapi/utils");
|
5
5
|
const getLimitConfigDefaults = () => ({
|
6
|
-
defaultLimit:
|
7
|
-
maxLimit:
|
6
|
+
defaultLimit: fp.toNumber(strapi.config.get("api.rest.defaultLimit", 25)),
|
7
|
+
maxLimit: fp.toNumber(strapi.config.get("api.rest.maxLimit")) || null
|
8
8
|
});
|
9
|
-
const isOffsetPagination = (pagination2) =>
|
10
|
-
const isPagedPagination = (pagination2) =>
|
9
|
+
const isOffsetPagination = (pagination2) => fp.has("start", pagination2) || fp.has("limit", pagination2);
|
10
|
+
const isPagedPagination = (pagination2) => fp.has("page", pagination2) || fp.has("pageSize", pagination2) || !isOffsetPagination(pagination2);
|
11
11
|
const shouldCount = (params) => {
|
12
|
-
if (
|
12
|
+
if (fp.has("pagination.withCount", params)) {
|
13
13
|
const withCount = params.pagination?.withCount;
|
14
14
|
if (typeof withCount === "boolean") {
|
15
15
|
return withCount;
|
@@ -40,8 +40,8 @@ const getPaginationInfo = (params) => {
|
|
40
40
|
const transformPaginationResponse = (paginationInfo, total, isPaged) => {
|
41
41
|
const transform = isPaged ? strapiUtils.pagination.transformPagedPaginationInfo : strapiUtils.pagination.transformOffsetPaginationInfo;
|
42
42
|
const paginationResponse = transform(paginationInfo, total);
|
43
|
-
if (
|
44
|
-
return
|
43
|
+
if (fp.isNil(total)) {
|
44
|
+
return fp.omit(["total", "pageCount"], paginationResponse);
|
45
45
|
}
|
46
46
|
return paginationResponse;
|
47
47
|
};
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"pagination.js","sources":["../../../src/core-api/service/pagination.ts"],"sourcesContent":["import { omit, has, toNumber, isNil } from 'lodash/fp';\n\nimport { errors, pagination } from '@strapi/utils';\n\ninterface BasePaginationParams {\n withCount?: boolean | 't' | '1' | 'true' | 'f' | '0' | 'false' | 0 | 1;\n}\n\ntype PagedPagination = BasePaginationParams & {\n page?: number;\n pageSize?: number;\n};\n\ntype OffsetPagination = BasePaginationParams & {\n start?: number;\n limit?: number;\n};\n\nexport type PaginationParams = PagedPagination | OffsetPagination;\n\ntype PaginationInfo =\n | {\n page: number;\n pageSize: number;\n }\n | {\n start: number;\n limit: number;\n };\n\n/**\n * Default limit values from config\n */\nconst getLimitConfigDefaults = () => ({\n defaultLimit: toNumber(strapi.config.get('api.rest.defaultLimit', 25)),\n maxLimit: toNumber(strapi.config.get('api.rest.maxLimit')) || null,\n});\n\nconst isOffsetPagination = (pagination?: PaginationParams): pagination is OffsetPagination =>\n has('start', pagination) || has('limit', pagination);\n\nconst isPagedPagination = (pagination?: PaginationParams): pagination is PagedPagination =>\n has('page', pagination) || has('pageSize', pagination) || !isOffsetPagination(pagination);\n\nconst shouldCount = (params: { pagination?: PaginationParams }) => {\n if (has('pagination.withCount', params)) {\n const withCount = params.pagination?.withCount;\n\n if (typeof withCount === 'boolean') {\n return withCount;\n }\n\n if (typeof withCount === 'undefined') {\n return false;\n }\n\n if (['true', 't', '1', 1].includes(withCount)) {\n return true;\n }\n\n if (['false', 'f', '0', 0].includes(withCount)) {\n return false;\n }\n\n throw new errors.ValidationError(\n 'Invalid withCount parameter. Expected \"t\",\"1\",\"true\",\"false\",\"0\",\"f\"'\n );\n }\n\n return Boolean(strapi.config.get('api.rest.withCount', true));\n};\n\nconst getPaginationInfo = (params: { pagination?: PaginationParams }): PaginationInfo => {\n const { defaultLimit, maxLimit } = getLimitConfigDefaults();\n\n const { start, limit } = pagination.withDefaultPagination(params.pagination || {}, {\n defaults: { offset: { limit: defaultLimit }, page: { pageSize: defaultLimit } },\n maxLimit: maxLimit || -1,\n });\n\n return { start, limit };\n};\n\nconst transformPaginationResponse = (\n paginationInfo: PaginationInfo,\n total: number | undefined,\n isPaged: boolean\n) => {\n const transform = isPaged\n ? pagination.transformPagedPaginationInfo\n : pagination.transformOffsetPaginationInfo;\n\n const paginationResponse = transform(paginationInfo, total!);\n\n if (isNil(total)) {\n // Ignore total and pageCount if `total` value is not available.\n return omit(['total', 'pageCount'], paginationResponse) as ReturnType<typeof transform>;\n }\n\n return paginationResponse;\n};\n\nexport { isPagedPagination, shouldCount, getPaginationInfo, transformPaginationResponse };\n"],"names":["toNumber","pagination","has","errors","isNil","omit"],"mappings":";;;;AAiCA,MAAM,yBAAyB,OAAO;AAAA,EACpC,cAAcA,
|
1
|
+
{"version":3,"file":"pagination.js","sources":["../../../src/core-api/service/pagination.ts"],"sourcesContent":["import { omit, has, toNumber, isNil } from 'lodash/fp';\n\nimport { errors, pagination } from '@strapi/utils';\n\ninterface BasePaginationParams {\n withCount?: boolean | 't' | '1' | 'true' | 'f' | '0' | 'false' | 0 | 1;\n}\n\ntype PagedPagination = BasePaginationParams & {\n page?: number;\n pageSize?: number;\n};\n\ntype OffsetPagination = BasePaginationParams & {\n start?: number;\n limit?: number;\n};\n\nexport type PaginationParams = PagedPagination | OffsetPagination;\n\ntype PaginationInfo =\n | {\n page: number;\n pageSize: number;\n }\n | {\n start: number;\n limit: number;\n };\n\n/**\n * Default limit values from config\n */\nconst getLimitConfigDefaults = () => ({\n defaultLimit: toNumber(strapi.config.get('api.rest.defaultLimit', 25)),\n maxLimit: toNumber(strapi.config.get('api.rest.maxLimit')) || null,\n});\n\nconst isOffsetPagination = (pagination?: PaginationParams): pagination is OffsetPagination =>\n has('start', pagination) || has('limit', pagination);\n\nconst isPagedPagination = (pagination?: PaginationParams): pagination is PagedPagination =>\n has('page', pagination) || has('pageSize', pagination) || !isOffsetPagination(pagination);\n\nconst shouldCount = (params: { pagination?: PaginationParams }) => {\n if (has('pagination.withCount', params)) {\n const withCount = params.pagination?.withCount;\n\n if (typeof withCount === 'boolean') {\n return withCount;\n }\n\n if (typeof withCount === 'undefined') {\n return false;\n }\n\n if (['true', 't', '1', 1].includes(withCount)) {\n return true;\n }\n\n if (['false', 'f', '0', 0].includes(withCount)) {\n return false;\n }\n\n throw new errors.ValidationError(\n 'Invalid withCount parameter. Expected \"t\",\"1\",\"true\",\"false\",\"0\",\"f\"'\n );\n }\n\n return Boolean(strapi.config.get('api.rest.withCount', true));\n};\n\nconst getPaginationInfo = (params: { pagination?: PaginationParams }): PaginationInfo => {\n const { defaultLimit, maxLimit } = getLimitConfigDefaults();\n\n const { start, limit } = pagination.withDefaultPagination(params.pagination || {}, {\n defaults: { offset: { limit: defaultLimit }, page: { pageSize: defaultLimit } },\n maxLimit: maxLimit || -1,\n });\n\n return { start, limit };\n};\n\nconst transformPaginationResponse = (\n paginationInfo: PaginationInfo,\n total: number | undefined,\n isPaged: boolean\n) => {\n const transform = isPaged\n ? pagination.transformPagedPaginationInfo\n : pagination.transformOffsetPaginationInfo;\n\n const paginationResponse = transform(paginationInfo, total!);\n\n if (isNil(total)) {\n // Ignore total and pageCount if `total` value is not available.\n return omit(['total', 'pageCount'], paginationResponse) as ReturnType<typeof transform>;\n }\n\n return paginationResponse;\n};\n\nexport { isPagedPagination, shouldCount, getPaginationInfo, transformPaginationResponse };\n"],"names":["toNumber","pagination","has","errors","isNil","omit"],"mappings":";;;;AAiCA,MAAM,yBAAyB,OAAO;A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;AACH,QAAM,YAAY,UACdA,YAAAA,WAAW,+BACXA,YAAAA,WAAW;AAET,QAAA,qBAAqB,UAAU,gBAAgB,KAAM;AAEvD,MAAAG,GAAAA,MAAM,KAAK,GAAG;AAEhB,WAAOC,GAAK,KAAA,CAAC,SAAS,WAAW,GAAG,kBAAkB;AAAA,EACxD;AAEO,SAAA;AACT;;;;;"}
|
@@ -1,11 +1,11 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
|
-
const
|
4
|
-
const _
|
3
|
+
const fp = require("lodash/fp");
|
4
|
+
const _ = require("lodash");
|
5
5
|
const strapiUtils = require("@strapi/utils");
|
6
6
|
const validator = require("./validator.js");
|
7
7
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
8
|
-
const ___default = /* @__PURE__ */ _interopDefault(_
|
8
|
+
const ___default = /* @__PURE__ */ _interopDefault(_);
|
9
9
|
const {
|
10
10
|
CREATED_AT_ATTRIBUTE,
|
11
11
|
UPDATED_AT_ATTRIBUTE,
|
@@ -23,7 +23,7 @@ ${e.errors}`);
|
|
23
23
|
}
|
24
24
|
throw e;
|
25
25
|
}
|
26
|
-
const { schema, actions, lifecycles } =
|
26
|
+
const { schema, actions, lifecycles } = fp.cloneDeep(definition);
|
27
27
|
Object.assign(schema, {
|
28
28
|
uid,
|
29
29
|
modelType: "contentType",
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/domain/content-type/index.ts"],"sourcesContent":["import { cloneDeep } from 'lodash/fp';\nimport _ from 'lodash';\nimport { yup, contentTypes as contentTypesUtils } from '@strapi/utils';\nimport type { Schema } from '@strapi/types';\nimport { validateContentTypeDefinition } from './validator';\n\nexport type ContentTypeDefinition = {\n schema: Schema.ContentType;\n actions: Record<string, unknown>;\n lifecycles: Record<string, unknown>;\n};\n\nconst {\n CREATED_AT_ATTRIBUTE,\n UPDATED_AT_ATTRIBUTE,\n PUBLISHED_AT_ATTRIBUTE,\n CREATED_BY_ATTRIBUTE,\n UPDATED_BY_ATTRIBUTE,\n} = contentTypesUtils.constants;\n\nconst createContentType = (uid: string, definition: ContentTypeDefinition) => {\n try {\n validateContentTypeDefinition(definition);\n } catch (e) {\n if (e instanceof yup.ValidationError) {\n throw new Error(`Content Type Definition is invalid for ${uid}'.\\n${e.errors}`);\n }\n\n throw e;\n }\n\n const { schema, actions, lifecycles } = cloneDeep(definition);\n\n // general info\n Object.assign(schema, {\n uid,\n modelType: 'contentType',\n kind: schema.kind || 'collectionType',\n __schema__: pickSchema(definition.schema),\n modelName: definition.schema.info.singularName,\n actions,\n lifecycles,\n });\n\n addTimestamps(schema);\n\n // Published at is added regardless of draft and publish being enabled\n // In case it is not enabled, value will be always published, and it will not contain a draft\n addDraftAndPublish(schema);\n\n addCreatorFields(schema);\n\n return schema;\n};\n\nconst addTimestamps = (schema: Schema.ContentType) => {\n // attributes\n Object.assign(schema.attributes, {\n [CREATED_AT_ATTRIBUTE]: {\n type: 'datetime',\n },\n // TODO: handle on edit set to new date\n [UPDATED_AT_ATTRIBUTE]: {\n type: 'datetime',\n },\n });\n};\n\nconst addDraftAndPublish = (schema: Schema.ContentType) => {\n if (!_.has(schema, 'options.draftAndPublish')) {\n _.set(schema, 'options.draftAndPublish', false); // Disabled by default\n }\n\n schema.attributes[PUBLISHED_AT_ATTRIBUTE] = {\n type: 'datetime',\n configurable: false,\n writable: true,\n visible: false,\n default() {\n return new Date();\n },\n };\n};\n\nconst addCreatorFields = (schema: Schema.ContentType) => {\n const isPrivate = !_.get(schema, 'options.populateCreatorFields', false);\n\n schema.attributes[CREATED_BY_ATTRIBUTE] = {\n type: 'relation',\n relation: 'oneToOne',\n target: 'admin::user',\n configurable: false,\n writable: false,\n visible: false,\n useJoinTable: false,\n private: isPrivate,\n };\n\n schema.attributes[UPDATED_BY_ATTRIBUTE] = {\n type: 'relation',\n relation: 'oneToOne',\n target: 'admin::user',\n configurable: false,\n writable: false,\n visible: false,\n useJoinTable: false,\n private: isPrivate,\n };\n};\n\nconst getGlobalId = (schema: Schema.ContentType, prefix?: string) => {\n const modelName = schema.info.singularName;\n const globalId = prefix ? `${prefix}-${modelName}` : modelName;\n\n return schema.globalId || _.upperFirst(_.camelCase(globalId));\n};\n\nconst pickSchema = (model: Schema.ContentType) => {\n const schema = _.cloneDeep(\n _.pick(model, [\n 'connection',\n 'collectionName',\n 'info',\n 'options',\n 'pluginOptions',\n 'attributes',\n 'kind',\n ])\n );\n\n schema.kind = model.kind || 'collectionType';\n return schema;\n};\n\nexport { createContentType, getGlobalId };\n"],"names":["contentTypesUtils","validateContentTypeDefinition","yup","cloneDeep","_"],"mappings":";;;;;;;;AAYA,MAAM;AAAA,EACJ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,IAAIA,YAAAA,aAAkB;AAEhB,MAAA,oBAAoB,CAAC,KAAa,eAAsC;AACxE,MAAA;AACFC,cAAA,8BAA8B,UAAU;AAAA,WACjC,GAAG;AACN,QAAA,aAAaC,gBAAI,iBAAiB;AAC9B,YAAA,IAAI,MAAM,0CAA0C,GAAG;AAAA,EAAO,EAAE,MAAM,EAAE;AAAA,IAChF;AAEM,UAAA;AAAA,EACR;AAEA,QAAM,EAAE,QAAQ,SAAS,WAAW,IAAIC,
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/domain/content-type/index.ts"],"sourcesContent":["import { cloneDeep } from 'lodash/fp';\nimport _ from 'lodash';\nimport { yup, contentTypes as contentTypesUtils } from '@strapi/utils';\nimport type { Schema } from '@strapi/types';\nimport { validateContentTypeDefinition } from './validator';\n\nexport type ContentTypeDefinition = {\n schema: Schema.ContentType;\n actions: Record<string, unknown>;\n lifecycles: Record<string, unknown>;\n};\n\nconst {\n CREATED_AT_ATTRIBUTE,\n UPDATED_AT_ATTRIBUTE,\n PUBLISHED_AT_ATTRIBUTE,\n CREATED_BY_ATTRIBUTE,\n UPDATED_BY_ATTRIBUTE,\n} = contentTypesUtils.constants;\n\nconst createContentType = (uid: string, definition: ContentTypeDefinition) => {\n try {\n validateContentTypeDefinition(definition);\n } catch (e) {\n if (e instanceof yup.ValidationError) {\n throw new Error(`Content Type Definition is invalid for ${uid}'.\\n${e.errors}`);\n }\n\n throw e;\n }\n\n const { schema, actions, lifecycles } = cloneDeep(definition);\n\n // general info\n Object.assign(schema, {\n uid,\n modelType: 'contentType',\n kind: schema.kind || 'collectionType',\n __schema__: pickSchema(definition.schema),\n modelName: definition.schema.info.singularName,\n actions,\n lifecycles,\n });\n\n addTimestamps(schema);\n\n // Published at is added regardless of draft and publish being enabled\n // In case it is not enabled, value will be always published, and it will not contain a draft\n addDraftAndPublish(schema);\n\n addCreatorFields(schema);\n\n return schema;\n};\n\nconst addTimestamps = (schema: Schema.ContentType) => {\n // attributes\n Object.assign(schema.attributes, {\n [CREATED_AT_ATTRIBUTE]: {\n type: 'datetime',\n },\n // TODO: handle on edit set to new date\n [UPDATED_AT_ATTRIBUTE]: {\n type: 'datetime',\n },\n });\n};\n\nconst addDraftAndPublish = (schema: Schema.ContentType) => {\n if (!_.has(schema, 'options.draftAndPublish')) {\n _.set(schema, 'options.draftAndPublish', false); // Disabled by default\n }\n\n schema.attributes[PUBLISHED_AT_ATTRIBUTE] = {\n type: 'datetime',\n configurable: false,\n writable: true,\n visible: false,\n default() {\n return new Date();\n },\n };\n};\n\nconst addCreatorFields = (schema: Schema.ContentType) => {\n const isPrivate = !_.get(schema, 'options.populateCreatorFields', false);\n\n schema.attributes[CREATED_BY_ATTRIBUTE] = {\n type: 'relation',\n relation: 'oneToOne',\n target: 'admin::user',\n configurable: false,\n writable: false,\n visible: false,\n useJoinTable: false,\n private: isPrivate,\n };\n\n schema.attributes[UPDATED_BY_ATTRIBUTE] = {\n type: 'relation',\n relation: 'oneToOne',\n target: 'admin::user',\n configurable: false,\n writable: false,\n visible: false,\n useJoinTable: false,\n private: isPrivate,\n };\n};\n\nconst getGlobalId = (schema: Schema.ContentType, prefix?: string) => {\n const modelName = schema.info.singularName;\n const globalId = prefix ? `${prefix}-${modelName}` : modelName;\n\n return schema.globalId || _.upperFirst(_.camelCase(globalId));\n};\n\nconst pickSchema = (model: Schema.ContentType) => {\n const schema = _.cloneDeep(\n _.pick(model, [\n 'connection',\n 'collectionName',\n 'info',\n 'options',\n 'pluginOptions',\n 'attributes',\n 'kind',\n ])\n );\n\n schema.kind = model.kind || 'collectionType';\n return schema;\n};\n\nexport { createContentType, getGlobalId };\n"],"names":["contentTypesUtils","validateContentTypeDefinition","yup","cloneDeep","_"],"mappings":";;;;;;;;AAYA,MAAM;AAAA,EACJ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,IAAIA,YAAAA,aAAkB;AAEhB,MAAA,oBAAoB,CAAC,KAAa,eAAsC;AACxE,MAAA;AACFC,cAAA,8BAA8B,UAAU;AAAA,WACjC,GAAG;AACN,QAAA,aAAaC,gBAAI,iBAAiB;AAC9B,YAAA,IAAI,MAAM,0CAA0C,GAAG;AAAA,EAAO,EAAE,MAAM,EAAE;AAAA,IAChF;AAEM,UAAA;AAAA,EACR;AAEA,QAAM,EAAE,QAAQ,SAAS,WAAW,IAAIC,GAAAA,UAAU,UAAU;AAG5D,SAAO,OAAO,QAAQ;AAAA,IACpB;AAAA,IACA,WAAW;AAAA,IACX,MAAM,OAAO,QAAQ;AAAA,IACrB,YAAY,WAAW,WAAW,MAAM;AAAA,IACxC,WAAW,WAAW,OAAO,KAAK;AAAA,IAClC;AAAA,IACA;AAAA,EAAA,CACD;AAED,gBAAc,MAAM;AAIpB,qBAAmB,MAAM;AAEzB,mBAAiB,MAAM;AAEhB,SAAA;AACT;AAEA,MAAM,gBAAgB,CAAC,WAA+B;AAE7C,SAAA,OAAO,OAAO,YAAY;AAAA,IAC/B,CAAC,oBAAoB,GAAG;AAAA,MACtB,MAAM;AAAA,IACR;AAAA;AAAA,IAEA,CAAC,oBAAoB,GAAG;AAAA,MACtB,MAAM;AAAA,IACR;AAAA,EAAA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AAQ;AACrB,SAAA;AACT;;;"}
|
package/dist/ee/index.js
CHANGED
@@ -1,5 +1,5 @@
|
|
1
1
|
"use strict";
|
2
|
-
const
|
2
|
+
const fp = require("lodash/fp");
|
3
3
|
const license = require("./license.js");
|
4
4
|
const cron = require("../utils/cron.js");
|
5
5
|
const ONE_MINUTE = 1e3 * 60;
|
@@ -10,7 +10,7 @@ const ee = {
|
|
10
10
|
const disable = (message) => {
|
11
11
|
const shouldEmitEvent = ee.enabled !== false;
|
12
12
|
ee.logger?.warn(`${message} Switching to CE.`);
|
13
|
-
ee.licenseInfo =
|
13
|
+
ee.licenseInfo = fp.pick("licenseKey", ee.licenseInfo);
|
14
14
|
ee.enabled = false;
|
15
15
|
if (shouldEmitEvent) {
|
16
16
|
strapi.eventHub.emit("ee.disable");
|
@@ -73,7 +73,7 @@ const onlineUpdate = async ({ strapi: strapi2 }) => {
|
|
73
73
|
if (license$1) {
|
74
74
|
try {
|
75
75
|
const newLicenseInfo = license.verifyLicense(license$1);
|
76
|
-
const licenseInfoChanged = !
|
76
|
+
const licenseInfoChanged = !fp.isEqual(newLicenseInfo.features, ee.licenseInfo.features) || newLicenseInfo.seats !== ee.licenseInfo.seats || newLicenseInfo.type !== ee.licenseInfo.type;
|
77
77
|
ee.licenseInfo = newLicenseInfo;
|
78
78
|
const wasEnabled = ee.enabled;
|
79
79
|
validateInfo();
|
package/dist/ee/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../src/ee/index.ts"],"sourcesContent":["import { pick, isEqual } from 'lodash/fp';\nimport type { Logger } from '@strapi/logger';\nimport type { Core } from '@strapi/types';\n\nimport { readLicense, verifyLicense, fetchLicense, LicenseCheckError } from './license';\nimport { shiftCronExpression } from '../utils/cron';\n\nconst ONE_MINUTE = 1000 * 60;\n\ninterface EE {\n enabled: boolean;\n licenseInfo: {\n licenseKey?: string;\n features?: Array<{ name: string; [key: string]: any } | string>;\n expireAt?: string;\n seats?: number;\n type?: string;\n };\n logger?: Logger;\n}\n\nconst ee: EE = {\n enabled: false,\n licenseInfo: {},\n};\n\nconst disable = (message: string) => {\n // Prevent emitting ee.disable if it was already disabled\n const shouldEmitEvent = ee.enabled !== false;\n\n ee.logger?.warn(`${message} Switching to CE.`);\n // Only keep the license key for potential re-enabling during a later check\n ee.licenseInfo = pick('licenseKey', ee.licenseInfo);\n\n ee.enabled = false;\n\n if (shouldEmitEvent) {\n // Notify EE features that they should be disabled\n strapi.eventHub.emit('ee.disable');\n }\n};\n\nconst enable = () => {\n // Prevent emitting ee.enable if it was already enabled\n const shouldEmitEvent = ee.enabled !== true;\n\n ee.enabled = true;\n\n if (shouldEmitEvent) {\n // Notify EE features that they should be disabled\n strapi.eventHub.emit('ee.enable');\n }\n};\n\nlet initialized = false;\n\n/**\n * Optimistically enable EE if the format of the license is valid, only run once.\n */\nconst init = (licenseDir: string, logger?: Logger) => {\n if (initialized) {\n return;\n }\n\n initialized = true;\n ee.logger = logger;\n\n if (process.env.STRAPI_DISABLE_EE?.toLowerCase() === 'true') {\n return;\n }\n\n try {\n const license = process.env.STRAPI_LICENSE || readLicense(licenseDir);\n\n if (license) {\n ee.licenseInfo = verifyLicense(license);\n enable();\n }\n } catch (error) {\n if (error instanceof Error) {\n disable(error.message);\n } else {\n disable('Invalid license.');\n }\n }\n};\n\n/**\n * Contact the license registry to update the license to its latest state.\n *\n * Store the result in database to avoid unecessary requests, and will fallback to that in case of a network failure.\n */\nconst onlineUpdate = async ({ strapi }: { strapi: Core.Strapi }) => {\n const { get, commit, rollback } = (await strapi.db?.transaction()) as any;\n const transaction = get();\n\n try {\n const storedInfo = await strapi.db\n ?.queryBuilder('strapi::core-store')\n .where({ key: 'ee_information' })\n .select('value')\n .first()\n .transacting(transaction)\n .forUpdate()\n .execute()\n .then((result: any) => (result ? JSON.parse(result.value) : result));\n\n const shouldContactRegistry = (storedInfo?.lastCheckAt ?? 0) < Date.now() - ONE_MINUTE;\n const result: {\n license?: string | null;\n error?: string;\n lastCheckAt?: number;\n } = { lastCheckAt: Date.now() };\n\n const fallback = (error: Error) => {\n if (error instanceof LicenseCheckError && error.shouldFallback && storedInfo?.license) {\n ee.logger?.warn(\n `${error.message} The last stored one will be used as a potential fallback.`\n );\n return storedInfo.license;\n }\n\n result.error = error.message;\n disable(error.message);\n };\n\n if (!ee?.licenseInfo?.licenseKey) {\n throw new Error('Missing license key.');\n }\n\n const license = shouldContactRegistry\n ? await fetchLicense({ strapi }, ee.licenseInfo.licenseKey, strapi.config.get('uuid')).catch(\n fallback\n )\n : storedInfo.license;\n\n if (license) {\n try {\n // Verify license and check if its info changed\n const newLicenseInfo = verifyLicense(license);\n const licenseInfoChanged =\n !isEqual(newLicenseInfo.features, ee.licenseInfo.features) ||\n newLicenseInfo.seats !== ee.licenseInfo.seats ||\n newLicenseInfo.type !== ee.licenseInfo.type;\n\n // Store the new license info\n ee.licenseInfo = newLicenseInfo;\n const wasEnabled = ee.enabled;\n validateInfo();\n\n // Notify EE features\n if (licenseInfoChanged && wasEnabled) {\n strapi.eventHub.emit('ee.update');\n }\n } catch (error) {\n if (error instanceof Error) {\n disable(error.message);\n } else {\n disable('Invalid license.');\n }\n }\n } else if (!shouldContactRegistry) {\n disable(storedInfo.error);\n }\n\n if (shouldContactRegistry) {\n result.license = license ?? null;\n const query = strapi.db.queryBuilder('strapi::core-store').transacting(transaction);\n\n if (!storedInfo) {\n query.insert({ key: 'ee_information', value: JSON.stringify(result) });\n } else {\n query.update({ value: JSON.stringify(result) }).where({ key: 'ee_information' });\n }\n\n await query.execute();\n }\n\n await commit();\n } catch (error) {\n // Example of errors: SQLite does not support FOR UPDATE\n await rollback();\n }\n};\n\nconst validateInfo = () => {\n if (typeof ee.licenseInfo.expireAt === 'undefined') {\n throw new Error('Missing license key.');\n }\n\n const expirationTime = new Date(ee.licenseInfo.expireAt).getTime();\n\n if (expirationTime < new Date().getTime()) {\n return disable('License expired.');\n }\n\n enable();\n};\n\nconst checkLicense = async ({ strapi }: { strapi: Core.Strapi }) => {\n const shouldStayOffline =\n ee.licenseInfo.type === 'gold' &&\n // This env variable support is temporarily used to ease the migration between online vs offline\n process.env.STRAPI_DISABLE_LICENSE_PING?.toLowerCase() === 'true';\n\n if (!shouldStayOffline) {\n await onlineUpdate({ strapi });\n strapi.cron.add({ [shiftCronExpression('0 0 */12 * * *')]: onlineUpdate });\n } else {\n if (!ee.licenseInfo.expireAt) {\n return disable('Your license does not have offline support.');\n }\n\n validateInfo();\n }\n};\n\nconst list = () => {\n return (\n ee.licenseInfo.features?.map((feature) =>\n typeof feature === 'object' ? feature : { name: feature }\n ) || []\n );\n};\n\nconst get = (featureName: string) => list().find((feature) => feature.name === featureName);\n\nexport default Object.freeze({\n init,\n checkLicense,\n\n get isEE() {\n return ee.enabled;\n },\n\n get seats() {\n return ee.licenseInfo.seats;\n },\n\n features: Object.freeze({\n list,\n get,\n isEnabled: (featureName: string) => get(featureName) !== undefined,\n }),\n});\n"],"names":["pick","license","readLicense","verifyLicense","strapi","get","result","LicenseCheckError","fetchLicense","isEqual","shiftCronExpression"],"mappings":";;;;AAOA,MAAM,aAAa,MAAO;AAc1B,MAAM,KAAS;AAAA,EACb,SAAS;AAAA,EACT,aAAa,CAAC;AAChB;AAEA,MAAM,UAAU,CAAC,YAAoB;AAE7B,QAAA,kBAAkB,GAAG,YAAY;AAEvC,KAAG,QAAQ,KAAK,GAAG,OAAO,mBAAmB;AAE7C,KAAG,cAAcA,EAAA,KAAK,cAAc,GAAG,WAAW;AAElD,KAAG,UAAU;AAEb,MAAI,iBAAiB;AAEZ,WAAA,SAAS,KAAK,YAAY;AAAA,EACnC;AACF;AAEA,MAAM,SAAS,MAAM;AAEb,QAAA,kBAAkB,GAAG,YAAY;AAEvC,KAAG,UAAU;AAEb,MAAI,iBAAiB;AAEZ,WAAA,SAAS,KAAK,WAAW;AAAA,EAClC;AACF;AAEA,IAAI,cAAc;AAKlB,MAAM,OAAO,CAAC,YAAoB,WAAoB;AACpD,MAAI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K,GAAG,YAAY,QAAQ,EAAE;AAEzD,MAAI,kBAAiB,oBAAI,KAAK,GAAE,WAAW;AACzC,WAAO,QAAQ,kBAAkB;AAAA,EACnC;AAEO;AACT;AAEA,MAAM,eAAe,OAAO,EAAE,QAAAA,cAAsC;AAC5D,QAAA,oBACJ,GAAG,YAAY,SAAS;AAAA,EAExB,QAAQ,IAAI,6BAA6B,YAAA,MAAkB;AAE7D,MAAI,CAAC,mBAAmB;AACtB,UAAM,aAAa,EAAE,QAAAA,QAAQ,CAAA;AAC7BA,YAAO,KAAK,IAAI,EAAE,CAACM,yBAAoB,gBAAgB,CAAC,GAAG,aAAA,CAAc;AAAA,EAAA,OACpE;AACD,QAAA,CAAC,GAAG,YAAY,UAAU;AAC5B,aAAO,QAAQ,6CAA6C;AAAA,IAC9D;AAEa;EACf;AACF;AAEA,MAAM,OAAO,MAAM;AAEf,SAAA,GAAG,YAAY,UAAU;AAAA,IAAI,CAAC,YAC5B,OAAO,YAAY,WAAW,UAAU,EAAE,MAAM,QAAQ;AAAA,OACrD;AAET;AAEA,MAAM,MAAM,CAAC,gBAAwB,OAAO,KAAK,CAAC,YAAY,QAAQ,SAAS,WAAW;AAE1F,MAAe,QAAA,OAAO,OAAO;AAAA,EAC3B;AAAA,EACA;AAAA,EAEA,IAAI,OAAO;AACT,WAAO,GAAG;AAAA,EACZ;AAAA,EAEA,IAAI,QAAQ;AACV,WAAO,GAAG,YAAY;AAAA,EACxB;AAAA,EAEA,UAAU,OAAO,OAAO;AAAA,IACtB;AAAA,IACA;AAAA,IACA,WAAW,CAAC,gBAAwB,IAAI,WAAW,MAAM;AAAA,EAAA,CAC1D;AACH,CAAC;;"}
|
1
|
+
{"version":3,"file":"index.js","sources":["../../src/ee/index.ts"],"sourcesContent":["import { pick, isEqual } from 'lodash/fp';\nimport type { Logger } from '@strapi/logger';\nimport type { Core } from '@strapi/types';\n\nimport { readLicense, verifyLicense, fetchLicense, LicenseCheckError } from './license';\nimport { shiftCronExpression } from '../utils/cron';\n\nconst ONE_MINUTE = 1000 * 60;\n\ninterface EE {\n enabled: boolean;\n licenseInfo: {\n licenseKey?: string;\n features?: Array<{ name: string; [key: string]: any } | string>;\n expireAt?: string;\n seats?: number;\n type?: string;\n };\n logger?: Logger;\n}\n\nconst ee: EE = {\n enabled: false,\n licenseInfo: {},\n};\n\nconst disable = (message: string) => {\n // Prevent emitting ee.disable if it was already disabled\n const shouldEmitEvent = ee.enabled !== false;\n\n ee.logger?.warn(`${message} Switching to CE.`);\n // Only keep the license key for potential re-enabling during a later check\n ee.licenseInfo = pick('licenseKey', ee.licenseInfo);\n\n ee.enabled = false;\n\n if (shouldEmitEvent) {\n // Notify EE features that they should be disabled\n strapi.eventHub.emit('ee.disable');\n }\n};\n\nconst enable = () => {\n // Prevent emitting ee.enable if it was already enabled\n const shouldEmitEvent = ee.enabled !== true;\n\n ee.enabled = true;\n\n if (shouldEmitEvent) {\n // Notify EE features that they should be disabled\n strapi.eventHub.emit('ee.enable');\n }\n};\n\nlet initialized = false;\n\n/**\n * Optimistically enable EE if the format of the license is valid, only run once.\n */\nconst init = (licenseDir: string, logger?: Logger) => {\n if (initialized) {\n return;\n }\n\n initialized = true;\n ee.logger = logger;\n\n if (process.env.STRAPI_DISABLE_EE?.toLowerCase() === 'true') {\n return;\n }\n\n try {\n const license = process.env.STRAPI_LICENSE || readLicense(licenseDir);\n\n if (license) {\n ee.licenseInfo = verifyLicense(license);\n enable();\n }\n } catch (error) {\n if (error instanceof Error) {\n disable(error.message);\n } else {\n disable('Invalid license.');\n }\n }\n};\n\n/**\n * Contact the license registry to update the license to its latest state.\n *\n * Store the result in database to avoid unecessary requests, and will fallback to that in case of a network failure.\n */\nconst onlineUpdate = async ({ strapi }: { strapi: Core.Strapi }) => {\n const { get, commit, rollback } = (await strapi.db?.transaction()) as any;\n const transaction = get();\n\n try {\n const storedInfo = await strapi.db\n ?.queryBuilder('strapi::core-store')\n .where({ key: 'ee_information' })\n .select('value')\n .first()\n .transacting(transaction)\n .forUpdate()\n .execute()\n .then((result: any) => (result ? JSON.parse(result.value) : result));\n\n const shouldContactRegistry = (storedInfo?.lastCheckAt ?? 0) < Date.now() - ONE_MINUTE;\n const result: {\n license?: string | null;\n error?: string;\n lastCheckAt?: number;\n } = { lastCheckAt: Date.now() };\n\n const fallback = (error: Error) => {\n if (error instanceof LicenseCheckError && error.shouldFallback && storedInfo?.license) {\n ee.logger?.warn(\n `${error.message} The last stored one will be used as a potential fallback.`\n );\n return storedInfo.license;\n }\n\n result.error = error.message;\n disable(error.message);\n };\n\n if (!ee?.licenseInfo?.licenseKey) {\n throw new Error('Missing license key.');\n }\n\n const license = shouldContactRegistry\n ? await fetchLicense({ strapi }, ee.licenseInfo.licenseKey, strapi.config.get('uuid')).catch(\n fallback\n )\n : storedInfo.license;\n\n if (license) {\n try {\n // Verify license and check if its info changed\n const newLicenseInfo = verifyLicense(license);\n const licenseInfoChanged =\n !isEqual(newLicenseInfo.features, ee.licenseInfo.features) ||\n newLicenseInfo.seats !== ee.licenseInfo.seats ||\n newLicenseInfo.type !== ee.licenseInfo.type;\n\n // Store the new license info\n ee.licenseInfo = newLicenseInfo;\n const wasEnabled = ee.enabled;\n validateInfo();\n\n // Notify EE features\n if (licenseInfoChanged && wasEnabled) {\n strapi.eventHub.emit('ee.update');\n }\n } catch (error) {\n if (error instanceof Error) {\n disable(error.message);\n } else {\n disable('Invalid license.');\n }\n }\n } else if (!shouldContactRegistry) {\n disable(storedInfo.error);\n }\n\n if (shouldContactRegistry) {\n result.license = license ?? null;\n const query = strapi.db.queryBuilder('strapi::core-store').transacting(transaction);\n\n if (!storedInfo) {\n query.insert({ key: 'ee_information', value: JSON.stringify(result) });\n } else {\n query.update({ value: JSON.stringify(result) }).where({ key: 'ee_information' });\n }\n\n await query.execute();\n }\n\n await commit();\n } catch (error) {\n // Example of errors: SQLite does not support FOR UPDATE\n await rollback();\n }\n};\n\nconst validateInfo = () => {\n if (typeof ee.licenseInfo.expireAt === 'undefined') {\n throw new Error('Missing license key.');\n }\n\n const expirationTime = new Date(ee.licenseInfo.expireAt).getTime();\n\n if (expirationTime < new Date().getTime()) {\n return disable('License expired.');\n }\n\n enable();\n};\n\nconst checkLicense = async ({ strapi }: { strapi: Core.Strapi }) => {\n const shouldStayOffline =\n ee.licenseInfo.type === 'gold' &&\n // This env variable support is temporarily used to ease the migration between online vs offline\n process.env.STRAPI_DISABLE_LICENSE_PING?.toLowerCase() === 'true';\n\n if (!shouldStayOffline) {\n await onlineUpdate({ strapi });\n strapi.cron.add({ [shiftCronExpression('0 0 */12 * * *')]: onlineUpdate });\n } else {\n if (!ee.licenseInfo.expireAt) {\n return disable('Your license does not have offline support.');\n }\n\n validateInfo();\n }\n};\n\nconst list = () => {\n return (\n ee.licenseInfo.features?.map((feature) =>\n typeof feature === 'object' ? feature : { name: feature }\n ) || []\n );\n};\n\nconst get = (featureName: string) => list().find((feature) => feature.name === featureName);\n\nexport default Object.freeze({\n init,\n checkLicense,\n\n get isEE() {\n return ee.enabled;\n },\n\n get seats() {\n return ee.licenseInfo.seats;\n },\n\n features: Object.freeze({\n list,\n get,\n isEnabled: (featureName: string) => get(featureName) !== undefined,\n }),\n});\n"],"names":["pick","license","readLicense","verifyLicense","strapi","get","result","LicenseCheckError","fetchLicense","isEqual","shiftCronExpression"],"mappings":";;;;AAOA,MAAM,aAAa,MAAO;AAc1B,MAAM,KAAS;AAAA,EACb,SAAS;AAAA,EACT,aAAa,CAAC;AAChB;AAEA,MAAM,UAAU,CAAC,YAAoB;AAE7B,QAAA,kBAAkB,GAAG,YAAY;AAEvC,KAAG,QAAQ,KAAK,GAAG,OAAO,mBAAmB;AAE7C,KAAG,cAAcA,GAAA,KAAK,cAAc,GAAG,WAAW;AAElD,KAAG,UAAU;AAEb,MAAI,iBAAiB;AAEZ,WAAA,SAAS,KAAK,YAAY;AAAA,EACnC;AACF;AAEA,MAAM,SAAS,MAAM;AAEb,QAAA,kBAAkB,GAAG,YAAY;AAEvC,KAAG,UA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"use strict";
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
|
-
const
|
3
|
+
const fp = require("lodash/fp");
|
4
4
|
const index = require("./core-api/controller/index.js");
|
5
5
|
const index$1 = require("./core-api/service/index.js");
|
6
6
|
const index$2 = require("./core-api/routes/index.js");
|
@@ -60,9 +60,9 @@ function createCoreRouter(uid, cfg) {
|
|
60
60
|
const defaultRoute = defaultRoutes[routeName];
|
61
61
|
Object.assign(defaultRoute.config, config[routeName] || {});
|
62
62
|
});
|
63
|
-
const selectedRoutes =
|
64
|
-
(routes2) => except ?
|
65
|
-
(routes2) => only ?
|
63
|
+
const selectedRoutes = fp.pipe(
|
64
|
+
(routes2) => except ? fp.omit(except, routes2) : routes2,
|
65
|
+
(routes2) => only ? fp.pick(only, routes2) : routes2
|
66
66
|
)(defaultRoutes);
|
67
67
|
routes = Object.values(selectedRoutes);
|
68
68
|
}
|
package/dist/factories.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"factories.js","sources":["../src/factories.ts"],"sourcesContent":["import { pipe, omit, pick } from 'lodash/fp';\nimport type { Core, UID, Utils } from '@strapi/types';\n\nimport { createController } from './core-api/controller';\nimport { createService } from './core-api/service';\nimport { createRoutes } from './core-api/routes';\n\nconst symbols = {\n CustomController: Symbol('StrapiCustomCoreController'),\n} as const;\n\ntype WithStrapiCallback<T> = T | (<S extends { strapi: Core.Strapi }>(params: S) => T);\n\nconst createCoreController = <\n TUID extends UID.ContentType,\n TController extends Core.CoreAPI.Controller.Extendable<TUID>,\n>(\n uid: TUID,\n cfg?: WithStrapiCallback<\n Utils.PartialWithThis<Core.CoreAPI.Controller.Extendable<TUID> & TController>\n >\n) => {\n return ({\n strapi,\n }: {\n strapi: Core.Strapi;\n }): TController & Core.CoreAPI.Controller.ContentType<TUID> => {\n const baseController = createController({ contentType: strapi.contentType(uid) });\n\n const userCtrl = typeof cfg === 'function' ? cfg({ strapi }) : cfg ?? ({} as any);\n\n for (const methodName of Object.keys(baseController) as Array<keyof typeof baseController>) {\n if (userCtrl[methodName] === undefined) {\n userCtrl[methodName] = baseController[methodName];\n }\n }\n\n Object.setPrototypeOf(userCtrl, baseController);\n\n const isCustom = typeof cfg !== 'undefined';\n if (isCustom) {\n Object.defineProperty(userCtrl, symbols.CustomController, {\n writable: false,\n configurable: false,\n enumerable: false,\n });\n }\n\n return userCtrl;\n };\n};\n\nfunction createCoreService<\n TUID extends UID.ContentType,\n TService extends Core.CoreAPI.Service.Extendable<TUID>,\n>(\n uid: TUID,\n cfg?: WithStrapiCallback<Utils.PartialWithThis<Core.CoreAPI.Service.Extendable<TUID> & TService>>\n) {\n return ({\n strapi,\n }: {\n strapi: Core.Strapi;\n }): TService & Core.CoreAPI.Service.ContentType<TUID> => {\n const baseService = createService({ contentType: strapi.contentType(uid) });\n\n const userService = typeof cfg === 'function' ? cfg({ strapi }) : cfg ?? ({} as any);\n\n for (const methodName of Object.keys(baseService) as Array<keyof typeof baseService>) {\n if (userService[methodName] === undefined) {\n userService[methodName] = baseService[methodName];\n }\n }\n\n Object.setPrototypeOf(userService, baseService);\n return userService;\n };\n}\n\nfunction createCoreRouter<T extends UID.ContentType>(\n uid: T,\n cfg?: Core.CoreAPI.Router.RouterConfig<T>\n): Core.CoreAPI.Router.Router {\n const { prefix, config = {}, only, except, type = 'content-api' } = cfg ?? {};\n let routes: Core.CoreAPI.Router.Route[];\n\n return {\n type,\n prefix,\n get routes() {\n if (!routes) {\n const contentType = strapi.contentType(uid);\n\n const defaultRoutes = createRoutes({ contentType });\n const keys = Object.keys(defaultRoutes) as Array<keyof typeof defaultRoutes>;\n\n keys.forEach((routeName) => {\n const defaultRoute = defaultRoutes[routeName];\n\n Object.assign(defaultRoute.config, config[routeName] || {});\n });\n\n const selectedRoutes = pipe(\n (routes) => (except ? omit(except, routes) : routes),\n (routes) => (only ? pick(only, routes) : routes)\n )(defaultRoutes);\n\n routes = Object.values(selectedRoutes);\n }\n\n return routes;\n },\n };\n}\n\nconst isCustomController = <T extends Core.Controller>(controller: T): boolean => {\n return symbols.CustomController in controller;\n};\n\nexport { createCoreController, createCoreService, createCoreRouter, isCustomController };\n"],"names":["strapi","createController","createService","createRoutes","pipe","routes","omit","pick"],"mappings":";;;;;;AAOA,MAAM,UAAU;AAAA,EACd,kBAAkB,OAAO,4BAA4B;AACvD;AAIM,MAAA,uBAAuB,CAI3B,KACA,QAGG;AACH,SAAO,CAAC;AAAA,IACN,QAAAA;AAAAA,EAAA,MAG6D;AACvD,UAAA,iBAAiBC,uBAAiB,EAAE,aAAaD,QAAO,YAAY,GAAG,GAAG;AAE1E,UAAA,WAAW,OAAO,QAAQ,aAAa,IAAI,EAAE,QAAAA,QAAQ,CAAA,IAAI,OAAQ;AAEvE,eAAW,cAAc,OAAO,KAAK,cAAc,GAAyC;AACtF,UAAA,SAAS,UAAU,MAAM,QAAW;AAC7B,iBAAA,UAAU,IAAI,eAAe,UAAU;AAAA,MAClD;AAAA,IACF;AAEO,WAAA,eAAe,UAAU,cAAc;AAExC,UAAA,WAAW,OAAO,QAAQ;AAChC,QAAI,UAAU;AACL,aAAA,eAAe,UAAU,QAAQ,kBAAkB;AAAA,QACxD,UAAU;AAAA,QACV,cAAc;AAAA,QACd,YAAY;AAAA,MAAA,CACb;AAAA,IACH;AAEO,WAAA;AAAA,EAAA;AAEX;AAEA,SAAS,kBAIP,KACA,KACA;AACA,SAAO,CAAC;AAAA,IACN,QAAAA;AAAAA,EAAA,MAGuD;AACjD,UAAA,cAAcE,sBAAc,EAAE,aAAaF,QAAO,YAAY,GAAG,GAAG;AAEpE,UAAA,cAAc,OAAO,QAAQ,aAAa,IAAI,EAAE,QAAAA,QAAQ,CAAA,IAAI,OAAQ;AAE1E,eAAW,cAAc,OAAO,KAAK,WAAW,GAAsC;AAChF,UAAA,YAAY,UAAU,MAAM,QAAW;AAC7B,oBAAA,UAAU,IAAI,YAAY,UAAU;AAAA,MAClD;AAAA,IACF;AAEO,WAAA,eAAe,aAAa,WAAW;AACvC,WAAA;AAAA,EAAA;AAEX;AAEA,SAAS,iBACP,KACA,KAC4B;AACtB,QAAA,EAAE,QAAQ,SAAS,CAAA,GAAI,MAAM,QAAQ,OAAO,cAAA,IAAkB,OAAO;AACvE,MAAA;AAEG,SAAA;AAAA,IACL;AAAA,IACA;AAAA,IACA,IAAI,SAAS;AACX,UAAI,CAAC,QAAQ;AACL,cAAA,cAAc,OAAO,YAAY,GAAG;AAE1C,cAAM,gBAAgBG,QAAAA,aAAa,EAAE,YAAa,CAAA;AAC5C,cAAA,OAAO,OAAO,KAAK,aAAa;AAEjC,aAAA,QAAQ,CAAC,cAAc;AACpB,gBAAA,eAAe,cAAc,SAAS;AAE5C,iBAAO,OAAO,aAAa,QAAQ,OAAO,SAAS,KAAK,CAAA,CAAE;AAAA,QAAA,CAC3D;AAED,cAAM,iBAAiBC,
|
1
|
+
{"version":3,"file":"factories.js","sources":["../src/factories.ts"],"sourcesContent":["import { pipe, omit, pick } from 'lodash/fp';\nimport type { Core, UID, Utils } from '@strapi/types';\n\nimport { createController } from './core-api/controller';\nimport { createService } from './core-api/service';\nimport { createRoutes } from './core-api/routes';\n\nconst symbols = {\n CustomController: Symbol('StrapiCustomCoreController'),\n} as const;\n\ntype WithStrapiCallback<T> = T | (<S extends { strapi: Core.Strapi }>(params: S) => T);\n\nconst createCoreController = <\n TUID extends UID.ContentType,\n TController extends Core.CoreAPI.Controller.Extendable<TUID>,\n>(\n uid: TUID,\n cfg?: WithStrapiCallback<\n Utils.PartialWithThis<Core.CoreAPI.Controller.Extendable<TUID> & TController>\n >\n) => {\n return ({\n strapi,\n }: {\n strapi: Core.Strapi;\n }): TController & Core.CoreAPI.Controller.ContentType<TUID> => {\n const baseController = createController({ contentType: strapi.contentType(uid) });\n\n const userCtrl = typeof cfg === 'function' ? cfg({ strapi }) : cfg ?? ({} as any);\n\n for (const methodName of Object.keys(baseController) as Array<keyof typeof baseController>) {\n if (userCtrl[methodName] === undefined) {\n userCtrl[methodName] = baseController[methodName];\n }\n }\n\n Object.setPrototypeOf(userCtrl, baseController);\n\n const isCustom = typeof cfg !== 'undefined';\n if (isCustom) {\n Object.defineProperty(userCtrl, symbols.CustomController, {\n writable: false,\n configurable: false,\n enumerable: false,\n });\n }\n\n return userCtrl;\n };\n};\n\nfunction createCoreService<\n TUID extends UID.ContentType,\n TService extends Core.CoreAPI.Service.Extendable<TUID>,\n>(\n uid: TUID,\n cfg?: WithStrapiCallback<Utils.PartialWithThis<Core.CoreAPI.Service.Extendable<TUID> & TService>>\n) {\n return ({\n strapi,\n }: {\n strapi: Core.Strapi;\n }): TService & Core.CoreAPI.Service.ContentType<TUID> => {\n const baseService = createService({ contentType: strapi.contentType(uid) });\n\n const userService = typeof cfg === 'function' ? cfg({ strapi }) : cfg ?? ({} as any);\n\n for (const methodName of Object.keys(baseService) as Array<keyof typeof baseService>) {\n if (userService[methodName] === undefined) {\n userService[methodName] = baseService[methodName];\n }\n }\n\n Object.setPrototypeOf(userService, baseService);\n return userService;\n };\n}\n\nfunction createCoreRouter<T extends UID.ContentType>(\n uid: T,\n cfg?: Core.CoreAPI.Router.RouterConfig<T>\n): Core.CoreAPI.Router.Router {\n const { prefix, config = {}, only, except, type = 'content-api' } = cfg ?? {};\n let routes: Core.CoreAPI.Router.Route[];\n\n return {\n type,\n prefix,\n get routes() {\n if (!routes) {\n const contentType = strapi.contentType(uid);\n\n const defaultRoutes = createRoutes({ contentType });\n const keys = Object.keys(defaultRoutes) as Array<keyof typeof defaultRoutes>;\n\n keys.forEach((routeName) => {\n const defaultRoute = defaultRoutes[routeName];\n\n Object.assign(defaultRoute.config, config[routeName] || {});\n });\n\n const selectedRoutes = pipe(\n (routes) => (except ? omit(except, routes) : routes),\n (routes) => (only ? pick(only, routes) : routes)\n )(defaultRoutes);\n\n routes = Object.values(selectedRoutes);\n }\n\n return routes;\n },\n };\n}\n\nconst isCustomController = <T extends Core.Controller>(controller: T): boolean => {\n return symbols.CustomController in controller;\n};\n\nexport { createCoreController, createCoreService, createCoreRouter, isCustomController };\n"],"names":["strapi","createController","createService","createRoutes","pipe","routes","omit","pick"],"mappings":";;;;;;AAOA,MAAM,UAAU;AAAA,EACd,kBAAkB,OAAO,4BAA4B;AACvD;AAIM,MAAA,uBAAuB,CAI3B,KACA,QAGG;AACH,SAAO,CAAC;AAAA,IACN,QAAAA;AAAAA,EAAA,MAG6D;AACvD,UAAA,iBAAiBC,uBAAiB,EAAE,aAAaD,QAAO,YAAY,GAAG,GAAG;AAE1E,UAAA,WAAW,OAAO,QAAQ,aAAa,IAAI,EAAE,QAAAA,QAAQ,CAAA,IAAI,OAAQ;AAEvE,eAAW,cAAc,OAAO,KAAK,cAAc,GAAyC;AACtF,UAAA,SAAS,UAAU,MAAM,QAAW;AAC7B,iBAAA,UAAU,IAAI,eAAe,UAAU;AAAA,MAClD;AAAA,IACF;AAEO,WAAA,eAAe,UAAU,cAAc;AAExC,UAAA,WAAW,OAAO,QAAQ;AAChC,QAAI,UAAU;AACL,aAAA,eAAe,UAAU,QAAQ,kBAAkB;AAAA,QACxD,UAAU;AAAA,QACV,cAAc;AAAA,QACd,YAAY;AAAA,MAAA,CACb;AAAA,IACH;AAEO,WAAA;AAAA,EAAA;AAEX;AAEA,SAAS,kBAIP,KACA,KACA;AACA,SAAO,CAAC;AAAA,IACN,QAAAA;AAAAA,EAAA,MAGuD;AACjD,UAAA,cAAcE,sBAAc,EAAE,aAAaF,QAAO,YAAY,GAAG,GAAG;AAEpE,UAAA,cAAc,OAAO,QAAQ,aAAa,IAAI,EAAE,QAAAA,QAAQ,CAAA,IAAI,OAAQ;AAE1E,eAAW,cAAc,OAAO,KAAK,WAAW,GAAsC;AAChF,UAAA,YAAY,UAAU,MAAM,QAAW;AAC7B,oBAAA,UAAU,IAAI,YAAY,UAAU;AAAA,MAClD;AAAA,IACF;AAEO,WAAA,eAAe,aAAa,WAAW;AACvC,WAAA;AAAA,EAAA;AAEX;AAEA,SAAS,iBACP,KACA,KAC4B;AACtB,QAAA,EAAE,QAAQ,SAAS,CAAA,GAAI,MAAM,QAAQ,OAAO,cAAA,IAAkB,OAAO;AACvE,MAAA;AAEG,SAAA;AAAA,IACL;AAAA,IACA;AAAA,IACA,IAAI,SAAS;AACX,UAAI,CAAC,QAAQ;AACL,cAAA,cAAc,OAAO,YAAY,GAAG;AAE1C,cAAM,gBAAgBG,QAAAA,aAAa,EAAE,YAAa,CAAA;AAC5C,cAAA,OAAO,OAAO,KAAK,aAAa;AAEjC,aAAA,QAAQ,CAAC,cAAc;AACpB,gBAAA,eAAe,cAAc,SAAS;AAE5C,iBAAO,OAAO,aAAa,QAAQ,OAAO,SAAS,KAAK,CAAA,CAAE;AAAA,QAAA,CAC3D;AAED,cAAM,iBAAiBC,GAAA;AAAA,UACrB,CAACC,YAAY,SAASC,GAAAA,KAAK,QAAQD,OAAM,IAAIA;AAAAA,UAC7C,CAACA,YAAY,OAAOE,GAAAA,KAAK,MAAMF,OAAM,IAAIA;AAAAA,UACzC,aAAa;AAEN,iBAAA,OAAO,OAAO,cAAc;AAAA,MACvC;AAEO,aAAA;AAAA,IACT;AAAA,EAAA;AAEJ;AAEM,MAAA,qBAAqB,CAA4B,eAA2B;AAChF,SAAO,QAAQ,oBAAoB;AACrC;;;;;"}
|
package/dist/loaders/apis.js
CHANGED
@@ -3,7 +3,7 @@ const path = require("path");
|
|
3
3
|
const fse = require("fs-extra");
|
4
4
|
const _ = require("lodash");
|
5
5
|
const strapiUtils = require("@strapi/utils");
|
6
|
-
const
|
6
|
+
const fp = require("lodash/fp");
|
7
7
|
const index = require("../domain/content-type/index.js");
|
8
8
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
9
9
|
const fse__default = /* @__PURE__ */ _interopDefault(fse);
|
@@ -91,7 +91,7 @@ const loadContentTypes = async (apiName, dir) => {
|
|
91
91
|
}
|
92
92
|
const contentTypeName = normalizeName(fd.name);
|
93
93
|
const loadedContentType = (await loadDir(path.join(dir, fd.name)))?.result;
|
94
|
-
if (
|
94
|
+
if (fp.isEmpty(loadedContentType) || fp.isEmpty(loadedContentType.schema)) {
|
95
95
|
throw new Error(`Could not load content type found at ${dir}`);
|
96
96
|
}
|
97
97
|
const contentType = {
|
package/dist/loaders/apis.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"apis.js","sources":["../../src/loaders/apis.ts"],"sourcesContent":["import { join, extname, basename } from 'path';\nimport fse, { existsSync } from 'fs-extra';\nimport _ from 'lodash';\nimport { strings, importDefault } from '@strapi/utils';\nimport { isEmpty } from 'lodash/fp';\nimport type { Core, Struct } from '@strapi/types';\nimport { getGlobalId, type ContentTypeDefinition } from '../domain/content-type';\n\ninterface API {\n bootstrap: () => void | Promise<void>;\n destroy: () => void | Promise<void>;\n register: () => void | Promise<void>;\n config: Record<string, unknown>;\n routes: Record<string, Core.Router>;\n controllers: Record<string, Core.Controller>;\n services: Record<string, Core.Service>;\n policies: Record<string, Core.Policy>;\n middlewares: Record<string, Core.Middleware>;\n contentTypes: Record<string, { schema: Struct.ContentTypeSchema }>;\n}\n\ninterface APIs {\n [key: string]: API;\n}\n\nconst DEFAULT_CONTENT_TYPE = {\n schema: {},\n actions: {},\n lifecycles: {},\n};\n\n// to handle names with numbers in it we first check if it is already in kebabCase\nconst normalizeName = (name: string) => (strings.isKebabCase(name) ? name : _.kebabCase(name));\n\nconst isDirectory = (fd: fse.Dirent) => fd.isDirectory();\nconst isDotFile = (fd: fse.Dirent) => fd.name.startsWith('.');\n\nexport default async function loadAPIs(strapi: Core.Strapi) {\n if (!existsSync(strapi.dirs.dist.api)) {\n return;\n }\n\n const apisFDs = await (await fse.readdir(strapi.dirs.dist.api, { withFileTypes: true }))\n .filter(isDirectory)\n .filter(_.negate(isDotFile));\n\n const apis: APIs = {};\n\n // only load folders\n for (const apiFD of apisFDs) {\n const apiName = normalizeName(apiFD.name);\n const api = await loadAPI(apiName, join(strapi.dirs.dist.api, apiFD.name));\n\n // @ts-expect-error TODO verify that it's a valid api, not missing bootstrap, register, and destroy\n apis[apiName] = api;\n }\n\n validateContentTypesUnicity(apis);\n\n for (const apiName of Object.keys(apis)) {\n strapi.get('apis').add(apiName, apis[apiName]);\n }\n}\n\nconst validateContentTypesUnicity = (apis: APIs) => {\n const allApisSchemas = Object.values(apis).flatMap((api) => Object.values(api.contentTypes));\n\n const names: string[] = [];\n allApisSchemas.forEach(({ schema }) => {\n if (schema.info.singularName) {\n const singularName = _.kebabCase(schema.info.singularName);\n if (names.includes(singularName)) {\n throw new Error(`The singular name \"${schema.info.singularName}\" should be unique`);\n }\n names.push(singularName);\n }\n\n if (schema.info.pluralName) {\n const pluralName = _.kebabCase(schema.info.pluralName);\n if (names.includes(pluralName)) {\n throw new Error(`The plural name \"${schema.info.pluralName}\" should be unique`);\n }\n names.push(pluralName);\n }\n });\n};\n\nconst loadAPI = async (apiName: string, dir: string) => {\n const [index, config, routes, controllers, services, policies, middlewares, contentTypes] = (\n await Promise.all([\n loadIndex(dir),\n loadDir(join(dir, 'config')),\n loadDir(join(dir, 'routes')),\n loadDir(join(dir, 'controllers')),\n loadDir(join(dir, 'services')),\n loadDir(join(dir, 'policies')),\n loadDir(join(dir, 'middlewares')),\n loadContentTypes(apiName, join(dir, 'content-types')),\n ])\n ).map((result) => result?.result);\n\n return {\n ...(index || {}),\n config: config || {},\n routes: routes || [],\n controllers: controllers || {},\n services: services || {},\n policies: policies || {},\n middlewares: middlewares || {},\n contentTypes: contentTypes || {},\n };\n};\n\nconst loadIndex = async (dir: string) => {\n if (await fse.pathExists(join(dir, 'index.js'))) {\n return loadFile(join(dir, 'index.js'));\n }\n};\n\n// because this is async and its contents are dynamic, we must return it within an object to avoid a property called `then` being interpreted as a Promise\nconst loadContentTypes = async (apiName: string, dir: string) => {\n if (!(await fse.pathExists(dir))) {\n return;\n }\n\n const fds = await fse.readdir(dir, { withFileTypes: true });\n const contentTypes: API['contentTypes'] = {};\n\n // only load folders\n for (const fd of fds) {\n if (fd.isFile()) {\n continue;\n }\n\n const contentTypeName = normalizeName(fd.name);\n const loadedContentType = (await loadDir(join(dir, fd.name)))?.result;\n\n if (isEmpty(loadedContentType) || isEmpty(loadedContentType.schema)) {\n throw new Error(`Could not load content type found at ${dir}`);\n }\n\n const contentType = {\n ...DEFAULT_CONTENT_TYPE,\n ...loadedContentType,\n } as ContentTypeDefinition;\n\n Object.assign(contentType.schema, {\n apiName,\n collectionName: contentType.schema.collectionName || contentType.schema.info.singularName,\n globalId: getGlobalId(contentType.schema),\n });\n\n contentTypes[normalizeName(contentTypeName)] = contentType;\n }\n\n return { result: contentTypes };\n};\n\n// because this is async and its contents are dynamic, we must return it within an object to avoid a property called `then` being interpreted as a Promise\nconst loadDir = async (dir: string) => {\n if (!(await fse.pathExists(dir))) {\n return;\n }\n\n const fds = await fse.readdir(dir, { withFileTypes: true });\n\n const root: Record<string, unknown> = {};\n for (const fd of fds) {\n if (!fd.isFile() || extname(fd.name) === '.map') {\n continue;\n }\n\n const key = basename(fd.name, extname(fd.name));\n\n root[normalizeName(key)] = (await loadFile(join(dir, fd.name))).result;\n }\n\n return { result: root };\n};\n\n// because this is async and its contents are dynamic, we must return it as an array to avoid a property called `then` being interpreted as a Promise\nconst loadFile = async (file: string): Promise<{ result: unknown }> => {\n const ext = extname(file);\n\n switch (ext) {\n case '.js':\n return { result: importDefault(file) };\n case '.json':\n return { result: await fse.readJSON(file) };\n default:\n return { result: {} };\n }\n};\n"],"names":["strings","_","existsSync","fse","join","index","isEmpty","getGlobalId","extname","basename","importDefault"],"mappings":";;;;;;;;;;AAyBA,MAAM,uBAAuB;AAAA,EAC3B,QAAQ,CAAC;AAAA,EACT,SAAS,CAAC;AAAA,EACV,YAAY,CAAC;AACf;AAGA,MAAM,gBAAgB,CAAC,SAAkBA,YAAQ,QAAA,YAAY,IAAI,IAAI,OAAOC,WAAE,QAAA,UAAU,IAAI;AAE5F,MAAM,cAAc,CAAC,OAAmB,GAAG,YAAY;AACvD,MAAM,YAAY,CAAC,OAAmB,GAAG,K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,MAAM,WAAW,OAAO,SAA+C;AAC/D,QAAA,MAAMI,aAAQ,IAAI;AAExB,UAAQ,KAAK;AAAA,IACX,KAAK;AACH,aAAO,EAAE,QAAQE,0BAAc,IAAI,EAAE;AAAA,IACvC,KAAK;AACH,aAAO,EAAE,QAAQ,MAAMP,aAAAA,QAAI,SAAS,IAAI,EAAE;AAAA,IAC5C;AACS,aAAA,EAAE,QAAQ,CAAA;EACrB;AACF;;"}
|
1
|
+
{"version":3,"file":"apis.js","sources":["../../src/loaders/apis.ts"],"sourcesContent":["import { join, extname, basename } from 'path';\nimport fse, { existsSync } from 'fs-extra';\nimport _ from 'lodash';\nimport { strings, importDefault } from '@strapi/utils';\nimport { isEmpty } from 'lodash/fp';\nimport type { Core, Struct } from '@strapi/types';\nimport { getGlobalId, type ContentTypeDefinition } from '../domain/content-type';\n\ninterface API {\n bootstrap: () => void | Promise<void>;\n destroy: () => void | Promise<void>;\n register: () => void | Promise<void>;\n config: Record<string, unknown>;\n routes: Record<string, Core.Router>;\n controllers: Record<string, Core.Controller>;\n services: Record<string, Core.Service>;\n policies: Record<string, Core.Policy>;\n middlewares: Record<string, Core.Middleware>;\n contentTypes: Record<string, { schema: Struct.ContentTypeSchema }>;\n}\n\ninterface APIs {\n [key: string]: API;\n}\n\nconst DEFAULT_CONTENT_TYPE = {\n schema: {},\n actions: {},\n lifecycles: {},\n};\n\n// to handle names with numbers in it we first check if it is already in kebabCase\nconst normalizeName = (name: string) => (strings.isKebabCase(name) ? name : _.kebabCase(name));\n\nconst isDirectory = (fd: fse.Dirent) => fd.isDirectory();\nconst isDotFile = (fd: fse.Dirent) => fd.name.startsWith('.');\n\nexport default async function loadAPIs(strapi: Core.Strapi) {\n if (!existsSync(strapi.dirs.dist.api)) {\n return;\n }\n\n const apisFDs = await (await fse.readdir(strapi.dirs.dist.api, { withFileTypes: true }))\n .filter(isDirectory)\n .filter(_.negate(isDotFile));\n\n const apis: APIs = {};\n\n // only load folders\n for (const apiFD of apisFDs) {\n const apiName = normalizeName(apiFD.name);\n const api = await loadAPI(apiName, join(strapi.dirs.dist.api, apiFD.name));\n\n // @ts-expect-error TODO verify that it's a valid api, not missing bootstrap, register, and destroy\n apis[apiName] = api;\n }\n\n validateContentTypesUnicity(apis);\n\n for (const apiName of Object.keys(apis)) {\n strapi.get('apis').add(apiName, apis[apiName]);\n }\n}\n\nconst validateContentTypesUnicity = (apis: APIs) => {\n const allApisSchemas = Object.values(apis).flatMap((api) => Object.values(api.contentTypes));\n\n const names: string[] = [];\n allApisSchemas.forEach(({ schema }) => {\n if (schema.info.singularName) {\n const singularName = _.kebabCase(schema.info.singularName);\n if (names.includes(singularName)) {\n throw new Error(`The singular name \"${schema.info.singularName}\" should be unique`);\n }\n names.push(singularName);\n }\n\n if (schema.info.pluralName) {\n const pluralName = _.kebabCase(schema.info.pluralName);\n if (names.includes(pluralName)) {\n throw new Error(`The plural name \"${schema.info.pluralName}\" should be unique`);\n }\n names.push(pluralName);\n }\n });\n};\n\nconst loadAPI = async (apiName: string, dir: string) => {\n const [index, config, routes, controllers, services, policies, middlewares, contentTypes] = (\n await Promise.all([\n loadIndex(dir),\n loadDir(join(dir, 'config')),\n loadDir(join(dir, 'routes')),\n loadDir(join(dir, 'controllers')),\n loadDir(join(dir, 'services')),\n loadDir(join(dir, 'policies')),\n loadDir(join(dir, 'middlewares')),\n loadContentTypes(apiName, join(dir, 'content-types')),\n ])\n ).map((result) => result?.result);\n\n return {\n ...(index || {}),\n config: config || {},\n routes: routes || [],\n controllers: controllers || {},\n services: services || {},\n policies: policies || {},\n middlewares: middlewares || {},\n contentTypes: contentTypes || {},\n };\n};\n\nconst loadIndex = async (dir: string) => {\n if (await fse.pathExists(join(dir, 'index.js'))) {\n return loadFile(join(dir, 'index.js'));\n }\n};\n\n// because this is async and its contents are dynamic, we must return it within an object to avoid a property called `then` being interpreted as a Promise\nconst loadContentTypes = async (apiName: string, dir: string) => {\n if (!(await fse.pathExists(dir))) {\n return;\n }\n\n const fds = await fse.readdir(dir, { withFileTypes: true });\n const contentTypes: API['contentTypes'] = {};\n\n // only load folders\n for (const fd of fds) {\n if (fd.isFile()) {\n continue;\n }\n\n const contentTypeName = normalizeName(fd.name);\n const loadedContentType = (await loadDir(join(dir, fd.name)))?.result;\n\n if (isEmpty(loadedContentType) || isEmpty(loadedContentType.schema)) {\n throw new Error(`Could not load content type found at ${dir}`);\n }\n\n const contentType = {\n ...DEFAULT_CONTENT_TYPE,\n ...loadedContentType,\n } as ContentTypeDefinition;\n\n Object.assign(contentType.schema, {\n apiName,\n collectionName: contentType.schema.collectionName || contentType.schema.info.singularName,\n globalId: getGlobalId(contentType.schema),\n });\n\n contentTypes[normalizeName(contentTypeName)] = contentType;\n }\n\n return { result: contentTypes };\n};\n\n// because this is async and its contents are dynamic, we must return it within an object to avoid a property called `then` being interpreted as a Promise\nconst loadDir = async (dir: string) => {\n if (!(await fse.pathExists(dir))) {\n return;\n }\n\n const fds = await fse.readdir(dir, { withFileTypes: true });\n\n const root: Record<string, unknown> = {};\n for (const fd of fds) {\n if (!fd.isFile() || extname(fd.name) === '.map') {\n continue;\n }\n\n const key = basename(fd.name, extname(fd.name));\n\n root[normalizeName(key)] = (await loadFile(join(dir, fd.name))).result;\n }\n\n return { result: root };\n};\n\n// because this is async and its contents are dynamic, we must return it as an array to avoid a property called `then` being interpreted as a Promise\nconst loadFile = async (file: string): Promise<{ result: unknown }> => {\n const ext = extname(file);\n\n switch (ext) {\n case '.js':\n return { result: importDefault(file) };\n case '.json':\n return { result: await fse.readJSON(file) };\n default:\n return { result: {} };\n }\n};\n"],"names":["strings","_","existsSync","fse","join","index","isEmpty","getGlobalId","extname","basename","importDefault"],"mappings":";;;;;;;;;;AAyBA,MAAM,uBAAuB;AAAA,EAC3B,QAAQ,CAAC;AAAA,EACT,SAAS,CAAC;AAAA,EACV,YAAY,CAAC;AACf;AAGA,MAAM,gBAAgB,CAAC,SAAkBA,YAAQ,QAAA,YAAY,IAAI,IAAI,OAAOC,WAA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MAAM,SAASJ,KAAA,KAAK,KAAK,GAAG,IAAI,CAAC,GAAG;AAAA,EAClE;AAEO,SAAA,EAAE,QAAQ;AACnB;AAGA,MAAM,WAAW,OAAO,SAA+C;AAC/D,QAAA,MAAMI,aAAQ,IAAI;AAExB,UAAQ,KAAK;AAAA,IACX,KAAK;AACH,aAAO,EAAE,QAAQE,0BAAc,IAAI,EAAE;AAAA,IACvC,KAAK;AACH,aAAO,EAAE,QAAQ,MAAMP,aAAAA,QAAI,SAAS,IAAI,EAAE;AAAA,IAC5C;AACS,aAAA,EAAE,QAAQ,CAAA;EACrB;AACF;;"}
|
@@ -3,7 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const path = require("path");
|
4
4
|
const fs = require("fs");
|
5
5
|
const _ = require("lodash");
|
6
|
-
const
|
6
|
+
const fp = require("lodash/fp");
|
7
7
|
const strapiUtils = require("@strapi/utils");
|
8
8
|
const getUserPluginsConfig = require("./get-user-plugins-config.js");
|
9
9
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
@@ -17,7 +17,7 @@ const INTERNAL_PLUGINS = [
|
|
17
17
|
"@strapi/content-releases",
|
18
18
|
"@strapi/review-workflows"
|
19
19
|
];
|
20
|
-
const isStrapiPlugin = (info) =>
|
20
|
+
const isStrapiPlugin = (info) => fp.get("strapi.kind", info) === "plugin";
|
21
21
|
const validatePluginName = (pluginName) => {
|
22
22
|
if (!strapiUtils.strings.isKebabCase(pluginName)) {
|
23
23
|
throw new Error(`Plugin name "${pluginName}" is not in kebab (an-example-of-kebab-case)`);
|
@@ -97,15 +97,15 @@ const getEnabledPlugins = async (strapi2, { client } = { client: false }) => {
|
|
97
97
|
}
|
98
98
|
}
|
99
99
|
});
|
100
|
-
const declaredPluginsResolves =
|
101
|
-
const installedPluginsNotAlreadyUsed =
|
100
|
+
const declaredPluginsResolves = fp.map(fp.prop("pathToPlugin"), declaredPlugins);
|
101
|
+
const installedPluginsNotAlreadyUsed = fp.pickBy(
|
102
102
|
(p) => !declaredPluginsResolves.includes(p.pathToPlugin),
|
103
103
|
installedPlugins
|
104
104
|
);
|
105
|
-
const enabledPlugins =
|
106
|
-
|
107
|
-
|
108
|
-
|
105
|
+
const enabledPlugins = fp.pipe(
|
106
|
+
fp.defaultsDeep(declaredPlugins),
|
107
|
+
fp.defaultsDeep(installedPluginsNotAlreadyUsed),
|
108
|
+
fp.pickBy((p) => p.enabled)
|
109
109
|
)(internalPlugins);
|
110
110
|
return enabledPlugins;
|
111
111
|
};
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"get-enabled-plugins.js","sources":["../../../src/loaders/plugins/get-enabled-plugins.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-var-requires */\nimport { dirname, join, resolve } from 'path';\nimport { statSync, existsSync } from 'fs';\nimport _ from 'lodash';\nimport { get, pickBy, defaultsDeep, map, prop, pipe } from 'lodash/fp';\nimport { strings } from '@strapi/utils';\nimport type { Core } from '@strapi/types';\nimport { getUserPluginsConfig } from './get-user-plugins-config';\n\ninterface PluginMeta {\n enabled: boolean;\n pathToPlugin?: string;\n info: Record<string, unknown>;\n}\n\ntype PluginMetas = Record<string, PluginMeta>;\n\ninterface PluginInfo {\n name: string;\n kind: string;\n}\n\ninterface PluginDeclaration {\n enabled: boolean;\n resolve: string;\n isModule: boolean;\n}\n\n/**\n * otherwise known as \"core features\"\n *\n * NOTE: These are excluded from the content manager plugin list, as they are always enabled.\n * See admin.ts server controller on the content-manager plugin for more details.\n */\nconst INTERNAL_PLUGINS = [\n '@strapi/content-manager',\n '@strapi/content-type-builder',\n '@strapi/email',\n '@strapi/upload',\n '@strapi/i18n',\n '@strapi/content-releases',\n '@strapi/review-workflows',\n];\n\nconst isStrapiPlugin = (info: PluginInfo) => get('strapi.kind', info) === 'plugin';\n\nconst validatePluginName = (pluginName: string) => {\n if (!strings.isKebabCase(pluginName)) {\n throw new Error(`Plugin name \"${pluginName}\" is not in kebab (an-example-of-kebab-case)`);\n }\n};\n\nconst toDetailedDeclaration = (declaration: boolean | PluginDeclaration) => {\n if (typeof declaration === 'boolean') {\n return { enabled: declaration };\n }\n\n const detailedDeclaration: { enabled: boolean; pathToPlugin?: string } = {\n enabled: declaration.enabled,\n };\n\n if (declaration?.resolve) {\n let pathToPlugin = '';\n\n if (declaration.isModule) {\n /**\n * we only want the node_module here, not the package.json\n */\n pathToPlugin = join(declaration.resolve, '..');\n } else {\n try {\n pathToPlugin = dirname(require.resolve(declaration.resolve));\n } catch (e) {\n pathToPlugin = resolve(strapi.dirs.app.root, declaration.resolve);\n\n if (!existsSync(pathToPlugin) || !statSync(pathToPlugin).isDirectory()) {\n throw new Error(`${declaration.resolve} couldn't be resolved`);\n }\n }\n }\n\n detailedDeclaration.pathToPlugin = pathToPlugin;\n }\n\n return detailedDeclaration;\n};\n\nexport const getEnabledPlugins = async (strapi: Core.Strapi, { client } = { client: false }) => {\n const internalPlugins: PluginMetas = {};\n\n for (const dep of INTERNAL_PLUGINS) {\n const packagePath = join(dep, 'package.json');\n const packageInfo = require(packagePath);\n\n validatePluginName(packageInfo.strapi.name);\n internalPlugins[packageInfo.strapi.name] = {\n ...toDetailedDeclaration({ enabled: true, resolve: packagePath, isModule: client }),\n info: packageInfo.strapi,\n };\n }\n\n const installedPlugins: PluginMetas = {};\n const dependencies = strapi.config.get('info.dependencies', {});\n\n for (const dep of Object.keys(dependencies)) {\n const packagePath = join(dep, 'package.json');\n let packageInfo;\n try {\n packageInfo = require(packagePath);\n } catch {\n continue;\n }\n\n if (isStrapiPlugin(packageInfo)) {\n validatePluginName(packageInfo.strapi.name);\n installedPlugins[packageInfo.strapi.name] = {\n ...toDetailedDeclaration({ enabled: true, resolve: packagePath, isModule: client }),\n info: {\n ...packageInfo.strapi,\n packageName: packageInfo.name,\n },\n };\n }\n }\n\n const declaredPlugins: PluginMetas = {};\n const userPluginsConfig = await getUserPluginsConfig();\n\n _.forEach(userPluginsConfig, (declaration, pluginName) => {\n validatePluginName(pluginName);\n\n declaredPlugins[pluginName] = {\n ...toDetailedDeclaration(declaration),\n info: {},\n };\n\n const { pathToPlugin } = declaredPlugins[pluginName];\n\n // for manually resolved plugins\n if (pathToPlugin) {\n const packagePath = join(pathToPlugin, 'package.json');\n const packageInfo = require(packagePath);\n\n if (isStrapiPlugin(packageInfo)) {\n declaredPlugins[pluginName].info = packageInfo.strapi || {};\n }\n }\n });\n\n const declaredPluginsResolves = map(prop('pathToPlugin'), declaredPlugins);\n const installedPluginsNotAlreadyUsed = pickBy(\n (p) => !declaredPluginsResolves.includes(p.pathToPlugin),\n installedPlugins\n );\n\n const enabledPlugins = pipe(\n defaultsDeep(declaredPlugins),\n defaultsDeep(installedPluginsNotAlreadyUsed),\n pickBy((p: PluginMeta) => p.enabled)\n )(internalPlugins);\n\n return enabledPlugins;\n};\n"],"names":["get","strings","join","dirname","resolve","existsSync","statSync","strapi","getUserPluginsConfig","_","map","prop","pickBy","pipe","defaultsDeep"],"mappings":";;;;;;;;;;AAkCA,MAAM,mBAAmB;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,iBAAiB,CAAC,SAAqBA,
|
1
|
+
{"version":3,"file":"get-enabled-plugins.js","sources":["../../../src/loaders/plugins/get-enabled-plugins.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-var-requires */\nimport { dirname, join, resolve } from 'path';\nimport { statSync, existsSync } from 'fs';\nimport _ from 'lodash';\nimport { get, pickBy, defaultsDeep, map, prop, pipe } from 'lodash/fp';\nimport { strings } from '@strapi/utils';\nimport type { Core } from '@strapi/types';\nimport { getUserPluginsConfig } from './get-user-plugins-config';\n\ninterface PluginMeta {\n enabled: boolean;\n pathToPlugin?: string;\n info: Record<string, unknown>;\n}\n\ntype PluginMetas = Record<string, PluginMeta>;\n\ninterface PluginInfo {\n name: string;\n kind: string;\n}\n\ninterface PluginDeclaration {\n enabled: boolean;\n resolve: string;\n isModule: boolean;\n}\n\n/**\n * otherwise known as \"core features\"\n *\n * NOTE: These are excluded from the content manager plugin list, as they are always enabled.\n * See admin.ts server controller on the content-manager plugin for more details.\n */\nconst INTERNAL_PLUGINS = [\n '@strapi/content-manager',\n '@strapi/content-type-builder',\n '@strapi/email',\n '@strapi/upload',\n '@strapi/i18n',\n '@strapi/content-releases',\n '@strapi/review-workflows',\n];\n\nconst isStrapiPlugin = (info: PluginInfo) => get('strapi.kind', info) === 'plugin';\n\nconst validatePluginName = (pluginName: string) => {\n if (!strings.isKebabCase(pluginName)) {\n throw new Error(`Plugin name \"${pluginName}\" is not in kebab (an-example-of-kebab-case)`);\n }\n};\n\nconst toDetailedDeclaration = (declaration: boolean | PluginDeclaration) => {\n if (typeof declaration === 'boolean') {\n return { enabled: declaration };\n }\n\n const detailedDeclaration: { enabled: boolean; pathToPlugin?: string } = {\n enabled: declaration.enabled,\n };\n\n if (declaration?.resolve) {\n let pathToPlugin = '';\n\n if (declaration.isModule) {\n /**\n * we only want the node_module here, not the package.json\n */\n pathToPlugin = join(declaration.resolve, '..');\n } else {\n try {\n pathToPlugin = dirname(require.resolve(declaration.resolve));\n } catch (e) {\n pathToPlugin = resolve(strapi.dirs.app.root, declaration.resolve);\n\n if (!existsSync(pathToPlugin) || !statSync(pathToPlugin).isDirectory()) {\n throw new Error(`${declaration.resolve} couldn't be resolved`);\n }\n }\n }\n\n detailedDeclaration.pathToPlugin = pathToPlugin;\n }\n\n return detailedDeclaration;\n};\n\nexport const getEnabledPlugins = async (strapi: Core.Strapi, { client } = { client: false }) => {\n const internalPlugins: PluginMetas = {};\n\n for (const dep of INTERNAL_PLUGINS) {\n const packagePath = join(dep, 'package.json');\n const packageInfo = require(packagePath);\n\n validatePluginName(packageInfo.strapi.name);\n internalPlugins[packageInfo.strapi.name] = {\n ...toDetailedDeclaration({ enabled: true, resolve: packagePath, isModule: client }),\n info: packageInfo.strapi,\n };\n }\n\n const installedPlugins: PluginMetas = {};\n const dependencies = strapi.config.get('info.dependencies', {});\n\n for (const dep of Object.keys(dependencies)) {\n const packagePath = join(dep, 'package.json');\n let packageInfo;\n try {\n packageInfo = require(packagePath);\n } catch {\n continue;\n }\n\n if (isStrapiPlugin(packageInfo)) {\n validatePluginName(packageInfo.strapi.name);\n installedPlugins[packageInfo.strapi.name] = {\n ...toDetailedDeclaration({ enabled: true, resolve: packagePath, isModule: client }),\n info: {\n ...packageInfo.strapi,\n packageName: packageInfo.name,\n },\n };\n }\n }\n\n const declaredPlugins: PluginMetas = {};\n const userPluginsConfig = await getUserPluginsConfig();\n\n _.forEach(userPluginsConfig, (declaration, pluginName) => {\n validatePluginName(pluginName);\n\n declaredPlugins[pluginName] = {\n ...toDetailedDeclaration(declaration),\n info: {},\n };\n\n const { pathToPlugin } = declaredPlugins[pluginName];\n\n // for manually resolved plugins\n if (pathToPlugin) {\n const packagePath = join(pathToPlugin, 'package.json');\n const packageInfo = require(packagePath);\n\n if (isStrapiPlugin(packageInfo)) {\n declaredPlugins[pluginName].info = packageInfo.strapi || {};\n }\n }\n });\n\n const declaredPluginsResolves = map(prop('pathToPlugin'), declaredPlugins);\n const installedPluginsNotAlreadyUsed = pickBy(\n (p) => !declaredPluginsResolves.includes(p.pathToPlugin),\n installedPlugins\n );\n\n const enabledPlugins = pipe(\n defaultsDeep(declaredPlugins),\n defaultsDeep(installedPluginsNotAlreadyUsed),\n pickBy((p: PluginMeta) => p.enabled)\n )(internalPlugins);\n\n return enabledPlugins;\n};\n"],"names":["get","strings","join","dirname","resolve","existsSync","statSync","strapi","getUserPluginsConfig","_","map","prop","pickBy","pipe","defaultsDeep"],"mappings":";;;;;;;;;;AAkCA,MAAM,mBAAmB;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,iBAAiB,CAAC,SAAqBA,GAAAA,IAAI,eAAe,IAAI,MAAM;AAE1E,MAAM,qBAAqB,CAAC,eAAuB;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AA8B;AAAA,IAC3CF,GAAAA,OAAO,CAAC,MAAkB,EAAE,OAAO;AAAA,IACnC,eAAe;AAEV,SAAA;AACT;;"}
|
@@ -2,7 +2,7 @@
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
3
|
const path = require("path");
|
4
4
|
const fse = require("fs-extra");
|
5
|
-
const
|
5
|
+
const fp = require("lodash/fp");
|
6
6
|
const loadConfigFile = require("../../utils/load-config-file.js");
|
7
7
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
8
8
|
const fse__default = /* @__PURE__ */ _interopDefault(fse);
|
@@ -19,7 +19,7 @@ const getUserPluginsConfig = async () => {
|
|
19
19
|
config = loadConfigFile.loadConfigFile(globalUserConfigPath);
|
20
20
|
}
|
21
21
|
if (await fse__default.default.pathExists(currentEnvUserConfigPath)) {
|
22
|
-
config =
|
22
|
+
config = fp.merge(config, loadConfigFile.loadConfigFile(currentEnvUserConfigPath));
|
23
23
|
}
|
24
24
|
return config;
|
25
25
|
};
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"get-user-plugins-config.js","sources":["../../../src/loaders/plugins/get-user-plugins-config.ts"],"sourcesContent":["import { join } from 'path';\nimport fse from 'fs-extra';\nimport { merge } from 'lodash/fp';\nimport { loadConfigFile } from '../../utils/load-config-file';\n\n/**\n * Return user defined plugins' config\n * first load config from `config/plugins.js`\n * and then merge config from `config/env/{env}/plugins.js`\n */\nexport const getUserPluginsConfig = async () => {\n const globalUserConfigPath = join(strapi.dirs.dist.config, 'plugins.js');\n const currentEnvUserConfigPath = join(\n strapi.dirs.dist.config,\n 'env',\n process.env.NODE_ENV as string,\n 'plugins.js'\n );\n let config = {};\n\n // assign global user config if exists\n if (await fse.pathExists(globalUserConfigPath)) {\n config = loadConfigFile(globalUserConfigPath);\n }\n\n // and merge user config by environment if exists\n if (await fse.pathExists(currentEnvUserConfigPath)) {\n config = merge(config, loadConfigFile(currentEnvUserConfigPath));\n }\n\n return config;\n};\n"],"names":["join","fse","loadConfigFile","merge"],"mappings":";;;;;;;;AAUO,MAAM,uBAAuB,YAAY;AAC9C,QAAM,uBAAuBA,KAAAA,KAAK,OAAO,KAAK,KAAK,QAAQ,YAAY;AACvE,QAAM,2BAA2BA,KAAA;AAAA,IAC/B,OAAO,KAAK,KAAK;AAAA,IACjB;AAAA,IACA,QAAQ,IAAI;AAAA,IACZ;AAAA,EAAA;AAEF,MAAI,SAAS,CAAA;AAGb,MAAI,MAAMC,aAAA,QAAI,WAAW,oBAAoB,GAAG;AAC9C,aAASC,eAAAA,eAAe,oBAAoB;AAAA,EAC9C;AAGA,MAAI,MAAMD,aAAA,QAAI,WAAW,wBAAwB,GAAG;AAClD,aAASE,
|
1
|
+
{"version":3,"file":"get-user-plugins-config.js","sources":["../../../src/loaders/plugins/get-user-plugins-config.ts"],"sourcesContent":["import { join } from 'path';\nimport fse from 'fs-extra';\nimport { merge } from 'lodash/fp';\nimport { loadConfigFile } from '../../utils/load-config-file';\n\n/**\n * Return user defined plugins' config\n * first load config from `config/plugins.js`\n * and then merge config from `config/env/{env}/plugins.js`\n */\nexport const getUserPluginsConfig = async () => {\n const globalUserConfigPath = join(strapi.dirs.dist.config, 'plugins.js');\n const currentEnvUserConfigPath = join(\n strapi.dirs.dist.config,\n 'env',\n process.env.NODE_ENV as string,\n 'plugins.js'\n );\n let config = {};\n\n // assign global user config if exists\n if (await fse.pathExists(globalUserConfigPath)) {\n config = loadConfigFile(globalUserConfigPath);\n }\n\n // and merge user config by environment if exists\n if (await fse.pathExists(currentEnvUserConfigPath)) {\n config = merge(config, loadConfigFile(currentEnvUserConfigPath));\n }\n\n return config;\n};\n"],"names":["join","fse","loadConfigFile","merge"],"mappings":";;;;;;;;AAUO,MAAM,uBAAuB,YAAY;AAC9C,QAAM,uBAAuBA,KAAAA,KAAK,OAAO,KAAK,KAAK,QAAQ,YAAY;AACvE,QAAM,2BAA2BA,KAAA;AAAA,IAC/B,OAAO,KAAK,KAAK;AAAA,IACjB;AAAA,IACA,QAAQ,IAAI;AAAA,IACZ;AAAA,EAAA;AAEF,MAAI,SAAS,CAAA;AAGb,MAAI,MAAMC,aAAA,QAAI,WAAW,oBAAoB,GAAG;AAC9C,aAASC,eAAAA,eAAe,oBAAoB;AAAA,EAC9C;AAGA,MAAI,MAAMD,aAAA,QAAI,WAAW,wBAAwB,GAAG;AAClD,aAASE,GAAAA,MAAM,QAAQD,eAAAA,eAAe,wBAAwB,CAAC;AAAA,EACjE;AAEO,SAAA;AACT;;"}
|
@@ -1,7 +1,7 @@
|
|
1
1
|
"use strict";
|
2
2
|
const path = require("path");
|
3
3
|
const fse = require("fs-extra");
|
4
|
-
const
|
4
|
+
const fp = require("lodash/fp");
|
5
5
|
const strapiUtils = require("@strapi/utils");
|
6
6
|
const loadConfigFile = require("../../utils/load-config-file.js");
|
7
7
|
const loadFiles = require("../../utils/load-files.js");
|
@@ -39,7 +39,7 @@ const applyUserExtension = async (plugins) => {
|
|
39
39
|
for (const pluginName of Object.keys(plugins)) {
|
40
40
|
const plugin = plugins[pluginName];
|
41
41
|
for (const ctName of Object.keys(plugin.contentTypes)) {
|
42
|
-
const extendedSchema =
|
42
|
+
const extendedSchema = fp.get([pluginName, "content-types", ctName, "schema"], extendedSchemas);
|
43
43
|
if (extendedSchema) {
|
44
44
|
plugin.contentTypes[ctName].schema = {
|
45
45
|
...plugin.contentTypes[ctName].schema,
|
@@ -47,7 +47,7 @@ const applyUserExtension = async (plugins) => {
|
|
47
47
|
};
|
48
48
|
}
|
49
49
|
}
|
50
|
-
const strapiServer =
|
50
|
+
const strapiServer = fp.get([pluginName, "strapi-server"], strapiServers);
|
51
51
|
if (strapiServer) {
|
52
52
|
plugins[pluginName] = await strapiServer(plugin);
|
53
53
|
}
|
@@ -57,9 +57,9 @@ const applyUserConfig = async (plugins) => {
|
|
57
57
|
const userPluginsConfig = await getUserPluginsConfig.getUserPluginsConfig();
|
58
58
|
for (const pluginName of Object.keys(plugins)) {
|
59
59
|
const plugin = plugins[pluginName];
|
60
|
-
const userPluginConfig =
|
60
|
+
const userPluginConfig = fp.getOr({}, `${pluginName}.config`, userPluginsConfig);
|
61
61
|
const defaultConfig = typeof plugin.config.default === "function" ? plugin.config.default({ env: strapiUtils.env }) : plugin.config.default;
|
62
|
-
const config =
|
62
|
+
const config = fp.defaultsDeep(defaultConfig, userPluginConfig);
|
63
63
|
try {
|
64
64
|
plugin.config.validator(config);
|
65
65
|
} catch (e) {
|
@@ -93,7 +93,7 @@ async function loadPlugins(strapi2) {
|
|
93
93
|
...defaultPlugin,
|
94
94
|
...pluginServer,
|
95
95
|
contentTypes: formatContentTypes(pluginName, pluginServer.contentTypes ?? {}),
|
96
|
-
config:
|
96
|
+
config: fp.defaults(defaultPlugin.config, pluginServer.config),
|
97
97
|
routes: pluginServer.routes ?? defaultPlugin.routes
|
98
98
|
};
|
99
99
|
}
|