@strapi/core 5.0.0-rc.1 → 5.0.0-rc.11
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/LICENSE +18 -3
- package/dist/Strapi.js +2 -2
- package/dist/Strapi.js.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/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs.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.d.ts.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.js +34 -9
- package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.mjs +4 -1
- package/dist/loaders/plugins/get-enabled-plugins.mjs.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/cors.d.ts.map +1 -1
- package/dist/middlewares/cors.js +4 -0
- package/dist/middlewares/cors.js.map +1 -1
- package/dist/middlewares/cors.mjs +4 -0
- package/dist/middlewares/cors.mjs.map +1 -1
- package/dist/middlewares/public.js +2 -2
- package/dist/middlewares/public.js.map +1 -1
- package/dist/middlewares/query.js.map +1 -1
- package/dist/middlewares/query.mjs.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.d.ts +1 -1
- package/dist/registries/policies.d.ts.map +1 -1
- package/dist/registries/policies.js +5 -5
- package/dist/registries/policies.js.map +1 -1
- package/dist/registries/policies.mjs +1 -1
- package/dist/registries/policies.mjs.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/content-api/index.d.ts +6 -12
- package/dist/services/content-api/index.d.ts.map +1 -1
- package/dist/services/content-api/permissions/index.d.ts +6 -12
- package/dist/services/content-api/permissions/index.d.ts.map +1 -1
- package/dist/services/content-api/permissions/providers/action.d.ts +3 -6
- package/dist/services/content-api/permissions/providers/action.d.ts.map +1 -1
- package/dist/services/content-api/permissions/providers/condition.d.ts +3 -6
- package/dist/services/content-api/permissions/providers/condition.d.ts.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/entity-validator/blocks-validator.d.ts +1 -2
- package/dist/services/entity-validator/blocks-validator.d.ts.map +1 -1
- package/dist/services/entity-validator/blocks-validator.js +4 -3
- package/dist/services/entity-validator/blocks-validator.js.map +1 -1
- package/dist/services/entity-validator/blocks-validator.mjs +3 -3
- package/dist/services/entity-validator/blocks-validator.mjs.map +1 -1
- package/dist/services/entity-validator/index.d.ts +2 -1
- package/dist/services/entity-validator/index.d.ts.map +1 -1
- package/dist/services/entity-validator/index.js +28 -33
- package/dist/services/entity-validator/index.js.map +1 -1
- package/dist/services/entity-validator/index.mjs +14 -19
- package/dist/services/entity-validator/index.mjs.map +1 -1
- package/dist/services/entity-validator/validators.d.ts +32 -23
- package/dist/services/entity-validator/validators.d.ts.map +1 -1
- package/dist/services/entity-validator/validators.js +137 -63
- package/dist/services/entity-validator/validators.js.map +1 -1
- package/dist/services/entity-validator/validators.mjs +136 -63
- 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/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/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 +2 -2
- package/dist/utils/transform-content-types-to-models.d.ts.map +1 -1
- package/dist/utils/transform-content-types-to-models.js +6 -5
- package/dist/utils/transform-content-types-to-models.js.map +1 -1
- package/dist/utils/transform-content-types-to-models.mjs +5 -4
- package/dist/utils/transform-content-types-to-models.mjs.map +1 -1
- package/package.json +13 -13
package/dist/utils/cron.js
CHANGED
@@ -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 INTEGER_REGEX = /^\d+$/;
|
5
5
|
const STEP_REGEX = /^\*\/\d+$/;
|
6
6
|
const COMPONENTS = [
|
@@ -24,13 +24,13 @@ const shift = (component, index, date) => {
|
|
24
24
|
if (STEP_REGEX.test(component)) {
|
25
25
|
const [, step] = component.split("/");
|
26
26
|
const frequency = Math.floor(limit / Number(step));
|
27
|
-
const list = Array.from({ length: frequency }, (
|
27
|
+
const list = Array.from({ length: frequency }, (_, index2) => index2 * Number(step));
|
28
28
|
return list.map((value) => (value + currentValue) % limit + offset).sort((a, b) => a - b);
|
29
29
|
}
|
30
30
|
return component;
|
31
31
|
};
|
32
32
|
const shiftCronExpression = (rule, date = /* @__PURE__ */ new Date()) => {
|
33
|
-
const components = rule.trim().split(" ").filter(
|
33
|
+
const components = rule.trim().split(" ").filter(fp.negate(fp.isEmpty));
|
34
34
|
const secondsIncluded = components.length === 6;
|
35
35
|
return components.map((component, index) => shift(component, secondsIncluded ? index : index + 1, date)).join(" ");
|
36
36
|
};
|
package/dist/utils/cron.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"cron.js","sources":["../../src/utils/cron.ts"],"sourcesContent":["import { isEmpty, negate } from 'lodash/fp';\n\nconst DATE_FUNCTIONS = [\n 'getSeconds',\n 'getMinutes',\n 'getHours',\n 'getDate',\n 'getMonth',\n 'getDay',\n] as const;\n\nconst INTEGER_REGEX = /^\\d+$/;\nconst STEP_REGEX = /^\\*\\/\\d+$/;\nconst COMPONENTS: {\n limit: number;\n zeroBasedIndices: boolean;\n functionName: (typeof DATE_FUNCTIONS)[number];\n}[] = [\n { limit: 60, zeroBasedIndices: true, functionName: 'getSeconds' },\n { limit: 60, zeroBasedIndices: true, functionName: 'getMinutes' },\n { limit: 24, zeroBasedIndices: true, functionName: 'getHours' },\n { limit: 31, zeroBasedIndices: false, functionName: 'getDate' },\n { limit: 12, zeroBasedIndices: false, functionName: 'getMonth' },\n { limit: 7, zeroBasedIndices: true, functionName: 'getDay' },\n];\n\nconst shift = (component: string, index: number, date: Date) => {\n if (component === '*') {\n return '*';\n }\n\n const { limit, zeroBasedIndices, functionName } = COMPONENTS[index];\n const offset = +!zeroBasedIndices;\n const currentValue = date[functionName]();\n\n if (INTEGER_REGEX.test(component)) {\n return ((Number.parseInt(component, 10) + currentValue) % limit) + offset;\n }\n\n if (STEP_REGEX.test(component)) {\n const [, step] = component.split('/');\n const frequency = Math.floor(limit / Number(step));\n const list = Array.from({ length: frequency }, (_, index) => index * Number(step));\n return list.map((value) => ((value + currentValue) % limit) + offset).sort((a, b) => a - b);\n }\n\n // Unsupported syntax\n return component;\n};\n\n/**\n * Simulate an interval by shifting a cron expression using the specified date.\n * @param {string} rule A cron expression you want to shift.\n * @param {Date} date The date that's gonna be used as the start of the \"interval\", it defaults to now.\n * @returns The shifted cron expression.\n */\nexport const shiftCronExpression = (rule: string, date = new Date()) => {\n const components = rule.trim().split(' ').filter(negate(isEmpty));\n const secondsIncluded = components.length === 6;\n return components\n .map((component, index) => shift(component, secondsIncluded ? index : index + 1, date))\n .join(' ');\n};\n"],"names":["
|
1
|
+
{"version":3,"file":"cron.js","sources":["../../src/utils/cron.ts"],"sourcesContent":["import { isEmpty, negate } from 'lodash/fp';\n\nconst DATE_FUNCTIONS = [\n 'getSeconds',\n 'getMinutes',\n 'getHours',\n 'getDate',\n 'getMonth',\n 'getDay',\n] as const;\n\nconst INTEGER_REGEX = /^\\d+$/;\nconst STEP_REGEX = /^\\*\\/\\d+$/;\nconst COMPONENTS: {\n limit: number;\n zeroBasedIndices: boolean;\n functionName: (typeof DATE_FUNCTIONS)[number];\n}[] = [\n { limit: 60, zeroBasedIndices: true, functionName: 'getSeconds' },\n { limit: 60, zeroBasedIndices: true, functionName: 'getMinutes' },\n { limit: 24, zeroBasedIndices: true, functionName: 'getHours' },\n { limit: 31, zeroBasedIndices: false, functionName: 'getDate' },\n { limit: 12, zeroBasedIndices: false, functionName: 'getMonth' },\n { limit: 7, zeroBasedIndices: true, functionName: 'getDay' },\n];\n\nconst shift = (component: string, index: number, date: Date) => {\n if (component === '*') {\n return '*';\n }\n\n const { limit, zeroBasedIndices, functionName } = COMPONENTS[index];\n const offset = +!zeroBasedIndices;\n const currentValue = date[functionName]();\n\n if (INTEGER_REGEX.test(component)) {\n return ((Number.parseInt(component, 10) + currentValue) % limit) + offset;\n }\n\n if (STEP_REGEX.test(component)) {\n const [, step] = component.split('/');\n const frequency = Math.floor(limit / Number(step));\n const list = Array.from({ length: frequency }, (_, index) => index * Number(step));\n return list.map((value) => ((value + currentValue) % limit) + offset).sort((a, b) => a - b);\n }\n\n // Unsupported syntax\n return component;\n};\n\n/**\n * Simulate an interval by shifting a cron expression using the specified date.\n * @param {string} rule A cron expression you want to shift.\n * @param {Date} date The date that's gonna be used as the start of the \"interval\", it defaults to now.\n * @returns The shifted cron expression.\n */\nexport const shiftCronExpression = (rule: string, date = new Date()) => {\n const components = rule.trim().split(' ').filter(negate(isEmpty));\n const secondsIncluded = components.length === 6;\n return components\n .map((component, index) => shift(component, secondsIncluded ? index : index + 1, date))\n .join(' ');\n};\n"],"names":["index","negate","isEmpty"],"mappings":";;;AAWA,MAAM,gBAAgB;AACtB,MAAM,aAAa;AACnB,MAAM,aAIA;AAAA,EACJ,EAAE,OAAO,IAAI,kBAAk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,MAAM,WAAW,kBAAkB,QAAQ,QAAQ,GAAG,IAAI,CAAC,EACrF,KAAK,GAAG;AACb;;"}
|
@@ -1,5 +1,5 @@
|
|
1
1
|
/**
|
2
2
|
* Returns a path (as an array) from a file path
|
3
3
|
*/
|
4
|
-
export declare const filePathToPropPath: (
|
4
|
+
export declare const filePathToPropPath: (entryPath: string, useFileNameAsKey?: boolean) => string[];
|
5
5
|
//# sourceMappingURL=filepath-to-prop-path.d.ts.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"filepath-to-prop-path.d.ts","sourceRoot":"","sources":["../../src/utils/filepath-to-prop-path.ts"],"names":[],"mappings":"
|
1
|
+
{"version":3,"file":"filepath-to-prop-path.d.ts","sourceRoot":"","sources":["../../src/utils/filepath-to-prop-path.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,eAAO,MAAM,kBAAkB,cAClB,MAAM,qBACC,OAAO,KACxB,MAAM,EAqBR,CAAC"}
|
@@ -1,12 +1,33 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
|
-
const
|
3
|
+
const path = require("node:path");
|
4
|
+
const fp = require("lodash/fp");
|
4
5
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
5
|
-
const
|
6
|
-
const
|
7
|
-
|
8
|
-
const
|
9
|
-
|
6
|
+
const path__default = /* @__PURE__ */ _interopDefault(path);
|
7
|
+
const fp__default = /* @__PURE__ */ _interopDefault(fp);
|
8
|
+
const filePathToPropPath = (entryPath, useFileNameAsKey = true) => {
|
9
|
+
const transform = fp__default.default.pipe(
|
10
|
+
// Remove the relative path prefixes: './' for posix (and some win32) and ".\" for win32
|
11
|
+
removeRelativePrefix,
|
12
|
+
// Remove the path metadata and extensions
|
13
|
+
fp__default.default.replace(/(\.settings|\.json|\.js)/g, ""),
|
14
|
+
// Transform to lowercase
|
15
|
+
// Note: We're using fp.toLower instead of fp.lowercase as the latest removes special characters such as "/"
|
16
|
+
fp__default.default.toLower,
|
17
|
+
// Split the cleaned path by matching every possible separator (either "/" or "\" depending on the OS)
|
18
|
+
fp__default.default.split(new RegExp(`[\\${path__default.default.win32.sep}|${path__default.default.posix.sep}]`, "g")),
|
19
|
+
// Make sure to remove leading '.' from the different path parts
|
20
|
+
fp__default.default.map(fp__default.default.trimCharsStart(".")),
|
21
|
+
// join + split in case some '.' characters are still present in different parts of the path
|
22
|
+
fp__default.default.join("."),
|
23
|
+
fp__default.default.split("."),
|
24
|
+
// Remove the last portion of the path array if the file name shouldn't be used as a key
|
25
|
+
useFileNameAsKey ? fp__default.default.identity : fp__default.default.slice(0, -1)
|
26
|
+
);
|
27
|
+
return transform(entryPath);
|
28
|
+
};
|
29
|
+
const removeRelativePrefix = (filePath) => {
|
30
|
+
return filePath.startsWith(`.${path__default.default.win32.sep}`) || filePath.startsWith(`.${path__default.default.posix.sep}`) ? filePath.slice(2) : filePath;
|
10
31
|
};
|
11
32
|
exports.filePathToPropPath = filePathToPropPath;
|
12
33
|
//# sourceMappingURL=filepath-to-prop-path.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"filepath-to-prop-path.js","sources":["../../src/utils/filepath-to-prop-path.ts"],"sourcesContent":["import
|
1
|
+
{"version":3,"file":"filepath-to-prop-path.js","sources":["../../src/utils/filepath-to-prop-path.ts"],"sourcesContent":["import path from 'node:path';\nimport fp from 'lodash/fp';\n\n/**\n * Returns a path (as an array) from a file path\n */\nexport const filePathToPropPath = (\n entryPath: string,\n useFileNameAsKey: boolean = true\n): string[] => {\n const transform = fp.pipe(\n // Remove the relative path prefixes: './' for posix (and some win32) and \".\\\" for win32\n removeRelativePrefix,\n // Remove the path metadata and extensions\n fp.replace(/(\\.settings|\\.json|\\.js)/g, ''),\n // Transform to lowercase\n // Note: We're using fp.toLower instead of fp.lowercase as the latest removes special characters such as \"/\"\n fp.toLower,\n // Split the cleaned path by matching every possible separator (either \"/\" or \"\\\" depending on the OS)\n fp.split(new RegExp(`[\\\\${path.win32.sep}|${path.posix.sep}]`, 'g')),\n // Make sure to remove leading '.' from the different path parts\n fp.map(fp.trimCharsStart('.')),\n // join + split in case some '.' characters are still present in different parts of the path\n fp.join('.'),\n fp.split('.'),\n // Remove the last portion of the path array if the file name shouldn't be used as a key\n useFileNameAsKey ? fp.identity : fp.slice(0, -1)\n );\n\n return transform(entryPath) as string[];\n};\n\nconst removeRelativePrefix = (filePath: string) => {\n return filePath.startsWith(`.${path.win32.sep}`) || filePath.startsWith(`.${path.posix.sep}`)\n ? filePath.slice(2)\n : filePath;\n};\n"],"names":["fp","path"],"mappings":";;;;;;;AAMO,MAAM,qBAAqB,CAChC,WACA,mBAA4B,SACf;AACb,QAAM,YAAYA,YAAAA,QAAG;AAAA;AAAA,IAEnB;AAAA;AAAA,IAEAA,oBAAG,QAAQ,6BAA6B,EAAE;AAAA;AAAA;AAAA,IAG1CA,YAAAA,QAAG;AAAA;AAAA,IAEHA,YAAG,QAAA,MAAM,IAAI,OAAO,MAAMC,cAAK,QAAA,MAAM,GAAG,IAAIA,cAAK,QAAA,MAAM,GAAG,KAAK,GAAG,CAAC;AAAA;AAAA,IAEnED,YAAAA,QAAG,IAAIA,YAAAA,QAAG,eAAe,GAAG,CAAC;AAAA;AAAA,IAE7BA,YAAA,QAAG,KAAK,GAAG;AAAA,IACXA,YAAA,QAAG,MAAM,GAAG;AAAA;AAAA,IAEZ,mBAAmBA,YAAG,QAAA,WAAWA,YAAAA,QAAG,MAAM,GAAG,EAAE;AAAA,EAAA;AAGjD,SAAO,UAAU,SAAS;AAC5B;AAEA,MAAM,uBAAuB,CAAC,aAAqB;AACjD,SAAO,SAAS,WAAW,IAAIC,cAAAA,QAAK,MAAM,GAAG,EAAE,KAAK,SAAS,WAAW,IAAIA,cAAAA,QAAK,MAAM,GAAG,EAAE,IACxF,SAAS,MAAM,CAAC,IAChB;AACN;;"}
|
@@ -1,8 +1,28 @@
|
|
1
|
-
import
|
2
|
-
|
3
|
-
|
4
|
-
const
|
5
|
-
|
1
|
+
import path from "node:path";
|
2
|
+
import fp from "lodash/fp";
|
3
|
+
const filePathToPropPath = (entryPath, useFileNameAsKey = true) => {
|
4
|
+
const transform = fp.pipe(
|
5
|
+
// Remove the relative path prefixes: './' for posix (and some win32) and ".\" for win32
|
6
|
+
removeRelativePrefix,
|
7
|
+
// Remove the path metadata and extensions
|
8
|
+
fp.replace(/(\.settings|\.json|\.js)/g, ""),
|
9
|
+
// Transform to lowercase
|
10
|
+
// Note: We're using fp.toLower instead of fp.lowercase as the latest removes special characters such as "/"
|
11
|
+
fp.toLower,
|
12
|
+
// Split the cleaned path by matching every possible separator (either "/" or "\" depending on the OS)
|
13
|
+
fp.split(new RegExp(`[\\${path.win32.sep}|${path.posix.sep}]`, "g")),
|
14
|
+
// Make sure to remove leading '.' from the different path parts
|
15
|
+
fp.map(fp.trimCharsStart(".")),
|
16
|
+
// join + split in case some '.' characters are still present in different parts of the path
|
17
|
+
fp.join("."),
|
18
|
+
fp.split("."),
|
19
|
+
// Remove the last portion of the path array if the file name shouldn't be used as a key
|
20
|
+
useFileNameAsKey ? fp.identity : fp.slice(0, -1)
|
21
|
+
);
|
22
|
+
return transform(entryPath);
|
23
|
+
};
|
24
|
+
const removeRelativePrefix = (filePath) => {
|
25
|
+
return filePath.startsWith(`.${path.win32.sep}`) || filePath.startsWith(`.${path.posix.sep}`) ? filePath.slice(2) : filePath;
|
6
26
|
};
|
7
27
|
export {
|
8
28
|
filePathToPropPath
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"filepath-to-prop-path.mjs","sources":["../../src/utils/filepath-to-prop-path.ts"],"sourcesContent":["import
|
1
|
+
{"version":3,"file":"filepath-to-prop-path.mjs","sources":["../../src/utils/filepath-to-prop-path.ts"],"sourcesContent":["import path from 'node:path';\nimport fp from 'lodash/fp';\n\n/**\n * Returns a path (as an array) from a file path\n */\nexport const filePathToPropPath = (\n entryPath: string,\n useFileNameAsKey: boolean = true\n): string[] => {\n const transform = fp.pipe(\n // Remove the relative path prefixes: './' for posix (and some win32) and \".\\\" for win32\n removeRelativePrefix,\n // Remove the path metadata and extensions\n fp.replace(/(\\.settings|\\.json|\\.js)/g, ''),\n // Transform to lowercase\n // Note: We're using fp.toLower instead of fp.lowercase as the latest removes special characters such as \"/\"\n fp.toLower,\n // Split the cleaned path by matching every possible separator (either \"/\" or \"\\\" depending on the OS)\n fp.split(new RegExp(`[\\\\${path.win32.sep}|${path.posix.sep}]`, 'g')),\n // Make sure to remove leading '.' from the different path parts\n fp.map(fp.trimCharsStart('.')),\n // join + split in case some '.' characters are still present in different parts of the path\n fp.join('.'),\n fp.split('.'),\n // Remove the last portion of the path array if the file name shouldn't be used as a key\n useFileNameAsKey ? fp.identity : fp.slice(0, -1)\n );\n\n return transform(entryPath) as string[];\n};\n\nconst removeRelativePrefix = (filePath: string) => {\n return filePath.startsWith(`.${path.win32.sep}`) || filePath.startsWith(`.${path.posix.sep}`)\n ? filePath.slice(2)\n : filePath;\n};\n"],"names":[],"mappings":";;AAMO,MAAM,qBAAqB,CAChC,WACA,mBAA4B,SACf;AACb,QAAM,YAAY,GAAG;AAAA;AAAA,IAEnB;AAAA;AAAA,IAEA,GAAG,QAAQ,6BAA6B,EAAE;AAAA;AAAA;AAAA,IAG1C,GAAG;AAAA;AAAA,IAEH,GAAG,MAAM,IAAI,OAAO,MAAM,KAAK,MAAM,GAAG,IAAI,KAAK,MAAM,GAAG,KAAK,GAAG,CAAC;AAAA;AAAA,IAEnE,GAAG,IAAI,GAAG,eAAe,GAAG,CAAC;AAAA;AAAA,IAE7B,GAAG,KAAK,GAAG;AAAA,IACX,GAAG,MAAM,GAAG;AAAA;AAAA,IAEZ,mBAAmB,GAAG,WAAW,GAAG,MAAM,GAAG,EAAE;AAAA,EAAA;AAGjD,SAAO,UAAU,SAAS;AAC5B;AAEA,MAAM,uBAAuB,CAAC,aAAqB;AACjD,SAAO,SAAS,WAAW,IAAI,KAAK,MAAM,GAAG,EAAE,KAAK,SAAS,WAAW,IAAI,KAAK,MAAM,GAAG,EAAE,IACxF,SAAS,MAAM,CAAC,IAChB;AACN;"}
|
@@ -1,13 +1,13 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
|
-
const
|
3
|
+
const fp = require("lodash/fp");
|
4
4
|
const isInitialized = async (strapi) => {
|
5
5
|
try {
|
6
|
-
if (
|
6
|
+
if (fp.isEmpty(strapi.admin)) {
|
7
7
|
return true;
|
8
8
|
}
|
9
9
|
const anyAdministrator = await strapi.db.query("admin::user").findOne({ select: ["id"] });
|
10
|
-
return !
|
10
|
+
return !fp.isNil(anyAdministrator);
|
11
11
|
} catch (err) {
|
12
12
|
strapi.stopWithError(err);
|
13
13
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"is-initialized.js","sources":["../../src/utils/is-initialized.ts"],"sourcesContent":["import { isEmpty, isNil } from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\n\n/**\n * Test if the strapi application is considered as initialized (1st user has been created)\n */\nexport const isInitialized = async (strapi: Core.Strapi): Promise<boolean> => {\n try {\n if (isEmpty(strapi.admin)) {\n return true;\n }\n\n // test if there is at least one admin\n const anyAdministrator = await strapi.db.query('admin::user').findOne({ select: ['id'] });\n\n return !isNil(anyAdministrator);\n } catch (err) {\n strapi.stopWithError(err);\n }\n};\n"],"names":["isEmpty","isNil"],"mappings":";;;AAOa,MAAA,gBAAgB,OAAO,WAA0C;AACxE,MAAA;AACE,QAAAA,
|
1
|
+
{"version":3,"file":"is-initialized.js","sources":["../../src/utils/is-initialized.ts"],"sourcesContent":["import { isEmpty, isNil } from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\n\n/**\n * Test if the strapi application is considered as initialized (1st user has been created)\n */\nexport const isInitialized = async (strapi: Core.Strapi): Promise<boolean> => {\n try {\n if (isEmpty(strapi.admin)) {\n return true;\n }\n\n // test if there is at least one admin\n const anyAdministrator = await strapi.db.query('admin::user').findOne({ select: ['id'] });\n\n return !isNil(anyAdministrator);\n } catch (err) {\n strapi.stopWithError(err);\n }\n};\n"],"names":["isEmpty","isNil"],"mappings":";;;AAOa,MAAA,gBAAgB,OAAO,WAA0C;AACxE,MAAA;AACE,QAAAA,GAAA,QAAQ,OAAO,KAAK,GAAG;AAClB,aAAA;AAAA,IACT;AAGA,UAAM,mBAAmB,MAAM,OAAO,GAAG,MAAM,aAAa,EAAE,QAAQ,EAAE,QAAQ,CAAC,IAAI,EAAG,CAAA;AAEjF,WAAA,CAACC,GAAAA,MAAM,gBAAgB;AAAA,WACvB,KAAK;AACZ,WAAO,cAAc,GAAG;AAAA,EAC1B;AACF;;"}
|
@@ -2,17 +2,17 @@
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
3
|
const chalk = require("chalk");
|
4
4
|
const CLITable = require("cli-table3");
|
5
|
-
const
|
5
|
+
const fp = require("lodash/fp");
|
6
6
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
7
7
|
const chalk__default = /* @__PURE__ */ _interopDefault(chalk);
|
8
8
|
const CLITable__default = /* @__PURE__ */ _interopDefault(CLITable);
|
9
|
-
const
|
9
|
+
const fp__default = /* @__PURE__ */ _interopDefault(fp);
|
10
10
|
const createStartupLogger = (app) => {
|
11
11
|
return {
|
12
12
|
logStats() {
|
13
13
|
const columns = Math.min(process.stderr.columns, 80) - 2;
|
14
14
|
console.log();
|
15
|
-
console.log(chalk__default.default.black.bgWhite(
|
15
|
+
console.log(chalk__default.default.black.bgWhite(fp__default.default.padEnd(columns, " Project information")));
|
16
16
|
console.log();
|
17
17
|
const infoTable = new CLITable__default.default({
|
18
18
|
colWidths: [20, 50],
|
@@ -29,7 +29,7 @@ const createStartupLogger = (app) => {
|
|
29
29
|
);
|
30
30
|
console.log(infoTable.toString());
|
31
31
|
console.log();
|
32
|
-
console.log(chalk__default.default.black.bgWhite(
|
32
|
+
console.log(chalk__default.default.black.bgWhite(fp__default.default.padEnd(columns, " Actions available")));
|
33
33
|
console.log();
|
34
34
|
},
|
35
35
|
logFirstStartupMessage() {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"startup-logger.js","sources":["../../src/utils/startup-logger.ts"],"sourcesContent":["import chalk from 'chalk';\nimport CLITable from 'cli-table3';\nimport _ from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\n\nexport const createStartupLogger = (app: Core.Strapi) => {\n return {\n logStats() {\n const columns = Math.min(process.stderr.columns, 80) - 2;\n console.log();\n console.log(chalk.black.bgWhite(_.padEnd(columns, ' Project information')));\n console.log();\n\n const infoTable = new CLITable({\n colWidths: [20, 50],\n chars: { mid: '', 'left-mid': '', 'mid-mid': '', 'right-mid': '' },\n });\n\n infoTable.push(\n [chalk.blue('Time'), `${new Date()}`],\n [chalk.blue('Launched in'), `${Date.now() - app.config.launchedAt} ms`],\n [chalk.blue('Environment'), app.config.environment],\n [chalk.blue('Process PID'), process.pid],\n [chalk.blue('Version'), `${app.config.info.strapi} (node ${process.version})`],\n [chalk.blue('Edition'), app.EE ? 'Enterprise' : 'Community'],\n [chalk.blue('Database'), app.db?.dialect.client]\n );\n\n console.log(infoTable.toString());\n console.log();\n console.log(chalk.black.bgWhite(_.padEnd(columns, ' Actions available')));\n console.log();\n },\n\n logFirstStartupMessage() {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n\n this.logStats();\n\n console.log(chalk.bold('One more thing...'));\n console.log(\n chalk.grey('Create your first administrator 💻 by going to the administration panel at:')\n );\n console.log();\n\n const addressTable = new CLITable();\n\n const adminUrl = strapi.config.get('admin.absoluteUrl');\n addressTable.push([chalk.bold(adminUrl)]);\n\n console.log(`${addressTable.toString()}`);\n console.log();\n },\n\n logDefaultStartupMessage() {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n this.logStats();\n\n console.log(chalk.bold('Welcome back!'));\n\n if (app.config.get('admin.serveAdminPanel') === true) {\n console.log(chalk.grey('To manage your project 🚀, go to the administration panel at:'));\n const adminUrl = strapi.config.get('admin.absoluteUrl');\n console.log(chalk.bold(adminUrl));\n console.log();\n }\n\n console.log(chalk.grey('To access the server ⚡️, go to:'));\n const serverUrl = strapi.config.get('server.absoluteUrl');\n console.log(chalk.bold(serverUrl));\n console.log();\n },\n\n logStartupMessage({ isInitialized }: { isInitialized: boolean }) {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n if (!isInitialized) {\n this.logFirstStartupMessage();\n } else {\n this.logDefaultStartupMessage();\n }\n },\n };\n};\n"],"names":["chalk","_","CLITable"],"mappings":";;;;;;;;;AAMa,MAAA,sBAAsB,CAAC,QAAqB;AAChD,SAAA;AAAA,IACL,WAAW;AACT,YAAM,UAAU,KAAK,IAAI,QAAQ,OAAO,SAAS,EAAE,IAAI;AACvD,cAAQ,IAAI;AACJ,cAAA,IAAIA,uBAAM,MAAM,QAAQC,
|
1
|
+
{"version":3,"file":"startup-logger.js","sources":["../../src/utils/startup-logger.ts"],"sourcesContent":["import chalk from 'chalk';\nimport CLITable from 'cli-table3';\nimport _ from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\n\nexport const createStartupLogger = (app: Core.Strapi) => {\n return {\n logStats() {\n const columns = Math.min(process.stderr.columns, 80) - 2;\n console.log();\n console.log(chalk.black.bgWhite(_.padEnd(columns, ' Project information')));\n console.log();\n\n const infoTable = new CLITable({\n colWidths: [20, 50],\n chars: { mid: '', 'left-mid': '', 'mid-mid': '', 'right-mid': '' },\n });\n\n infoTable.push(\n [chalk.blue('Time'), `${new Date()}`],\n [chalk.blue('Launched in'), `${Date.now() - app.config.launchedAt} ms`],\n [chalk.blue('Environment'), app.config.environment],\n [chalk.blue('Process PID'), process.pid],\n [chalk.blue('Version'), `${app.config.info.strapi} (node ${process.version})`],\n [chalk.blue('Edition'), app.EE ? 'Enterprise' : 'Community'],\n [chalk.blue('Database'), app.db?.dialect.client]\n );\n\n console.log(infoTable.toString());\n console.log();\n console.log(chalk.black.bgWhite(_.padEnd(columns, ' Actions available')));\n console.log();\n },\n\n logFirstStartupMessage() {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n\n this.logStats();\n\n console.log(chalk.bold('One more thing...'));\n console.log(\n chalk.grey('Create your first administrator 💻 by going to the administration panel at:')\n );\n console.log();\n\n const addressTable = new CLITable();\n\n const adminUrl = strapi.config.get('admin.absoluteUrl');\n addressTable.push([chalk.bold(adminUrl)]);\n\n console.log(`${addressTable.toString()}`);\n console.log();\n },\n\n logDefaultStartupMessage() {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n this.logStats();\n\n console.log(chalk.bold('Welcome back!'));\n\n if (app.config.get('admin.serveAdminPanel') === true) {\n console.log(chalk.grey('To manage your project 🚀, go to the administration panel at:'));\n const adminUrl = strapi.config.get('admin.absoluteUrl');\n console.log(chalk.bold(adminUrl));\n console.log();\n }\n\n console.log(chalk.grey('To access the server ⚡️, go to:'));\n const serverUrl = strapi.config.get('server.absoluteUrl');\n console.log(chalk.bold(serverUrl));\n console.log();\n },\n\n logStartupMessage({ isInitialized }: { isInitialized: boolean }) {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n if (!isInitialized) {\n this.logFirstStartupMessage();\n } else {\n this.logDefaultStartupMessage();\n }\n },\n };\n};\n"],"names":["chalk","_","CLITable"],"mappings":";;;;;;;;;AAMa,MAAA,sBAAsB,CAAC,QAAqB;AAChD,SAAA;AAAA,IACL,WAAW;AACT,YAAM,UAAU,KAAK,IAAI,QAAQ,OAAO,SAAS,EAAE,IAAI;AACvD,cAAQ,IAAI;AACJ,cAAA,IAAIA,uBAAM,MAAM,QAAQC,oBAAE,OAAO,SAAS,sBAAsB,CAAC,CAAC;AAC1E,cAAQ,IAAI;AAEN,YAAA,YAAY,IAAIC,0BAAS;AAAA,QAC7B,WAAW,CAAC,IAAI,EAAE;AAAA,QAClB,OAAO,EAAE,KAAK,IAAI,YAAY,IAAI,WAAW,IAAI,aAAa,GAAG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A,IAEA,2BAA2B;AACzB,UAAI,CAAC,OAAO,OAAO,IAAI,+BAA+B,GAAG;AACvD;AAAA,MACF;AACA,WAAK,SAAS;AAEd,cAAQ,IAAIA,eAAAA,QAAM,KAAK,eAAe,CAAC;AAEvC,UAAI,IAAI,OAAO,IAAI,uBAAuB,MAAM,MAAM;AACpD,gBAAQ,IAAIA,eAAAA,QAAM,KAAK,+DAA+D,CAAC;AACvF,cAAM,WAAW,OAAO,OAAO,IAAI,mBAAmB;AACtD,gBAAQ,IAAIA,eAAAA,QAAM,KAAK,QAAQ,CAAC;AAChC,gBAAQ,IAAI;AAAA,MACd;AAEA,cAAQ,IAAIA,eAAAA,QAAM,KAAK,iCAAiC,CAAC;AACzD,YAAM,YAAY,OAAO,OAAO,IAAI,oBAAoB;AACxD,cAAQ,IAAIA,eAAAA,QAAM,KAAK,SAAS,CAAC;AACjC,cAAQ,IAAI;AAAA,IACd;AAAA,IAEA,kBAAkB,EAAE,iBAA6C;AAC/D,UAAI,CAAC,OAAO,OAAO,IAAI,+BAA+B,GAAG;AACvD;AAAA,MACF;AACA,UAAI,CAAC,eAAe;AAClB,aAAK,uBAAuB;AAAA,MAAA,OACvB;AACL,aAAK,yBAAyB;AAAA,MAChC;AAAA,IACF;AAAA,EAAA;AAEJ;;"}
|
@@ -1,12 +1,12 @@
|
|
1
1
|
import chalk from "chalk";
|
2
2
|
import CLITable from "cli-table3";
|
3
|
-
import
|
3
|
+
import fp from "lodash/fp";
|
4
4
|
const createStartupLogger = (app) => {
|
5
5
|
return {
|
6
6
|
logStats() {
|
7
7
|
const columns = Math.min(process.stderr.columns, 80) - 2;
|
8
8
|
console.log();
|
9
|
-
console.log(chalk.black.bgWhite(
|
9
|
+
console.log(chalk.black.bgWhite(fp.padEnd(columns, " Project information")));
|
10
10
|
console.log();
|
11
11
|
const infoTable = new CLITable({
|
12
12
|
colWidths: [20, 50],
|
@@ -23,7 +23,7 @@ const createStartupLogger = (app) => {
|
|
23
23
|
);
|
24
24
|
console.log(infoTable.toString());
|
25
25
|
console.log();
|
26
|
-
console.log(chalk.black.bgWhite(
|
26
|
+
console.log(chalk.black.bgWhite(fp.padEnd(columns, " Actions available")));
|
27
27
|
console.log();
|
28
28
|
},
|
29
29
|
logFirstStartupMessage() {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"startup-logger.mjs","sources":["../../src/utils/startup-logger.ts"],"sourcesContent":["import chalk from 'chalk';\nimport CLITable from 'cli-table3';\nimport _ from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\n\nexport const createStartupLogger = (app: Core.Strapi) => {\n return {\n logStats() {\n const columns = Math.min(process.stderr.columns, 80) - 2;\n console.log();\n console.log(chalk.black.bgWhite(_.padEnd(columns, ' Project information')));\n console.log();\n\n const infoTable = new CLITable({\n colWidths: [20, 50],\n chars: { mid: '', 'left-mid': '', 'mid-mid': '', 'right-mid': '' },\n });\n\n infoTable.push(\n [chalk.blue('Time'), `${new Date()}`],\n [chalk.blue('Launched in'), `${Date.now() - app.config.launchedAt} ms`],\n [chalk.blue('Environment'), app.config.environment],\n [chalk.blue('Process PID'), process.pid],\n [chalk.blue('Version'), `${app.config.info.strapi} (node ${process.version})`],\n [chalk.blue('Edition'), app.EE ? 'Enterprise' : 'Community'],\n [chalk.blue('Database'), app.db?.dialect.client]\n );\n\n console.log(infoTable.toString());\n console.log();\n console.log(chalk.black.bgWhite(_.padEnd(columns, ' Actions available')));\n console.log();\n },\n\n logFirstStartupMessage() {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n\n this.logStats();\n\n console.log(chalk.bold('One more thing...'));\n console.log(\n chalk.grey('Create your first administrator 💻 by going to the administration panel at:')\n );\n console.log();\n\n const addressTable = new CLITable();\n\n const adminUrl = strapi.config.get('admin.absoluteUrl');\n addressTable.push([chalk.bold(adminUrl)]);\n\n console.log(`${addressTable.toString()}`);\n console.log();\n },\n\n logDefaultStartupMessage() {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n this.logStats();\n\n console.log(chalk.bold('Welcome back!'));\n\n if (app.config.get('admin.serveAdminPanel') === true) {\n console.log(chalk.grey('To manage your project 🚀, go to the administration panel at:'));\n const adminUrl = strapi.config.get('admin.absoluteUrl');\n console.log(chalk.bold(adminUrl));\n console.log();\n }\n\n console.log(chalk.grey('To access the server ⚡️, go to:'));\n const serverUrl = strapi.config.get('server.absoluteUrl');\n console.log(chalk.bold(serverUrl));\n console.log();\n },\n\n logStartupMessage({ isInitialized }: { isInitialized: boolean }) {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n if (!isInitialized) {\n this.logFirstStartupMessage();\n } else {\n this.logDefaultStartupMessage();\n }\n },\n };\n};\n"],"names":[],"mappings":";;;AAMa,MAAA,sBAAsB,CAAC,QAAqB;AAChD,SAAA;AAAA,IACL,WAAW;AACT,YAAM,UAAU,KAAK,IAAI,QAAQ,OAAO,SAAS,EAAE,IAAI;AACvD,cAAQ,IAAI;AACJ,cAAA,IAAI,MAAM,MAAM,
|
1
|
+
{"version":3,"file":"startup-logger.mjs","sources":["../../src/utils/startup-logger.ts"],"sourcesContent":["import chalk from 'chalk';\nimport CLITable from 'cli-table3';\nimport _ from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\n\nexport const createStartupLogger = (app: Core.Strapi) => {\n return {\n logStats() {\n const columns = Math.min(process.stderr.columns, 80) - 2;\n console.log();\n console.log(chalk.black.bgWhite(_.padEnd(columns, ' Project information')));\n console.log();\n\n const infoTable = new CLITable({\n colWidths: [20, 50],\n chars: { mid: '', 'left-mid': '', 'mid-mid': '', 'right-mid': '' },\n });\n\n infoTable.push(\n [chalk.blue('Time'), `${new Date()}`],\n [chalk.blue('Launched in'), `${Date.now() - app.config.launchedAt} ms`],\n [chalk.blue('Environment'), app.config.environment],\n [chalk.blue('Process PID'), process.pid],\n [chalk.blue('Version'), `${app.config.info.strapi} (node ${process.version})`],\n [chalk.blue('Edition'), app.EE ? 'Enterprise' : 'Community'],\n [chalk.blue('Database'), app.db?.dialect.client]\n );\n\n console.log(infoTable.toString());\n console.log();\n console.log(chalk.black.bgWhite(_.padEnd(columns, ' Actions available')));\n console.log();\n },\n\n logFirstStartupMessage() {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n\n this.logStats();\n\n console.log(chalk.bold('One more thing...'));\n console.log(\n chalk.grey('Create your first administrator 💻 by going to the administration panel at:')\n );\n console.log();\n\n const addressTable = new CLITable();\n\n const adminUrl = strapi.config.get('admin.absoluteUrl');\n addressTable.push([chalk.bold(adminUrl)]);\n\n console.log(`${addressTable.toString()}`);\n console.log();\n },\n\n logDefaultStartupMessage() {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n this.logStats();\n\n console.log(chalk.bold('Welcome back!'));\n\n if (app.config.get('admin.serveAdminPanel') === true) {\n console.log(chalk.grey('To manage your project 🚀, go to the administration panel at:'));\n const adminUrl = strapi.config.get('admin.absoluteUrl');\n console.log(chalk.bold(adminUrl));\n console.log();\n }\n\n console.log(chalk.grey('To access the server ⚡️, go to:'));\n const serverUrl = strapi.config.get('server.absoluteUrl');\n console.log(chalk.bold(serverUrl));\n console.log();\n },\n\n logStartupMessage({ isInitialized }: { isInitialized: boolean }) {\n if (!strapi.config.get('server.logger.startup.enabled')) {\n return;\n }\n if (!isInitialized) {\n this.logFirstStartupMessage();\n } else {\n this.logDefaultStartupMessage();\n }\n },\n };\n};\n"],"names":["_"],"mappings":";;;AAMa,MAAA,sBAAsB,CAAC,QAAqB;AAChD,SAAA;AAAA,IACL,WAAW;AACT,YAAM,UAAU,KAAK,IAAI,QAAQ,OAAO,SAAS,EAAE,IAAI;AACvD,cAAQ,IAAI;AACJ,cAAA,IAAI,MAAM,MAAM,QAAQA,GAAE,OAAO,SAAS,sBAAsB,CAAC,CAAC;AAC1E,cAAQ,IAAI;AAEN,YAAA,YAAY,IAAI,SAAS;AAAA,QAC7B,WAAW,CAAC,IAAI,EAAE;AAAA,QAClB,OAAO,EAAE,KAA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,OAAO,OAAO,IAAI,+BAA+B,GAAG;AACvD;AAAA,MACF;AACA,WAAK,SAAS;AAEd,cAAQ,IAAI,MAAM,KAAK,eAAe,CAAC;AAEvC,UAAI,IAAI,OAAO,IAAI,uBAAuB,MAAM,MAAM;AACpD,gBAAQ,IAAI,MAAM,KAAK,+DAA+D,CAAC;AACvF,cAAM,WAAW,OAAO,OAAO,IAAI,mBAAmB;AACtD,gBAAQ,IAAI,MAAM,KAAK,QAAQ,CAAC;AAChC,gBAAQ,IAAI;AAAA,MACd;AAEA,cAAQ,IAAI,MAAM,KAAK,iCAAiC,CAAC;AACzD,YAAM,YAAY,OAAO,OAAO,IAAI,oBAAoB;AACxD,cAAQ,IAAI,MAAM,KAAK,SAAS,CAAC;AACjC,cAAQ,IAAI;AAAA,IACd;AAAA,IAEA,kBAAkB,EAAE,iBAA6C;AAC/D,UAAI,CAAC,OAAO,OAAO,IAAI,+BAA+B,GAAG;AACvD;AAAA,MACF;AACA,UAAI,CAAC,eAAe;AAClB,aAAK,uBAAuB;AAAA,MAAA,OACvB;AACL,aAAK,yBAAyB;AAAA,MAChC;AAAA,IACF;AAAA,EAAA;AAEJ;"}
|
@@ -19,7 +19,7 @@ export declare const getComponentJoinColumnEntityName: (identifiers: Identifiers
|
|
19
19
|
export declare const getComponentJoinColumnInverseName: (identifiers: Identifiers) => string;
|
20
20
|
export declare const getComponentTypeColumn: (identifiers: Identifiers) => string;
|
21
21
|
export declare const getComponentFkIndexName: (contentType: string, identifiers: Identifiers) => string;
|
22
|
-
export type LoadedContentTypeModel = Struct.ContentTypeSchema & Required<Pick<Struct.ContentTypeSchema, 'collectionName' | 'uid' | 'modelName'
|
22
|
+
export type LoadedContentTypeModel = Struct.ContentTypeSchema & Required<Pick<Struct.ContentTypeSchema, 'collectionName' | 'uid' | 'modelName'>> & Pick<Model, 'lifecycles'>;
|
23
23
|
export declare const transformAttribute: (name: string, attribute: Schema.Attribute.AnyAttribute, contentType: LoadedContentTypeModel, identifiers: Identifiers) => (Schema.Attribute.OfType<"biginteger"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<string> & Schema.Attribute.MinMaxOption<string> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption) | (Schema.Attribute.OfType<"boolean"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<boolean> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"blocks"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"datetime"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.DateTimeValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"date"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<Schema.Attribute.DateValue> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"decimal"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption) | (Schema.Attribute.OfType<"email"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<string> & Schema.Attribute.MinMaxLengthOption & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.UniqueOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"enumeration"> & Schema.Attribute.EnumerationProperties<string[]> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<string> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"float"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption) | (Schema.Attribute.OfType<"integer"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<number> & Schema.Attribute.MinMaxOption<number> & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.UniqueOption) | (Schema.Attribute.OfType<"json"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.RequiredOption & Schema.Attribute.PrivateOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.DefaultOption<import("@strapi/types/dist/utils").JSONPrimitive>) | (Schema.Attribute.OfType<"password"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.DefaultOption<string> & Schema.Attribute.MinMaxLengthOption & Schema.Attribute.PrivateOption & Schema.Attribute.RequiredOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption) | (Schema.Attribute.OfType<"relation"> & Schema.Attribute.ConfigurableOption & Schema.Attribute.PrivateOption & Schema.Attribute.WritableOption & Schema.Attribute.VisibleOption & Schema.Attribute.RequiredOption & {
|
24
24
|
useJoinTable?: boolean | undefined;
|
25
25
|
} & {
|
@@ -124,7 +124,7 @@ export declare const transformAttribute: (name: string, attribute: Schema.Attrib
|
|
124
124
|
morphBy?: undefined;
|
125
125
|
};
|
126
126
|
export declare const transformAttributes: (contentType: LoadedContentTypeModel, identifiers: Identifiers) => {};
|
127
|
-
export declare const hasComponentsOrDz: (contentType: LoadedContentTypeModel) => contentType is Struct.ContentTypeSchema & Required<Pick<Struct.ContentTypeSchema, "uid" | "collectionName" | "modelName">> & {
|
127
|
+
export declare const hasComponentsOrDz: (contentType: LoadedContentTypeModel) => contentType is Struct.ContentTypeSchema & Required<Pick<Struct.ContentTypeSchema, "uid" | "collectionName" | "modelName">> & Pick<Model, "lifecycles"> & {
|
128
128
|
type: 'dynamiczone' | 'component';
|
129
129
|
};
|
130
130
|
export declare const createDocumentId: typeof createId;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"transform-content-types-to-models.d.ts","sourceRoot":"","sources":["../../src/utils/transform-content-types-to-models.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,KAAK,EAAE,KAAK,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAIhD;;;;;;;;;;;GAWG;AAEH,eAAO,MAAM,yBAAyB,mBAAoB,MAAM,eAAe,WAAW,WAKzF,CAAC;AAEF,eAAO,MAAM,kBAAkB,mBAAoB,MAAM,eAAe,WAAW,WAKlF,CAAC;AAEF,eAAO,MAAM,gCAAgC,gBAAiB,WAAW,WAKxE,CAAC;AAEF,eAAO,MAAM,iCAAiC,gBAAiB,WAAW,WAKzE,CAAC;AAEF,eAAO,MAAM,sBAAsB,gBAAiB,WAAW,WAE9D,CAAC;AAEF,eAAO,MAAM,uBAAuB,gBAAiB,MAAM,eAAe,WAAW,WAMpF,CAAC;AAIF,MAAM,MAAM,sBAAsB,GAAG,MAAM,CAAC,iBAAiB,GAC3D,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,iBAAiB,EAAE,gBAAgB,GAAG,KAAK,GAAG,WAAW,CAAC,CAAC,CAAC;
|
1
|
+
{"version":3,"file":"transform-content-types-to-models.d.ts","sourceRoot":"","sources":["../../src/utils/transform-content-types-to-models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MAAM,6BAA6B,iBAC1B,sBAAsB,EAAE,eACzB,WAAW,KACvB,KAAK,EAkEP,CAAC"}
|
@@ -2,10 +2,10 @@
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
3
3
|
const cuid2 = require("@paralleldrive/cuid2");
|
4
4
|
const assert = require("node:assert");
|
5
|
-
const
|
5
|
+
const fp = require("lodash/fp");
|
6
6
|
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
7
7
|
const assert__default = /* @__PURE__ */ _interopDefault(assert);
|
8
|
-
const
|
8
|
+
const fp__default = /* @__PURE__ */ _interopDefault(fp);
|
9
9
|
const getComponentJoinTableName = (collectionName, identifiers) => {
|
10
10
|
return identifiers.getNameFromTokens([
|
11
11
|
{ name: collectionName, compressible: true },
|
@@ -233,7 +233,7 @@ const transformContentTypesToModels = (contentTypes, identifiers) => {
|
|
233
233
|
const documentIdAttribute = contentType.modelType === "contentType" ? { documentId: { type: "string", default: createDocumentId } } : {};
|
234
234
|
const reservedAttributeNames = ["document_id", identifiers.ID_COLUMN];
|
235
235
|
Object.keys(contentType.attributes || {}).forEach((attributeName) => {
|
236
|
-
const snakeCasedAttributeName =
|
236
|
+
const snakeCasedAttributeName = fp__default.default.snakeCase(attributeName);
|
237
237
|
if (reservedAttributeNames.includes(snakeCasedAttributeName)) {
|
238
238
|
throw new Error(
|
239
239
|
`The attribute "${attributeName}" is reserved and cannot be used in a model. Please rename "${contentType.modelName}" attribute "${attributeName}" to something else.`
|
@@ -257,7 +257,8 @@ const transformContentTypesToModels = (contentTypes, identifiers) => {
|
|
257
257
|
...transformAttributes(contentType, identifiers)
|
258
258
|
},
|
259
259
|
indexes: contentType.indexes,
|
260
|
-
foreignKeys: contentType.foreignKeys
|
260
|
+
foreignKeys: contentType.foreignKeys,
|
261
|
+
lifecycles: contentType?.lifecycles ?? {}
|
261
262
|
};
|
262
263
|
if (contentType.modelType === "contentType") {
|
263
264
|
model.indexes = [
|
@@ -265,7 +266,7 @@ const transformContentTypesToModels = (contentTypes, identifiers) => {
|
|
265
266
|
{
|
266
267
|
name: identifiers.getIndexName([contentType.collectionName, "documents"]),
|
267
268
|
// Filter attributes that are not in the schema
|
268
|
-
columns: ["documentId", "locale", "publishedAt"].filter((n) => model.attributes[n]).map((name) => identifiers.getColumnName(
|
269
|
+
columns: ["documentId", "locale", "publishedAt"].filter((n) => model.attributes[n]).map((name) => identifiers.getColumnName(fp__default.default.snakeCase(name)))
|
269
270
|
}
|
270
271
|
];
|
271
272
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"transform-content-types-to-models.js","sources":["../../src/utils/transform-content-types-to-models.ts"],"sourcesContent":["import { type Model, type Identifiers } from '@strapi/database';\nimport type { Struct, Schema } from '@strapi/types';\nimport { createId } from '@paralleldrive/cuid2';\nimport assert from 'node:assert';\nimport _ from 'lodash/fp';\n\n/**\n * Because strapi/database models don't know about things like components or dynamic zones, we use this file to convert them\n * to a relations format that it recognizes\n *\n * Therefore we have to keep an additional set of helpers/extensions to the database naming methods\n *\n * IMPORTANT!\n * If we use short versions of anything, we MUST call getNameFromTokens directly; attempting to shorten them ourselves\n * prevents the unshortened name map from being filled properly, so for example it will think that the short name\n * 'collection4f3a_cmps' maps to the unshortened 'collectionname_cmps' rather than 'collectionname_components'\n * Therefore, we only use the identifiers helpers in cases where we do not do any of our own shortening\n */\n\nexport const getComponentJoinTableName = (collectionName: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: collectionName, compressible: true },\n { name: 'components', shortName: 'cmps', compressible: false },\n ]);\n};\n\nexport const getDzJoinTableName = (collectionName: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: collectionName, compressible: true },\n { name: 'components', shortName: 'cmps', compressible: false },\n ]);\n};\n\nexport const getComponentJoinColumnEntityName = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: 'entity', compressible: false },\n { name: 'id', compressible: false },\n ]);\n};\n\nexport const getComponentJoinColumnInverseName = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: 'component', shortName: 'cmp', compressible: false },\n { name: 'id', compressible: false },\n ]);\n};\n\nexport const getComponentTypeColumn = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([{ name: 'component_type', compressible: false }]);\n};\n\nexport const getComponentFkIndexName = (contentType: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: contentType, compressible: true },\n { name: 'entity', compressible: false },\n { name: 'fk', compressible: false },\n ]);\n};\n\n// const { ID_COLUMN: id, FIELD_COLUMN: field, ORDER_COLUMN: order } = identifiers;\n\nexport type LoadedContentTypeModel = Struct.ContentTypeSchema &\n Required<Pick<Struct.ContentTypeSchema, 'collectionName' | 'uid' | 'modelName'>>;\n\n// Transforms an attribute (particularly for relation types) into the format that strapi/database accepts\nexport const transformAttribute = (\n name: string,\n attribute: Schema.Attribute.AnyAttribute,\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n) => {\n switch (attribute.type) {\n case 'media': {\n return {\n type: 'relation',\n relation: attribute.multiple === true ? 'morphMany' : 'morphOne',\n target: 'plugin::upload.file',\n morphBy: 'related',\n };\n }\n case 'component': {\n const joinTableName = getComponentJoinTableName(contentType.collectionName, identifiers);\n const joinColumnEntityName = getComponentJoinColumnEntityName(identifiers);\n const joinColumnInverseName = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n return {\n type: 'relation',\n relation: attribute.repeatable === true ? 'oneToMany' : 'oneToOne',\n target: attribute.component,\n\n // We need the join table name to be deterministic,\n // We need to allow passing the join table name as an option\n joinTable: {\n name: joinTableName,\n joinColumn: {\n name: joinColumnEntityName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n inverseJoinColumn: {\n name: joinColumnInverseName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n on: {\n field: name,\n },\n orderColumnName: identifiers.ORDER_COLUMN,\n orderBy: {\n order: 'asc',\n },\n pivotColumns: [\n joinColumnEntityName,\n joinColumnInverseName,\n identifiers.FIELD_COLUMN,\n compTypeColumn,\n ],\n },\n };\n }\n case 'dynamiczone': {\n const joinTableName = getDzJoinTableName(contentType.collectionName, identifiers);\n const joinColumnEntityName = getComponentJoinColumnEntityName(identifiers);\n const joinColumnInverseName = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n\n return {\n type: 'relation',\n relation: 'morphToMany',\n // TODO: handle restrictions at some point\n // target: attribute.components,\n joinTable: {\n name: joinTableName,\n joinColumn: {\n name: joinColumnEntityName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n morphColumn: {\n idColumn: {\n name: joinColumnInverseName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n typeColumn: {\n name: compTypeColumn,\n },\n typeField: '__component',\n },\n on: {\n field: name,\n },\n orderBy: {\n order: 'asc',\n },\n pivotColumns: [\n joinColumnEntityName,\n joinColumnInverseName,\n identifiers.FIELD_COLUMN,\n compTypeColumn,\n ],\n },\n };\n }\n default: {\n return attribute;\n }\n }\n};\n\nexport const transformAttributes = (\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n) => {\n return Object.keys(contentType.attributes! || {}).reduce((attrs, attrName) => {\n return {\n ...attrs,\n [attrName]: transformAttribute(\n attrName,\n contentType.attributes[attrName]!,\n contentType,\n identifiers\n ),\n };\n }, {});\n};\n\nexport const hasComponentsOrDz = (\n contentType: LoadedContentTypeModel\n): contentType is LoadedContentTypeModel & { type: 'dynamiczone' | 'component' } => {\n return Object.values(contentType.attributes || {}).some(\n (({ type }: { type: string }) => type === 'dynamiczone' || type === 'component') as any\n );\n};\n\nexport const createDocumentId = createId;\n\nconst createCompoLinkModel = (\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n): Model => {\n const name = getComponentJoinTableName(contentType.collectionName, identifiers);\n\n const entityId = getComponentJoinColumnEntityName(identifiers);\n const componentId = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n const fkIndex = getComponentFkIndexName(contentType.collectionName, identifiers);\n\n return {\n // TODO: make sure there can't be any conflicts with a prefix\n singularName: name,\n uid: name,\n tableName: name,\n attributes: {\n [identifiers.ID_COLUMN]: {\n type: 'increments',\n },\n [entityId]: {\n type: 'integer',\n column: {\n unsigned: true,\n },\n },\n [componentId]: {\n type: 'integer',\n column: {\n unsigned: true,\n },\n },\n [compTypeColumn]: {\n type: 'string',\n },\n [identifiers.FIELD_COLUMN]: {\n type: 'string',\n },\n [identifiers.ORDER_COLUMN]: {\n type: 'float',\n column: {\n unsigned: true,\n defaultTo: null,\n },\n },\n },\n indexes: [\n {\n name: identifiers.getIndexName([contentType.collectionName, identifiers.FIELD_COLUMN]),\n columns: [identifiers.FIELD_COLUMN],\n },\n {\n name: identifiers.getIndexName([contentType.collectionName, compTypeColumn]),\n columns: [compTypeColumn],\n },\n {\n name: fkIndex,\n columns: [entityId],\n },\n {\n // NOTE: since we don't include attribute names, we need to be careful not to create another unique index\n name: identifiers.getUniqueIndexName([contentType.collectionName]),\n columns: [entityId, componentId, identifiers.FIELD_COLUMN, compTypeColumn],\n type: 'unique',\n },\n ],\n foreignKeys: [\n {\n name: fkIndex,\n columns: [entityId],\n referencedColumns: [identifiers.ID_COLUMN],\n referencedTable: identifiers.getTableName(contentType.collectionName),\n onDelete: 'CASCADE',\n },\n ],\n };\n};\n\nexport const transformContentTypesToModels = (\n contentTypes: LoadedContentTypeModel[],\n identifiers: Identifiers\n): Model[] => {\n const models: Model[] = [];\n\n contentTypes.forEach((contentType) => {\n assert(contentType.collectionName, 'Content type \"collectionName\" is required');\n assert(contentType.modelName, 'Content type \"modelName\" is required');\n assert(contentType.uid, 'Content type \"uid\" is required');\n\n // Add document id to content types\n // as it is not documented\n const documentIdAttribute: Record<string, Schema.Attribute.AnyAttribute> =\n contentType.modelType === 'contentType'\n ? { documentId: { type: 'string', default: createDocumentId } }\n : {};\n\n // TODO: this needs to be combined with getReservedNames, we should not be maintaining two lists\n // Prevent user from creating a documentId attribute\n const reservedAttributeNames = ['document_id', identifiers.ID_COLUMN];\n Object.keys(contentType.attributes || {}).forEach((attributeName) => {\n const snakeCasedAttributeName = _.snakeCase(attributeName);\n if (reservedAttributeNames.includes(snakeCasedAttributeName)) {\n throw new Error(\n `The attribute \"${attributeName}\" is reserved and cannot be used in a model. Please rename \"${contentType.modelName}\" attribute \"${attributeName}\" to something else.`\n );\n }\n });\n\n if (hasComponentsOrDz(contentType)) {\n const compoLinkModel = createCompoLinkModel(contentType, identifiers);\n models.push(compoLinkModel);\n }\n\n const model: Model = {\n uid: contentType.uid,\n singularName: contentType.modelName,\n tableName: contentType.collectionName, // This gets shortened in metadata.loadModels(), so we don't shorten here or it will happen twice\n attributes: {\n [identifiers.ID_COLUMN]: {\n type: 'increments',\n },\n ...documentIdAttribute,\n ...transformAttributes(contentType, identifiers),\n },\n indexes: contentType.indexes as Model['indexes'],\n foreignKeys: contentType.foreignKeys as Model['foreignKeys'],\n };\n\n // Add indexes to model\n if (contentType.modelType === 'contentType') {\n model.indexes = [\n ...(model.indexes || []),\n {\n name: identifiers.getIndexName([contentType.collectionName, 'documents']),\n // Filter attributes that are not in the schema\n columns: ['documentId', 'locale', 'publishedAt']\n .filter((n) => model.attributes[n])\n .map((name) => identifiers.getColumnName(_.snakeCase(name))),\n },\n ];\n }\n\n models.push(model);\n });\n\n return models;\n};\n"],"names":["createId","assert","_"],"mappings":";;;;;;;;AAmBa,MAAA,4BAA4B,CAAC,gBAAwB,gBAA6B;AAC7F,SAAO,YAAY,kBAAkB;AAAA,IACnC,EAAE,MAAM,gBAAgB,cAAc,KAAK;AAAA,IAC3C,EAAE,MAAM,cAAc,WAAW,QAAQ,cAAc,MAAM;AAAA,EAAA,CAC9D;AACH;AAEa,MAAA,qBAAqB,CAAC,gBAAwB,gBAA6B;AACtF,SAAO,YAAY,kBAAkB;AAAA,IACnC,EAAE,MAAM,gBAAgB,cAAc,KAAK;AAAA,IAC3C,EAAE,MAAM,cA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;AAC7D,YAAA,0BAA0BC,WAAAA,QAAE,UAAU,aAAa;AACrD,UAAA,uBAAuB,SAAS,uBAAuB,GAAG;AAC5D,cAAM,IAAI;AAAA,UACR,kBAAkB,aAAa,+DAA+D,YAAY,SAAS,gBAAgB,aAAa;AAAA,QAAA;AAAA,MAEpJ;AAAA,IAAA,CACD;AAEG,QAAA,kBAAkB,WAAW,GAAG;AAC5B,YAAA,iBAAiB,qBAAqB,aAAa,WAAW;AACpE,aAAO,KAAK,cAAc;AAAA,IAC5B;AAEA,UAAM,QAAe;AAAA,MACnB,KAAK,YAAY;AAAA,MACjB,cAAc,YAAY;AAAA,MAC1B,WAAW,YAAY;AAAA;AAAA,MACvB,YAAY;AAAA,QACV,CAAC,YAAY,SAAS,GAAG;AAAA,UACvB,MAAM;AAAA,QACR;AAAA,QACA,GAAG;AAAA,QACH,GAAG,oBAAoB,aAAa,WAAW;AAAA,MACjD;AAAA,MACA,SAAS,YAAY;AAAA,MACrB,aAAa,YAAY;AAAA,IAAA;AAIvB,QAAA,YAAY,cAAc,eAAe;AAC3C,YAAM,UAAU;AAAA,QACd,GAAI,MAAM,WAAW,CAAC;AAAA,QACtB;AAAA,UACE,MAAM,YAAY,aAAa,CAAC,YAAY,gBAAgB,WAAW,CAAC;AAAA;AAAA,UAExE,SAAS,CAAC,cAAc,UAAU,aAAa,EAC5C,OAAO,CAAC,MAAM,MAAM,WAAW,CAAC,CAAC,EACjC,IAAI,CAAC,SAAS,YAAY,cAAcA,mBAAE,UAAU,IAAI,CAAC,CAAC;AAAA,QAC/D;AAAA,MAAA;AAAA,IAEJ;AAEA,WAAO,KAAK,KAAK;AAAA,EAAA,CAClB;AAEM,SAAA;AACT;;;;;;;;;;;;"}
|
1
|
+
{"version":3,"file":"transform-content-types-to-models.js","sources":["../../src/utils/transform-content-types-to-models.ts"],"sourcesContent":["import { type Model, type Identifiers } from '@strapi/database';\nimport type { Struct, Schema } from '@strapi/types';\nimport { createId } from '@paralleldrive/cuid2';\nimport assert from 'node:assert';\nimport _ from 'lodash/fp';\n\n/**\n * Because strapi/database models don't know about things like components or dynamic zones, we use this file to convert them\n * to a relations format that it recognizes\n *\n * Therefore we have to keep an additional set of helpers/extensions to the database naming methods\n *\n * IMPORTANT!\n * If we use short versions of anything, we MUST call getNameFromTokens directly; attempting to shorten them ourselves\n * prevents the unshortened name map from being filled properly, so for example it will think that the short name\n * 'collection4f3a_cmps' maps to the unshortened 'collectionname_cmps' rather than 'collectionname_components'\n * Therefore, we only use the identifiers helpers in cases where we do not do any of our own shortening\n */\n\nexport const getComponentJoinTableName = (collectionName: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: collectionName, compressible: true },\n { name: 'components', shortName: 'cmps', compressible: false },\n ]);\n};\n\nexport const getDzJoinTableName = (collectionName: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: collectionName, compressible: true },\n { name: 'components', shortName: 'cmps', compressible: false },\n ]);\n};\n\nexport const getComponentJoinColumnEntityName = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: 'entity', compressible: false },\n { name: 'id', compressible: false },\n ]);\n};\n\nexport const getComponentJoinColumnInverseName = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: 'component', shortName: 'cmp', compressible: false },\n { name: 'id', compressible: false },\n ]);\n};\n\nexport const getComponentTypeColumn = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([{ name: 'component_type', compressible: false }]);\n};\n\nexport const getComponentFkIndexName = (contentType: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: contentType, compressible: true },\n { name: 'entity', compressible: false },\n { name: 'fk', compressible: false },\n ]);\n};\n\n// const { ID_COLUMN: id, FIELD_COLUMN: field, ORDER_COLUMN: order } = identifiers;\n\nexport type LoadedContentTypeModel = Struct.ContentTypeSchema &\n Required<Pick<Struct.ContentTypeSchema, 'collectionName' | 'uid' | 'modelName'>> &\n Pick<Model, 'lifecycles'>;\n\n// Transforms an attribute (particularly for relation types) into the format that strapi/database accepts\nexport const transformAttribute = (\n name: string,\n attribute: Schema.Attribute.AnyAttribute,\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n) => {\n switch (attribute.type) {\n case 'media': {\n return {\n type: 'relation',\n relation: attribute.multiple === true ? 'morphMany' : 'morphOne',\n target: 'plugin::upload.file',\n morphBy: 'related',\n };\n }\n case 'component': {\n const joinTableName = getComponentJoinTableName(contentType.collectionName, identifiers);\n const joinColumnEntityName = getComponentJoinColumnEntityName(identifiers);\n const joinColumnInverseName = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n return {\n type: 'relation',\n relation: attribute.repeatable === true ? 'oneToMany' : 'oneToOne',\n target: attribute.component,\n\n // We need the join table name to be deterministic,\n // We need to allow passing the join table name as an option\n joinTable: {\n name: joinTableName,\n joinColumn: {\n name: joinColumnEntityName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n inverseJoinColumn: {\n name: joinColumnInverseName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n on: {\n field: name,\n },\n orderColumnName: identifiers.ORDER_COLUMN,\n orderBy: {\n order: 'asc',\n },\n pivotColumns: [\n joinColumnEntityName,\n joinColumnInverseName,\n identifiers.FIELD_COLUMN,\n compTypeColumn,\n ],\n },\n };\n }\n case 'dynamiczone': {\n const joinTableName = getDzJoinTableName(contentType.collectionName, identifiers);\n const joinColumnEntityName = getComponentJoinColumnEntityName(identifiers);\n const joinColumnInverseName = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n\n return {\n type: 'relation',\n relation: 'morphToMany',\n // TODO: handle restrictions at some point\n // target: attribute.components,\n joinTable: {\n name: joinTableName,\n joinColumn: {\n name: joinColumnEntityName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n morphColumn: {\n idColumn: {\n name: joinColumnInverseName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n typeColumn: {\n name: compTypeColumn,\n },\n typeField: '__component',\n },\n on: {\n field: name,\n },\n orderBy: {\n order: 'asc',\n },\n pivotColumns: [\n joinColumnEntityName,\n joinColumnInverseName,\n identifiers.FIELD_COLUMN,\n compTypeColumn,\n ],\n },\n };\n }\n default: {\n return attribute;\n }\n }\n};\n\nexport const transformAttributes = (\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n) => {\n return Object.keys(contentType.attributes! || {}).reduce((attrs, attrName) => {\n return {\n ...attrs,\n [attrName]: transformAttribute(\n attrName,\n contentType.attributes[attrName]!,\n contentType,\n identifiers\n ),\n };\n }, {});\n};\n\nexport const hasComponentsOrDz = (\n contentType: LoadedContentTypeModel\n): contentType is LoadedContentTypeModel & { type: 'dynamiczone' | 'component' } => {\n return Object.values(contentType.attributes || {}).some(\n (({ type }: { type: string }) => type === 'dynamiczone' || type === 'component') as any\n );\n};\n\nexport const createDocumentId = createId;\n\nconst createCompoLinkModel = (\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n): Model => {\n const name = getComponentJoinTableName(contentType.collectionName, identifiers);\n\n const entityId = getComponentJoinColumnEntityName(identifiers);\n const componentId = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n const fkIndex = getComponentFkIndexName(contentType.collectionName, identifiers);\n\n return {\n // TODO: make sure there can't be any conflicts with a prefix\n singularName: name,\n uid: name,\n tableName: name,\n attributes: {\n [identifiers.ID_COLUMN]: {\n type: 'increments',\n },\n [entityId]: {\n type: 'integer',\n column: {\n unsigned: true,\n },\n },\n [componentId]: {\n type: 'integer',\n column: {\n unsigned: true,\n },\n },\n [compTypeColumn]: {\n type: 'string',\n },\n [identifiers.FIELD_COLUMN]: {\n type: 'string',\n },\n [identifiers.ORDER_COLUMN]: {\n type: 'float',\n column: {\n unsigned: true,\n defaultTo: null,\n },\n },\n },\n indexes: [\n {\n name: identifiers.getIndexName([contentType.collectionName, identifiers.FIELD_COLUMN]),\n columns: [identifiers.FIELD_COLUMN],\n },\n {\n name: identifiers.getIndexName([contentType.collectionName, compTypeColumn]),\n columns: [compTypeColumn],\n },\n {\n name: fkIndex,\n columns: [entityId],\n },\n {\n // NOTE: since we don't include attribute names, we need to be careful not to create another unique index\n name: identifiers.getUniqueIndexName([contentType.collectionName]),\n columns: [entityId, componentId, identifiers.FIELD_COLUMN, compTypeColumn],\n type: 'unique',\n },\n ],\n foreignKeys: [\n {\n name: fkIndex,\n columns: [entityId],\n referencedColumns: [identifiers.ID_COLUMN],\n referencedTable: identifiers.getTableName(contentType.collectionName),\n onDelete: 'CASCADE',\n },\n ],\n };\n};\n\nexport const transformContentTypesToModels = (\n contentTypes: LoadedContentTypeModel[],\n identifiers: Identifiers\n): Model[] => {\n const models: Model[] = [];\n\n contentTypes.forEach((contentType) => {\n assert(contentType.collectionName, 'Content type \"collectionName\" is required');\n assert(contentType.modelName, 'Content type \"modelName\" is required');\n assert(contentType.uid, 'Content type \"uid\" is required');\n\n // Add document id to content types\n // as it is not documented\n const documentIdAttribute: Record<string, Schema.Attribute.AnyAttribute> =\n contentType.modelType === 'contentType'\n ? { documentId: { type: 'string', default: createDocumentId } }\n : {};\n\n // TODO: this needs to be combined with getReservedNames, we should not be maintaining two lists\n // Prevent user from creating a documentId attribute\n const reservedAttributeNames = ['document_id', identifiers.ID_COLUMN];\n Object.keys(contentType.attributes || {}).forEach((attributeName) => {\n const snakeCasedAttributeName = _.snakeCase(attributeName);\n if (reservedAttributeNames.includes(snakeCasedAttributeName)) {\n throw new Error(\n `The attribute \"${attributeName}\" is reserved and cannot be used in a model. Please rename \"${contentType.modelName}\" attribute \"${attributeName}\" to something else.`\n );\n }\n });\n\n if (hasComponentsOrDz(contentType)) {\n const compoLinkModel = createCompoLinkModel(contentType, identifiers);\n models.push(compoLinkModel);\n }\n\n const model: Model = {\n uid: contentType.uid,\n singularName: contentType.modelName,\n tableName: contentType.collectionName, // This gets shortened in metadata.loadModels(), so we don't shorten here or it will happen twice\n attributes: {\n [identifiers.ID_COLUMN]: {\n type: 'increments',\n },\n ...documentIdAttribute,\n ...transformAttributes(contentType, identifiers),\n },\n indexes: contentType.indexes as Model['indexes'],\n foreignKeys: contentType.foreignKeys as Model['foreignKeys'],\n lifecycles: contentType?.lifecycles ?? {},\n };\n\n // Add indexes to model\n if (contentType.modelType === 'contentType') {\n model.indexes = [\n ...(model.indexes || []),\n {\n name: identifiers.getIndexName([contentType.collectionName, 'documents']),\n // Filter attributes that are not in the schema\n columns: ['documentId', 'locale', 'publishedAt']\n .filter((n) => model.attributes[n])\n .map((name) => identifiers.getColumnName(_.snakeCase(name))),\n },\n ];\n }\n\n models.push(model);\n });\n\n return models;\n};\n"],"names":["createId","assert","_"],"mappings":";;;;;;;;AAmBa,MAAA,4BAA4B,CAAC,gBAAwB,gBAA6B;AAC7F,SAAO,YAAY,kBAAkB;AAAA,IACnC,EAAE,MAAM,gBAAgB,cAAc,KAAK;AAAA,IAC3C,EAAE,MAAM,cAAc,WAAW,QAAQ,cAAc,MAAM;AAAA,EAAA,CAC9D;AACH;AAEa,MAAA,qBAAqB,CAAC,gBAAwB,gBAA6B;AACtF,SAAO,YAAY,kBAAkB;AAAA,IACnC,EAAE,MAAM,gBAAgB,cAAc,KAAK;AAAA,IAC3C,EAAE,MAAM,cAAc,WAAW,QAAQ,cAAc,MAAM;AAAA,EAAA,CAC9D;AACH;AAEa,MAAA,mCAAmC,CAAC,gBAA6B;AAC5E,SAAO,YAAY,kBAAkB;AAAA,IACnC,EAAE,MAAM,UAAU,cAAc,MAAM;AAAA,IACtC,EAAE,MAAM,MAAM,cAAc,MAAM;AAAA,EAAA,CACnC;AACH;AAEa,MAAA,oCAAoC,CAAC,gBAA6B;AAC7E,SAAO,YAAY,kBAAkB;AAAA,IACnC,EAAE,MAAM,aAAa,WAAW,OAAO,cAAc,MAAM;AAAA,IAC3D,EAAE,MAAM,MAAM,cAAc,MAAM;AAAA,EAAA,CACnC;AACH;AAEa,MAAA,yBAAyB,CAAC,gBAA6B;AAC3D,SAAA,YAAY,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Y,SAAS,GAAG;AAAA,UACvB,MAAM;AAAA,QACR;AAAA,QACA,GAAG;AAAA,QACH,GAAG,oBAAoB,aAAa,WAAW;AAAA,MACjD;AAAA,MACA,SAAS,YAAY;AAAA,MACrB,aAAa,YAAY;AAAA,MACzB,YAAY,aAAa,cAAc,CAAC;AAAA,IAAA;AAItC,QAAA,YAAY,cAAc,eAAe;AAC3C,YAAM,UAAU;AAAA,QACd,GAAI,MAAM,WAAW,CAAC;AAAA,QACtB;AAAA,UACE,MAAM,YAAY,aAAa,CAAC,YAAY,gBAAgB,WAAW,CAAC;AAAA;AAAA,UAExE,SAAS,CAAC,cAAc,UAAU,aAAa,EAC5C,OAAO,CAAC,MAAM,MAAM,WAAW,CAAC,CAAC,EACjC,IAAI,CAAC,SAAS,YAAY,cAAcA,oBAAE,UAAU,IAAI,CAAC,CAAC;AAAA,QAC/D;AAAA,MAAA;AAAA,IAEJ;AAEA,WAAO,KAAK,KAAK;AAAA,EAAA,CAClB;AAEM,SAAA;AACT;;;;;;;;;;;;"}
|
@@ -1,6 +1,6 @@
|
|
1
1
|
import { createId } from "@paralleldrive/cuid2";
|
2
2
|
import assert from "node:assert";
|
3
|
-
import
|
3
|
+
import fp from "lodash/fp";
|
4
4
|
const getComponentJoinTableName = (collectionName, identifiers) => {
|
5
5
|
return identifiers.getNameFromTokens([
|
6
6
|
{ name: collectionName, compressible: true },
|
@@ -228,7 +228,7 @@ const transformContentTypesToModels = (contentTypes, identifiers) => {
|
|
228
228
|
const documentIdAttribute = contentType.modelType === "contentType" ? { documentId: { type: "string", default: createDocumentId } } : {};
|
229
229
|
const reservedAttributeNames = ["document_id", identifiers.ID_COLUMN];
|
230
230
|
Object.keys(contentType.attributes || {}).forEach((attributeName) => {
|
231
|
-
const snakeCasedAttributeName =
|
231
|
+
const snakeCasedAttributeName = fp.snakeCase(attributeName);
|
232
232
|
if (reservedAttributeNames.includes(snakeCasedAttributeName)) {
|
233
233
|
throw new Error(
|
234
234
|
`The attribute "${attributeName}" is reserved and cannot be used in a model. Please rename "${contentType.modelName}" attribute "${attributeName}" to something else.`
|
@@ -252,7 +252,8 @@ const transformContentTypesToModels = (contentTypes, identifiers) => {
|
|
252
252
|
...transformAttributes(contentType, identifiers)
|
253
253
|
},
|
254
254
|
indexes: contentType.indexes,
|
255
|
-
foreignKeys: contentType.foreignKeys
|
255
|
+
foreignKeys: contentType.foreignKeys,
|
256
|
+
lifecycles: contentType?.lifecycles ?? {}
|
256
257
|
};
|
257
258
|
if (contentType.modelType === "contentType") {
|
258
259
|
model.indexes = [
|
@@ -260,7 +261,7 @@ const transformContentTypesToModels = (contentTypes, identifiers) => {
|
|
260
261
|
{
|
261
262
|
name: identifiers.getIndexName([contentType.collectionName, "documents"]),
|
262
263
|
// Filter attributes that are not in the schema
|
263
|
-
columns: ["documentId", "locale", "publishedAt"].filter((n) => model.attributes[n]).map((name) => identifiers.getColumnName(
|
264
|
+
columns: ["documentId", "locale", "publishedAt"].filter((n) => model.attributes[n]).map((name) => identifiers.getColumnName(fp.snakeCase(name)))
|
264
265
|
}
|
265
266
|
];
|
266
267
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"transform-content-types-to-models.mjs","sources":["../../src/utils/transform-content-types-to-models.ts"],"sourcesContent":["import { type Model, type Identifiers } from '@strapi/database';\nimport type { Struct, Schema } from '@strapi/types';\nimport { createId } from '@paralleldrive/cuid2';\nimport assert from 'node:assert';\nimport _ from 'lodash/fp';\n\n/**\n * Because strapi/database models don't know about things like components or dynamic zones, we use this file to convert them\n * to a relations format that it recognizes\n *\n * Therefore we have to keep an additional set of helpers/extensions to the database naming methods\n *\n * IMPORTANT!\n * If we use short versions of anything, we MUST call getNameFromTokens directly; attempting to shorten them ourselves\n * prevents the unshortened name map from being filled properly, so for example it will think that the short name\n * 'collection4f3a_cmps' maps to the unshortened 'collectionname_cmps' rather than 'collectionname_components'\n * Therefore, we only use the identifiers helpers in cases where we do not do any of our own shortening\n */\n\nexport const getComponentJoinTableName = (collectionName: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: collectionName, compressible: true },\n { name: 'components', shortName: 'cmps', compressible: false },\n ]);\n};\n\nexport const getDzJoinTableName = (collectionName: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: collectionName, compressible: true },\n { name: 'components', shortName: 'cmps', compressible: false },\n ]);\n};\n\nexport const getComponentJoinColumnEntityName = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: 'entity', compressible: false },\n { name: 'id', compressible: false },\n ]);\n};\n\nexport const getComponentJoinColumnInverseName = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: 'component', shortName: 'cmp', compressible: false },\n { name: 'id', compressible: false },\n ]);\n};\n\nexport const getComponentTypeColumn = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([{ name: 'component_type', compressible: false }]);\n};\n\nexport const getComponentFkIndexName = (contentType: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: contentType, compressible: true },\n { name: 'entity', compressible: false },\n { name: 'fk', compressible: false },\n ]);\n};\n\n// const { ID_COLUMN: id, FIELD_COLUMN: field, ORDER_COLUMN: order } = identifiers;\n\nexport type LoadedContentTypeModel = Struct.ContentTypeSchema &\n Required<Pick<Struct.ContentTypeSchema, 'collectionName' | 'uid' | 'modelName'>>;\n\n// Transforms an attribute (particularly for relation types) into the format that strapi/database accepts\nexport const transformAttribute = (\n name: string,\n attribute: Schema.Attribute.AnyAttribute,\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n) => {\n switch (attribute.type) {\n case 'media': {\n return {\n type: 'relation',\n relation: attribute.multiple === true ? 'morphMany' : 'morphOne',\n target: 'plugin::upload.file',\n morphBy: 'related',\n };\n }\n case 'component': {\n const joinTableName = getComponentJoinTableName(contentType.collectionName, identifiers);\n const joinColumnEntityName = getComponentJoinColumnEntityName(identifiers);\n const joinColumnInverseName = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n return {\n type: 'relation',\n relation: attribute.repeatable === true ? 'oneToMany' : 'oneToOne',\n target: attribute.component,\n\n // We need the join table name to be deterministic,\n // We need to allow passing the join table name as an option\n joinTable: {\n name: joinTableName,\n joinColumn: {\n name: joinColumnEntityName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n inverseJoinColumn: {\n name: joinColumnInverseName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n on: {\n field: name,\n },\n orderColumnName: identifiers.ORDER_COLUMN,\n orderBy: {\n order: 'asc',\n },\n pivotColumns: [\n joinColumnEntityName,\n joinColumnInverseName,\n identifiers.FIELD_COLUMN,\n compTypeColumn,\n ],\n },\n };\n }\n case 'dynamiczone': {\n const joinTableName = getDzJoinTableName(contentType.collectionName, identifiers);\n const joinColumnEntityName = getComponentJoinColumnEntityName(identifiers);\n const joinColumnInverseName = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n\n return {\n type: 'relation',\n relation: 'morphToMany',\n // TODO: handle restrictions at some point\n // target: attribute.components,\n joinTable: {\n name: joinTableName,\n joinColumn: {\n name: joinColumnEntityName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n morphColumn: {\n idColumn: {\n name: joinColumnInverseName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n typeColumn: {\n name: compTypeColumn,\n },\n typeField: '__component',\n },\n on: {\n field: name,\n },\n orderBy: {\n order: 'asc',\n },\n pivotColumns: [\n joinColumnEntityName,\n joinColumnInverseName,\n identifiers.FIELD_COLUMN,\n compTypeColumn,\n ],\n },\n };\n }\n default: {\n return attribute;\n }\n }\n};\n\nexport const transformAttributes = (\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n) => {\n return Object.keys(contentType.attributes! || {}).reduce((attrs, attrName) => {\n return {\n ...attrs,\n [attrName]: transformAttribute(\n attrName,\n contentType.attributes[attrName]!,\n contentType,\n identifiers\n ),\n };\n }, {});\n};\n\nexport const hasComponentsOrDz = (\n contentType: LoadedContentTypeModel\n): contentType is LoadedContentTypeModel & { type: 'dynamiczone' | 'component' } => {\n return Object.values(contentType.attributes || {}).some(\n (({ type }: { type: string }) => type === 'dynamiczone' || type === 'component') as any\n );\n};\n\nexport const createDocumentId = createId;\n\nconst createCompoLinkModel = (\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n): Model => {\n const name = getComponentJoinTableName(contentType.collectionName, identifiers);\n\n const entityId = getComponentJoinColumnEntityName(identifiers);\n const componentId = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n const fkIndex = getComponentFkIndexName(contentType.collectionName, identifiers);\n\n return {\n // TODO: make sure there can't be any conflicts with a prefix\n singularName: name,\n uid: name,\n tableName: name,\n attributes: {\n [identifiers.ID_COLUMN]: {\n type: 'increments',\n },\n [entityId]: {\n type: 'integer',\n column: {\n unsigned: true,\n },\n },\n [componentId]: {\n type: 'integer',\n column: {\n unsigned: true,\n },\n },\n [compTypeColumn]: {\n type: 'string',\n },\n [identifiers.FIELD_COLUMN]: {\n type: 'string',\n },\n [identifiers.ORDER_COLUMN]: {\n type: 'float',\n column: {\n unsigned: true,\n defaultTo: null,\n },\n },\n },\n indexes: [\n {\n name: identifiers.getIndexName([contentType.collectionName, identifiers.FIELD_COLUMN]),\n columns: [identifiers.FIELD_COLUMN],\n },\n {\n name: identifiers.getIndexName([contentType.collectionName, compTypeColumn]),\n columns: [compTypeColumn],\n },\n {\n name: fkIndex,\n columns: [entityId],\n },\n {\n // NOTE: since we don't include attribute names, we need to be careful not to create another unique index\n name: identifiers.getUniqueIndexName([contentType.collectionName]),\n columns: [entityId, componentId, identifiers.FIELD_COLUMN, compTypeColumn],\n type: 'unique',\n },\n ],\n foreignKeys: [\n {\n name: fkIndex,\n columns: [entityId],\n referencedColumns: [identifiers.ID_COLUMN],\n referencedTable: identifiers.getTableName(contentType.collectionName),\n onDelete: 'CASCADE',\n },\n ],\n };\n};\n\nexport const transformContentTypesToModels = (\n contentTypes: LoadedContentTypeModel[],\n identifiers: Identifiers\n): Model[] => {\n const models: Model[] = [];\n\n contentTypes.forEach((contentType) => {\n assert(contentType.collectionName, 'Content type \"collectionName\" is required');\n assert(contentType.modelName, 'Content type \"modelName\" is required');\n assert(contentType.uid, 'Content type \"uid\" is required');\n\n // Add document id to content types\n // as it is not documented\n const documentIdAttribute: Record<string, Schema.Attribute.AnyAttribute> =\n contentType.modelType === 'contentType'\n ? { documentId: { type: 'string', default: createDocumentId } }\n : {};\n\n // TODO: this needs to be combined with getReservedNames, we should not be maintaining two lists\n // Prevent user from creating a documentId attribute\n const reservedAttributeNames = ['document_id', identifiers.ID_COLUMN];\n Object.keys(contentType.attributes || {}).forEach((attributeName) => {\n const snakeCasedAttributeName = _.snakeCase(attributeName);\n if (reservedAttributeNames.includes(snakeCasedAttributeName)) {\n throw new Error(\n `The attribute \"${attributeName}\" is reserved and cannot be used in a model. Please rename \"${contentType.modelName}\" attribute \"${attributeName}\" to something else.`\n );\n }\n });\n\n if (hasComponentsOrDz(contentType)) {\n const compoLinkModel = createCompoLinkModel(contentType, identifiers);\n models.push(compoLinkModel);\n }\n\n const model: Model = {\n uid: contentType.uid,\n singularName: contentType.modelName,\n tableName: contentType.collectionName, // This gets shortened in metadata.loadModels(), so we don't shorten here or it will happen twice\n attributes: {\n [identifiers.ID_COLUMN]: {\n type: 'increments',\n },\n ...documentIdAttribute,\n ...transformAttributes(contentType, identifiers),\n },\n indexes: contentType.indexes as Model['indexes'],\n foreignKeys: contentType.foreignKeys as Model['foreignKeys'],\n };\n\n // Add indexes to model\n if (contentType.modelType === 'contentType') {\n model.indexes = [\n ...(model.indexes || []),\n {\n name: identifiers.getIndexName([contentType.collectionName, 'documents']),\n // Filter attributes that are not in the schema\n columns: ['documentId', 'locale', 'publishedAt']\n .filter((n) => model.attributes[n])\n .map((name) => identifiers.getColumnName(_.snakeCase(name))),\n },\n ];\n }\n\n models.push(model);\n });\n\n return models;\n};\n"],"names":[],"mapp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U,IAAI,CAAC,CAAC;AAAA,QAC/D;AAAA,MAAA;AAAA,IAEJ;AAEA,WAAO,KAAK,KAAK;AAAA,EAAA,CAClB;AAEM,SAAA;AACT;"}
|
1
|
+
{"version":3,"file":"transform-content-types-to-models.mjs","sources":["../../src/utils/transform-content-types-to-models.ts"],"sourcesContent":["import { type Model, type Identifiers } from '@strapi/database';\nimport type { Struct, Schema } from '@strapi/types';\nimport { createId } from '@paralleldrive/cuid2';\nimport assert from 'node:assert';\nimport _ from 'lodash/fp';\n\n/**\n * Because strapi/database models don't know about things like components or dynamic zones, we use this file to convert them\n * to a relations format that it recognizes\n *\n * Therefore we have to keep an additional set of helpers/extensions to the database naming methods\n *\n * IMPORTANT!\n * If we use short versions of anything, we MUST call getNameFromTokens directly; attempting to shorten them ourselves\n * prevents the unshortened name map from being filled properly, so for example it will think that the short name\n * 'collection4f3a_cmps' maps to the unshortened 'collectionname_cmps' rather than 'collectionname_components'\n * Therefore, we only use the identifiers helpers in cases where we do not do any of our own shortening\n */\n\nexport const getComponentJoinTableName = (collectionName: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: collectionName, compressible: true },\n { name: 'components', shortName: 'cmps', compressible: false },\n ]);\n};\n\nexport const getDzJoinTableName = (collectionName: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: collectionName, compressible: true },\n { name: 'components', shortName: 'cmps', compressible: false },\n ]);\n};\n\nexport const getComponentJoinColumnEntityName = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: 'entity', compressible: false },\n { name: 'id', compressible: false },\n ]);\n};\n\nexport const getComponentJoinColumnInverseName = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: 'component', shortName: 'cmp', compressible: false },\n { name: 'id', compressible: false },\n ]);\n};\n\nexport const getComponentTypeColumn = (identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([{ name: 'component_type', compressible: false }]);\n};\n\nexport const getComponentFkIndexName = (contentType: string, identifiers: Identifiers) => {\n return identifiers.getNameFromTokens([\n { name: contentType, compressible: true },\n { name: 'entity', compressible: false },\n { name: 'fk', compressible: false },\n ]);\n};\n\n// const { ID_COLUMN: id, FIELD_COLUMN: field, ORDER_COLUMN: order } = identifiers;\n\nexport type LoadedContentTypeModel = Struct.ContentTypeSchema &\n Required<Pick<Struct.ContentTypeSchema, 'collectionName' | 'uid' | 'modelName'>> &\n Pick<Model, 'lifecycles'>;\n\n// Transforms an attribute (particularly for relation types) into the format that strapi/database accepts\nexport const transformAttribute = (\n name: string,\n attribute: Schema.Attribute.AnyAttribute,\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n) => {\n switch (attribute.type) {\n case 'media': {\n return {\n type: 'relation',\n relation: attribute.multiple === true ? 'morphMany' : 'morphOne',\n target: 'plugin::upload.file',\n morphBy: 'related',\n };\n }\n case 'component': {\n const joinTableName = getComponentJoinTableName(contentType.collectionName, identifiers);\n const joinColumnEntityName = getComponentJoinColumnEntityName(identifiers);\n const joinColumnInverseName = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n return {\n type: 'relation',\n relation: attribute.repeatable === true ? 'oneToMany' : 'oneToOne',\n target: attribute.component,\n\n // We need the join table name to be deterministic,\n // We need to allow passing the join table name as an option\n joinTable: {\n name: joinTableName,\n joinColumn: {\n name: joinColumnEntityName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n inverseJoinColumn: {\n name: joinColumnInverseName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n on: {\n field: name,\n },\n orderColumnName: identifiers.ORDER_COLUMN,\n orderBy: {\n order: 'asc',\n },\n pivotColumns: [\n joinColumnEntityName,\n joinColumnInverseName,\n identifiers.FIELD_COLUMN,\n compTypeColumn,\n ],\n },\n };\n }\n case 'dynamiczone': {\n const joinTableName = getDzJoinTableName(contentType.collectionName, identifiers);\n const joinColumnEntityName = getComponentJoinColumnEntityName(identifiers);\n const joinColumnInverseName = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n\n return {\n type: 'relation',\n relation: 'morphToMany',\n // TODO: handle restrictions at some point\n // target: attribute.components,\n joinTable: {\n name: joinTableName,\n joinColumn: {\n name: joinColumnEntityName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n morphColumn: {\n idColumn: {\n name: joinColumnInverseName,\n referencedColumn: identifiers.ID_COLUMN,\n },\n typeColumn: {\n name: compTypeColumn,\n },\n typeField: '__component',\n },\n on: {\n field: name,\n },\n orderBy: {\n order: 'asc',\n },\n pivotColumns: [\n joinColumnEntityName,\n joinColumnInverseName,\n identifiers.FIELD_COLUMN,\n compTypeColumn,\n ],\n },\n };\n }\n default: {\n return attribute;\n }\n }\n};\n\nexport const transformAttributes = (\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n) => {\n return Object.keys(contentType.attributes! || {}).reduce((attrs, attrName) => {\n return {\n ...attrs,\n [attrName]: transformAttribute(\n attrName,\n contentType.attributes[attrName]!,\n contentType,\n identifiers\n ),\n };\n }, {});\n};\n\nexport const hasComponentsOrDz = (\n contentType: LoadedContentTypeModel\n): contentType is LoadedContentTypeModel & { type: 'dynamiczone' | 'component' } => {\n return Object.values(contentType.attributes || {}).some(\n (({ type }: { type: string }) => type === 'dynamiczone' || type === 'component') as any\n );\n};\n\nexport const createDocumentId = createId;\n\nconst createCompoLinkModel = (\n contentType: LoadedContentTypeModel,\n identifiers: Identifiers\n): Model => {\n const name = getComponentJoinTableName(contentType.collectionName, identifiers);\n\n const entityId = getComponentJoinColumnEntityName(identifiers);\n const componentId = getComponentJoinColumnInverseName(identifiers);\n const compTypeColumn = getComponentTypeColumn(identifiers);\n const fkIndex = getComponentFkIndexName(contentType.collectionName, identifiers);\n\n return {\n // TODO: make sure there can't be any conflicts with a prefix\n singularName: name,\n uid: name,\n tableName: name,\n attributes: {\n [identifiers.ID_COLUMN]: {\n type: 'increments',\n },\n [entityId]: {\n type: 'integer',\n column: {\n unsigned: true,\n },\n },\n [componentId]: {\n type: 'integer',\n column: {\n unsigned: true,\n },\n },\n [compTypeColumn]: {\n type: 'string',\n },\n [identifiers.FIELD_COLUMN]: {\n type: 'string',\n },\n [identifiers.ORDER_COLUMN]: {\n type: 'float',\n column: {\n unsigned: true,\n defaultTo: null,\n },\n },\n },\n indexes: [\n {\n name: identifiers.getIndexName([contentType.collectionName, identifiers.FIELD_COLUMN]),\n columns: [identifiers.FIELD_COLUMN],\n },\n {\n name: identifiers.getIndexName([contentType.collectionName, compTypeColumn]),\n columns: [compTypeColumn],\n },\n {\n name: fkIndex,\n columns: [entityId],\n },\n {\n // NOTE: since we don't include attribute names, we need to be careful not to create another unique index\n name: identifiers.getUniqueIndexName([contentType.collectionName]),\n columns: [entityId, componentId, identifiers.FIELD_COLUMN, compTypeColumn],\n type: 'unique',\n },\n ],\n foreignKeys: [\n {\n name: fkIndex,\n columns: [entityId],\n referencedColumns: [identifiers.ID_COLUMN],\n referencedTable: identifiers.getTableName(contentType.collectionName),\n onDelete: 'CASCADE',\n },\n ],\n };\n};\n\nexport const transformContentTypesToModels = (\n contentTypes: LoadedContentTypeModel[],\n identifiers: Identifiers\n): Model[] => {\n const models: Model[] = [];\n\n contentTypes.forEach((contentType) => {\n assert(contentType.collectionName, 'Content type \"collectionName\" is required');\n assert(contentType.modelName, 'Content type \"modelName\" is required');\n assert(contentType.uid, 'Content type \"uid\" is required');\n\n // Add document id to content types\n // as it is not documented\n const documentIdAttribute: Record<string, Schema.Attribute.AnyAttribute> =\n contentType.modelType === 'contentType'\n ? { documentId: { type: 'string', default: createDocumentId } }\n : {};\n\n // TODO: this needs to be combined with getReservedNames, we should not be maintaining two lists\n // Prevent user from creating a documentId attribute\n const reservedAttributeNames = ['document_id', identifiers.ID_COLUMN];\n Object.keys(contentType.attributes || {}).forEach((attributeName) => {\n const snakeCasedAttributeName = _.snakeCase(attributeName);\n if (reservedAttributeNames.includes(snakeCasedAttributeName)) {\n throw new Error(\n `The attribute \"${attributeName}\" is reserved and cannot be used in a model. Please rename \"${contentType.modelName}\" attribute \"${attributeName}\" to something else.`\n );\n }\n });\n\n if (hasComponentsOrDz(contentType)) {\n const compoLinkModel = createCompoLinkModel(contentType, identifiers);\n models.push(compoLinkModel);\n }\n\n const model: Model = {\n uid: contentType.uid,\n singularName: contentType.modelName,\n tableName: contentType.collectionName, // This gets shortened in metadata.loadModels(), so we don't shorten here or it will happen twice\n attributes: {\n [identifiers.ID_COLUMN]: {\n type: 'increments',\n },\n ...documentIdAttribute,\n ...transformAttributes(contentType, identifiers),\n },\n indexes: contentType.indexes as Model['indexes'],\n foreignKeys: contentType.foreignKeys as Model['foreignKeys'],\n lifecycles: contentType?.lifecycles ?? {},\n };\n\n // Add indexes to model\n if (contentType.modelType === 'contentType') {\n model.indexes = [\n ...(model.indexes || []),\n {\n name: identifiers.getIndexName([contentType.collectionName, 'documents']),\n // Filter attributes that are not in the schema\n columns: ['documentId', 'locale', 'publishedAt']\n .filter((n) => model.attributes[n])\n .map((name) => identifiers.getColumnName(_.snakeCase(name))),\n },\n ];\n }\n\n models.push(model);\n });\n\n return models;\n};\n"],"names":["_"],"mappings":";;;AAmBa,MAAA,4BAA4B,CAAC,gBAAwB,gBAA6B;AAC7F,SAAO,YAAY,kBAAkB;AAAA,IACnC,EAAE,MAAM,gBAAgB,cAAc,KAAK;AAAA,IAC3C,EAAE,MAAM,cAAc,WAAW,QAAQ,cAAc,MAAM;AAAA,EAAA,CAC9D;AACH;AAEa,MAAA,qBAAqB,CAAC,gBAAwB,gBAA6B;AACtF,SAAO,YAAY,kBAAkB;AAAA,IACnC,EAAE,MAAM,gBAAgB,cAAc,KAAK;AAAA,IAC3C,EAAE,MAAM,cAAc,WAAW,QAAQ,cAAc,MAAM;AAAA,EAAA,CAC9D;AACH;AAEa,MAAA,mCAAmC,CAAC,gBAA6B;AAC5E,SAAO,YAAY,kBAAkB;AAAA,IACnC,EAAE,MAAM,UAAU,cAAc,MAAM;AAAA,IACtC,EAAE,MAAM,MAA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