@strapi/plugin-documentation 5.60.0 → 5.61.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/controllers/documentation.js +2 -1
- package/dist/server/controllers/documentation.js.map +1 -1
- package/dist/server/controllers/documentation.mjs +2 -1
- package/dist/server/controllers/documentation.mjs.map +1 -1
- package/dist/server/services/documentation.js +1 -1
- package/dist/server/services/documentation.js.map +1 -1
- package/dist/server/services/documentation.mjs +1 -1
- package/dist/server/services/documentation.mjs.map +1 -1
- package/dist/server/services/helpers/build-component-schema.js +10 -1
- package/dist/server/services/helpers/build-component-schema.js.map +1 -1
- package/dist/server/services/helpers/build-component-schema.mjs +10 -1
- package/dist/server/services/helpers/build-component-schema.mjs.map +1 -1
- package/dist/server/services/override.js +18 -6
- package/dist/server/services/override.js.map +1 -1
- package/dist/server/services/override.mjs +18 -6
- package/dist/server/services/override.mjs.map +1 -1
- package/dist/server/services/utils/get-plugins-that-need-documentation.js +3 -3
- package/dist/server/services/utils/get-plugins-that-need-documentation.js.map +1 -1
- package/dist/server/services/utils/get-plugins-that-need-documentation.mjs +3 -3
- package/dist/server/services/utils/get-plugins-that-need-documentation.mjs.map +1 -1
- package/dist/server/src/controllers/documentation.d.ts.map +1 -1
- package/dist/server/src/index.d.ts +1 -1
- package/dist/server/src/index.d.ts.map +1 -1
- package/dist/server/src/services/helpers/build-component-schema.d.ts.map +1 -1
- package/dist/server/src/services/index.d.ts +1 -1
- package/dist/server/src/services/index.d.ts.map +1 -1
- package/dist/server/src/services/override.d.ts +1 -1
- package/dist/server/src/services/override.d.ts.map +1 -1
- package/dist/server/src/services/utils/get-plugins-that-need-documentation.d.ts +2 -1
- package/dist/server/src/services/utils/get-plugins-that-need-documentation.d.ts.map +1 -1
- package/package.json +14 -12
|
@@ -121,7 +121,8 @@ var documentation = {
|
|
|
121
121
|
name: 'documentation',
|
|
122
122
|
key: 'config'
|
|
123
123
|
}).get();
|
|
124
|
-
|
|
124
|
+
// A missing stored hash or a missing submitted password counts as a wrong password
|
|
125
|
+
const isValid = typeof password === 'string' && typeof hash === 'string' ? await bcrypt__default.default.compare(password, hash) : false;
|
|
125
126
|
let querystring = '?error=password';
|
|
126
127
|
if (isValid && ctx.session) {
|
|
127
128
|
ctx.session.documentation = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentation.js","sources":["../../../server/src/controllers/documentation.ts"],"sourcesContent":["import path from 'path';\nimport bcrypt from 'bcryptjs';\nimport fs from 'fs-extra';\nimport _ from 'lodash';\nimport koaStatic from 'koa-static';\nimport { yup, validateYupSchema } from '@strapi/utils';\n\nimport type Koa from 'koa';\nimport type {} from 'koa-body';\n\nimport { getService } from '../utils';\nimport type { Config } from '../types';\n\nconst validation = {\n validateSettings: validateYupSchema(\n yup.object().shape({\n restrictedAccess: yup.boolean(),\n password: yup\n .string()\n .min(8)\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/[a-z]/, '${path} must contain at least one lowercase character')\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/[A-Z]/, '${path} must contain at least one uppercase character')\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/\\d/, '${path} must contain at least one number')\n .when('restrictedAccess', (value, initSchema) => {\n return value ? initSchema.required('password is required') : initSchema;\n }),\n })\n ),\n};\n\nexport default {\n async getInfos(ctx: Koa.Context) {\n try {\n const docService = getService('documentation');\n const docVersions = docService.getDocumentationVersions();\n const documentationAccess = await docService.getDocumentationAccess();\n\n ctx.send({\n docVersions,\n currentVersion: docService.getDocumentationVersion(),\n prefix: '/documentation',\n documentationAccess,\n });\n } catch (err) {\n strapi.log.error(err);\n ctx.badRequest();\n }\n },\n\n async index(ctx: Koa.Context, next: Koa.Next) {\n try {\n /**\n * We don't expose the specs using koa-static or something else due to security reasons.\n * That's why, we need to read the file localy and send the specs through it when we serve the Swagger UI.\n */\n const { major, minor, patch } = ctx.params;\n const version =\n major && minor && patch\n ? `${major}.${minor}.${patch}`\n : getService('documentation').getDocumentationVersion();\n\n const extensionsDir =\n strapi.config.environment === 'production'\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n\n const openAPISpecsPath = path.join(\n extensionsDir,\n 'documentation',\n 'documentation',\n version,\n 'full_documentation.json'\n );\n\n try {\n const documentation = fs.readFileSync(openAPISpecsPath, 'utf8');\n\n const layout = (await import('../public/index.html')).default;\n\n const filledLayout = _.template(layout)({\n backendUrl: strapi.config.server.url,\n spec: JSON.stringify(JSON.parse(documentation)),\n });\n\n try {\n const layoutPath = path.resolve(extensionsDir, 'documentation', 'public', 'index.html');\n await fs.ensureFile(layoutPath);\n await fs.writeFile(layoutPath, filledLayout);\n\n // Serve the file.\n ctx.url = path.basename(`${ctx.url}/index.html`);\n\n try {\n const staticFolder = path.resolve(extensionsDir, 'documentation', 'public');\n return koaStatic(staticFolder)(ctx, next);\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n },\n\n async loginView(ctx: Koa.Context, next: Koa.Next) {\n // lazy require cheerio\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const cheerio = require('cheerio');\n\n const { error } = ctx.query;\n\n try {\n const layout = (await import('../public/login.html')).default;\n\n const filledLayout = _.template(layout.toString())({\n actionUrl: `${strapi.config.server.url}/documentation/login`,\n });\n\n const $ = cheerio.load(filledLayout);\n\n $('.error').text(_.isEmpty(error) ? '' : 'Wrong password...');\n\n try {\n const layoutPath = path.resolve(\n strapi.dirs.app.extensions,\n 'documentation',\n 'public',\n 'login.html'\n );\n await fs.ensureFile(layoutPath);\n await fs.writeFile(layoutPath, $.html());\n\n ctx.url = path.basename(`${ctx.url}/login.html`);\n\n try {\n const staticFolder = path.resolve(strapi.dirs.app.extensions, 'documentation', 'public');\n return koaStatic(staticFolder)(ctx, next);\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n },\n\n async login(ctx: Koa.Context) {\n const {\n body: { password },\n } = ctx.request;\n\n const { password: hash } = (await strapi\n .store({ type: 'plugin', name: 'documentation', key: 'config' })\n .get()) as { password: string };\n\n const isValid = await bcrypt.compare(password, hash);\n\n let querystring = '?error=password';\n\n if (isValid && ctx.session) {\n ctx.session.documentation = {\n logged: true,\n };\n\n querystring = '';\n }\n\n ctx.redirect(`${strapi.config.server.url}/documentation${querystring}`);\n },\n\n async regenerateDoc(ctx: Koa.Context) {\n const { version } = ctx.request.body;\n\n const service = getService('documentation');\n\n const documentationVersions = service.getDocumentationVersions().map((el) => el.version);\n\n if (_.isEmpty(version)) {\n return ctx.badRequest('Please provide a version.');\n }\n\n if (!documentationVersions.includes(version)) {\n return ctx.badRequest('The version you are trying to generate does not exist.');\n }\n\n try {\n strapi.reload.isWatching = false;\n await service.generateFullDoc(version);\n ctx.send({ ok: true });\n } finally {\n strapi.reload.isWatching = true;\n }\n },\n\n async deleteDoc(ctx: Koa.Context) {\n const { version } = ctx.params;\n\n const service = getService('documentation');\n\n const documentationVersions = service.getDocumentationVersions().map((el) => el.version);\n\n if (_.isEmpty(version)) {\n return ctx.badRequest('Please provide a version.');\n }\n\n if (!documentationVersions.includes(version)) {\n return ctx.badRequest('The version you are trying to delete does not exist.');\n }\n\n try {\n strapi.reload.isWatching = false;\n await service.deleteDocumentation(version);\n ctx.send({ ok: true });\n } finally {\n strapi.reload.isWatching = true;\n }\n },\n\n async updateSettings(ctx: Koa.Context) {\n const pluginStore = strapi.store({ type: 'plugin', name: 'documentation' });\n\n const data = await validation.validateSettings(ctx.request.body);\n\n const config: Config = {\n restrictedAccess: Boolean(data.restrictedAccess),\n };\n\n if (data.password) {\n config.password = await bcrypt.hash(data.password, 10);\n }\n\n await pluginStore.set({ key: 'config', value: config });\n\n return ctx.send({ ok: true });\n },\n};\n"],"names":["validation","validateSettings","validateYupSchema","yup","object","shape","restrictedAccess","boolean","password","string","min","matches","when","value","initSchema","required","getInfos","ctx","docService","getService","docVersions","getDocumentationVersions","documentationAccess","getDocumentationAccess","send","currentVersion","getDocumentationVersion","prefix","err","strapi","log","error","badRequest","index","next","major","minor","patch","params","version","extensionsDir","config","environment","dirs","dist","extensions","app","openAPISpecsPath","path","join","documentation","fs","readFileSync","layout","default","filledLayout","_","template","backendUrl","server","url","spec","JSON","stringify","parse","layoutPath","resolve","ensureFile","writeFile","basename","staticFolder","koaStatic","e","loginView","cheerio","require","query","toString","actionUrl","$","load","text","isEmpty","html","login","body","request","hash","store","type","name","key","get","isValid","bcrypt","compare","querystring","session","logged","redirect","regenerateDoc","service","documentationVersions","map","el","includes","reload","isWatching","generateFullDoc","ok","deleteDoc","deleteDocumentation","updateSettings","pluginStore","data","Boolean","set"],"mappings":";;;;;;;;;;;;;;;;;;;;AAaA,MAAMA,UAAAA,GAAa;AACjBC,IAAAA,gBAAAA,EAAkBC,uBAAAA,CAChBC,SAAAA,CAAIC,MAAM,EAAA,CAAGC,KAAK,CAAC;AACjBC,QAAAA,gBAAAA,EAAkBH,UAAII,OAAO,EAAA;AAC7BC,QAAAA,QAAAA,EAAUL,UACPM,MAAM,EAAA,CACNC,GAAG,CAAC,EACL;SACCC,OAAO,CAAC,OAAA,EAAS,uDAAA,CAClB;SACCA,OAAO,CAAC,OAAA,EAAS,uDAAA,CAClB;AACCA,SAAAA,OAAO,CAAC,IAAA,EAAM,0CAAA,CAAA,CACdC,IAAI,CAAC,kBAAA,EAAoB,CAACC,KAAAA,EAAOC,UAAAA,GAAAA;AAChC,YAAA,OAAOD,KAAAA,GAAQC,UAAAA,CAAWC,QAAQ,CAAC,sBAAA,CAAA,GAA0BD,UAAAA;AAC/D,QAAA,CAAA;AACJ,KAAA,CAAA;AAEJ,CAAA;AAEA,oBAAe;AACb,IAAA,MAAME,UAASC,GAAgB,EAAA;QA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,GAAG,MAAMsF,uBAAAA,CAAOP,IAAI,CAAC2B,IAAAA,CAAK1G,QAAQ,EAAE,EAAA,CAAA;AACrD,QAAA;QAEA,MAAMyG,WAAAA,CAAYG,GAAG,CAAC;YAAEzB,GAAAA,EAAK,QAAA;YAAU9E,KAAAA,EAAO4B;AAAO,SAAA,CAAA;QAErD,OAAOxB,GAAAA,CAAIO,IAAI,CAAC;YAAEqF,EAAAA,EAAI;AAAK,SAAA,CAAA;AAC7B,IAAA;AACF,CAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"documentation.js","sources":["../../../server/src/controllers/documentation.ts"],"sourcesContent":["import path from 'path';\nimport bcrypt from 'bcryptjs';\nimport fs from 'fs-extra';\nimport _ from 'lodash';\nimport koaStatic from 'koa-static';\nimport { yup, validateYupSchema } from '@strapi/utils';\n\nimport type Koa from 'koa';\nimport type {} from 'koa-body';\n\nimport { getService } from '../utils';\nimport type { Config } from '../types';\n\nconst validation = {\n validateSettings: validateYupSchema(\n yup.object().shape({\n restrictedAccess: yup.boolean(),\n password: yup\n .string()\n .min(8)\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/[a-z]/, '${path} must contain at least one lowercase character')\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/[A-Z]/, '${path} must contain at least one uppercase character')\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/\\d/, '${path} must contain at least one number')\n .when('restrictedAccess', (value, initSchema) => {\n return value ? initSchema.required('password is required') : initSchema;\n }),\n })\n ),\n};\n\nexport default {\n async getInfos(ctx: Koa.Context) {\n try {\n const docService = getService('documentation');\n const docVersions = docService.getDocumentationVersions();\n const documentationAccess = await docService.getDocumentationAccess();\n\n ctx.send({\n docVersions,\n currentVersion: docService.getDocumentationVersion(),\n prefix: '/documentation',\n documentationAccess,\n });\n } catch (err) {\n strapi.log.error(err);\n ctx.badRequest();\n }\n },\n\n async index(ctx: Koa.Context, next: Koa.Next) {\n try {\n /**\n * We don't expose the specs using koa-static or something else due to security reasons.\n * That's why, we need to read the file localy and send the specs through it when we serve the Swagger UI.\n */\n const { major, minor, patch } = ctx.params;\n const version =\n major && minor && patch\n ? `${major}.${minor}.${patch}`\n : getService('documentation').getDocumentationVersion();\n\n const extensionsDir =\n strapi.config.environment === 'production'\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n\n const openAPISpecsPath = path.join(\n extensionsDir,\n 'documentation',\n 'documentation',\n version,\n 'full_documentation.json'\n );\n\n try {\n const documentation = fs.readFileSync(openAPISpecsPath, 'utf8');\n\n const layout = (await import('../public/index.html')).default;\n\n const filledLayout = _.template(layout)({\n backendUrl: strapi.config.server.url,\n spec: JSON.stringify(JSON.parse(documentation)),\n });\n\n try {\n const layoutPath = path.resolve(extensionsDir, 'documentation', 'public', 'index.html');\n await fs.ensureFile(layoutPath);\n await fs.writeFile(layoutPath, filledLayout);\n\n // Serve the file.\n ctx.url = path.basename(`${ctx.url}/index.html`);\n\n try {\n const staticFolder = path.resolve(extensionsDir, 'documentation', 'public');\n return koaStatic(staticFolder)(ctx, next);\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n },\n\n async loginView(ctx: Koa.Context, next: Koa.Next) {\n // lazy require cheerio\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const cheerio = require('cheerio');\n\n const { error } = ctx.query;\n\n try {\n const layout = (await import('../public/login.html')).default;\n\n const filledLayout = _.template(layout.toString())({\n actionUrl: `${strapi.config.server.url}/documentation/login`,\n });\n\n const $ = cheerio.load(filledLayout);\n\n $('.error').text(_.isEmpty(error) ? '' : 'Wrong password...');\n\n try {\n const layoutPath = path.resolve(\n strapi.dirs.app.extensions,\n 'documentation',\n 'public',\n 'login.html'\n );\n await fs.ensureFile(layoutPath);\n await fs.writeFile(layoutPath, $.html());\n\n ctx.url = path.basename(`${ctx.url}/login.html`);\n\n try {\n const staticFolder = path.resolve(strapi.dirs.app.extensions, 'documentation', 'public');\n return koaStatic(staticFolder)(ctx, next);\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n },\n\n async login(ctx: Koa.Context) {\n const {\n body: { password },\n } = ctx.request;\n\n const { password: hash } = (await strapi\n .store({ type: 'plugin', name: 'documentation', key: 'config' })\n .get()) as { password?: string };\n\n // A missing stored hash or a missing submitted password counts as a wrong password\n const isValid =\n typeof password === 'string' && typeof hash === 'string'\n ? await bcrypt.compare(password, hash)\n : false;\n\n let querystring = '?error=password';\n\n if (isValid && ctx.session) {\n ctx.session.documentation = {\n logged: true,\n };\n\n querystring = '';\n }\n\n ctx.redirect(`${strapi.config.server.url}/documentation${querystring}`);\n },\n\n async regenerateDoc(ctx: Koa.Context) {\n const { version } = ctx.request.body;\n\n const service = getService('documentation');\n\n const documentationVersions = service.getDocumentationVersions().map((el) => el.version);\n\n if (_.isEmpty(version)) {\n return ctx.badRequest('Please provide a version.');\n }\n\n if (!documentationVersions.includes(version)) {\n return ctx.badRequest('The version you are trying to generate does not exist.');\n }\n\n try {\n strapi.reload.isWatching = false;\n await service.generateFullDoc(version);\n ctx.send({ ok: true });\n } finally {\n strapi.reload.isWatching = true;\n }\n },\n\n async deleteDoc(ctx: Koa.Context) {\n const { version } = ctx.params;\n\n const service = getService('documentation');\n\n const documentationVersions = service.getDocumentationVersions().map((el) => el.version);\n\n if (_.isEmpty(version)) {\n return ctx.badRequest('Please provide a version.');\n }\n\n if (!documentationVersions.includes(version)) {\n return ctx.badRequest('The version you are trying to delete does not exist.');\n }\n\n try {\n strapi.reload.isWatching = false;\n await service.deleteDocumentation(version);\n ctx.send({ ok: true });\n } finally {\n strapi.reload.isWatching = true;\n }\n },\n\n async updateSettings(ctx: Koa.Context) {\n const pluginStore = strapi.store({ type: 'plugin', name: 'documentation' });\n\n const data = await validation.validateSettings(ctx.request.body);\n\n const config: Config = {\n restrictedAccess: Boolean(data.restrictedAccess),\n };\n\n if (data.password) {\n config.password = await bcrypt.hash(data.password, 10);\n }\n\n await pluginStore.set({ key: 'config', value: config });\n\n return ctx.send({ ok: true });\n },\n};\n"],"names":["validation","validateSettings","validateYupSchema","yup","object","shape","restrictedAccess","boolean","password","string","min","matches","when","value","initSchema","required","getInfos","ctx","docService","getService","docVersions","getDocumentationVersions","documentationAccess","getDocumentationAccess","send","currentVersion","getDocumentationVersion","prefix","err","strapi","log","error","badRequest","index","next","major","minor","patch","params","version","extensionsDir","config","environment","dirs","dist","extensions","app","openAPISpecsPath","path","join","documentation","fs","readFileSync","layout","default","filledLayout","_","template","backendUrl","server","url","spec","JSON","stringify","parse","layoutPath","resolve","ensureFile","writeFile","basename","staticFolder","koaStatic","e","loginView","cheerio","require","query","toString","actionUrl","$","load","text","isEmpty","html","login","body","request","hash","store","type","name","key","get","isValid","bcrypt","compare","querystring","session","logged","redirect","regenerateDoc","service","documentationVersions","map","el","includes","reload","isWatching","generateFullDoc","ok","deleteDoc","deleteDocumentation","updateSettings","pluginStore","data","Boolean","set"],"mappings":";;;;;;;;;;;;;;;;;;;;AAaA,MAAMA,UAAAA,GAAa;AACjBC,IAAAA,gBAAAA,EAAkBC,uBAAAA,CAChBC,SAAAA,CAAIC,MAAM,EAAA,CAAGC,KAAK,CAAC;AACjBC,QAAAA,gBAAAA,EAAkBH,UAAII,OAAO,EAAA;AAC7BC,QAAAA,QAAAA,EAAUL,UACPM,MAAM,EAAA,CACNC,GAAG,CAAC,EACL;SACCC,OAAO,CAAC,OAAA,EAAS,uDAAA,CAClB;SACCA,OAAO,CAAC,OAAA,EAAS,uDAAA,CAClB;AACCA,SAAAA,OAAO,CAAC,IAAA,EAAM,0CAAA,CAAA,CACdC,IAAI,CAAC,kBAAA,EAAoB,CAACC,KAAAA,EAAOC,UAAAA,GAAAA;AAChC,YAAA,OAAOD,KAA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H,UAAAA,CAAWC,gBAAgB,CAACgB,GAAAA,CAAIqE,OAAO,CAACD,IAAI,CAAA;AAE/D,QAAA,MAAM5C,MAAAA,GAAiB;YACrBnC,gBAAAA,EAAkB6G,OAAAA,CAAQD,KAAK5G,gBAAgB;AACjD,SAAA;QAEA,IAAI4G,IAAAA,CAAK1G,QAAQ,EAAE;YACjBiC,MAAAA,CAAOjC,QAAQ,GAAG,MAAMsF,uBAAAA,CAAOP,IAAI,CAAC2B,IAAAA,CAAK1G,QAAQ,EAAE,EAAA,CAAA;AACrD,QAAA;QAEA,MAAMyG,WAAAA,CAAYG,GAAG,CAAC;YAAEzB,GAAAA,EAAK,QAAA;YAAU9E,KAAAA,EAAO4B;AAAO,SAAA,CAAA;QAErD,OAAOxB,GAAAA,CAAIO,IAAI,CAAC;YAAEqF,EAAAA,EAAI;AAAK,SAAA,CAAA;AAC7B,IAAA;AACF,CAAA;;;;"}
|
|
@@ -109,7 +109,8 @@ var documentation = {
|
|
|
109
109
|
name: 'documentation',
|
|
110
110
|
key: 'config'
|
|
111
111
|
}).get();
|
|
112
|
-
|
|
112
|
+
// A missing stored hash or a missing submitted password counts as a wrong password
|
|
113
|
+
const isValid = typeof password === 'string' && typeof hash === 'string' ? await bcrypt.compare(password, hash) : false;
|
|
113
114
|
let querystring = '?error=password';
|
|
114
115
|
if (isValid && ctx.session) {
|
|
115
116
|
ctx.session.documentation = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentation.mjs","sources":["../../../server/src/controllers/documentation.ts"],"sourcesContent":["import path from 'path';\nimport bcrypt from 'bcryptjs';\nimport fs from 'fs-extra';\nimport _ from 'lodash';\nimport koaStatic from 'koa-static';\nimport { yup, validateYupSchema } from '@strapi/utils';\n\nimport type Koa from 'koa';\nimport type {} from 'koa-body';\n\nimport { getService } from '../utils';\nimport type { Config } from '../types';\n\nconst validation = {\n validateSettings: validateYupSchema(\n yup.object().shape({\n restrictedAccess: yup.boolean(),\n password: yup\n .string()\n .min(8)\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/[a-z]/, '${path} must contain at least one lowercase character')\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/[A-Z]/, '${path} must contain at least one uppercase character')\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/\\d/, '${path} must contain at least one number')\n .when('restrictedAccess', (value, initSchema) => {\n return value ? initSchema.required('password is required') : initSchema;\n }),\n })\n ),\n};\n\nexport default {\n async getInfos(ctx: Koa.Context) {\n try {\n const docService = getService('documentation');\n const docVersions = docService.getDocumentationVersions();\n const documentationAccess = await docService.getDocumentationAccess();\n\n ctx.send({\n docVersions,\n currentVersion: docService.getDocumentationVersion(),\n prefix: '/documentation',\n documentationAccess,\n });\n } catch (err) {\n strapi.log.error(err);\n ctx.badRequest();\n }\n },\n\n async index(ctx: Koa.Context, next: Koa.Next) {\n try {\n /**\n * We don't expose the specs using koa-static or something else due to security reasons.\n * That's why, we need to read the file localy and send the specs through it when we serve the Swagger UI.\n */\n const { major, minor, patch } = ctx.params;\n const version =\n major && minor && patch\n ? `${major}.${minor}.${patch}`\n : getService('documentation').getDocumentationVersion();\n\n const extensionsDir =\n strapi.config.environment === 'production'\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n\n const openAPISpecsPath = path.join(\n extensionsDir,\n 'documentation',\n 'documentation',\n version,\n 'full_documentation.json'\n );\n\n try {\n const documentation = fs.readFileSync(openAPISpecsPath, 'utf8');\n\n const layout = (await import('../public/index.html')).default;\n\n const filledLayout = _.template(layout)({\n backendUrl: strapi.config.server.url,\n spec: JSON.stringify(JSON.parse(documentation)),\n });\n\n try {\n const layoutPath = path.resolve(extensionsDir, 'documentation', 'public', 'index.html');\n await fs.ensureFile(layoutPath);\n await fs.writeFile(layoutPath, filledLayout);\n\n // Serve the file.\n ctx.url = path.basename(`${ctx.url}/index.html`);\n\n try {\n const staticFolder = path.resolve(extensionsDir, 'documentation', 'public');\n return koaStatic(staticFolder)(ctx, next);\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n },\n\n async loginView(ctx: Koa.Context, next: Koa.Next) {\n // lazy require cheerio\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const cheerio = require('cheerio');\n\n const { error } = ctx.query;\n\n try {\n const layout = (await import('../public/login.html')).default;\n\n const filledLayout = _.template(layout.toString())({\n actionUrl: `${strapi.config.server.url}/documentation/login`,\n });\n\n const $ = cheerio.load(filledLayout);\n\n $('.error').text(_.isEmpty(error) ? '' : 'Wrong password...');\n\n try {\n const layoutPath = path.resolve(\n strapi.dirs.app.extensions,\n 'documentation',\n 'public',\n 'login.html'\n );\n await fs.ensureFile(layoutPath);\n await fs.writeFile(layoutPath, $.html());\n\n ctx.url = path.basename(`${ctx.url}/login.html`);\n\n try {\n const staticFolder = path.resolve(strapi.dirs.app.extensions, 'documentation', 'public');\n return koaStatic(staticFolder)(ctx, next);\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n },\n\n async login(ctx: Koa.Context) {\n const {\n body: { password },\n } = ctx.request;\n\n const { password: hash } = (await strapi\n .store({ type: 'plugin', name: 'documentation', key: 'config' })\n .get()) as { password: string };\n\n const isValid = await bcrypt.compare(password, hash);\n\n let querystring = '?error=password';\n\n if (isValid && ctx.session) {\n ctx.session.documentation = {\n logged: true,\n };\n\n querystring = '';\n }\n\n ctx.redirect(`${strapi.config.server.url}/documentation${querystring}`);\n },\n\n async regenerateDoc(ctx: Koa.Context) {\n const { version } = ctx.request.body;\n\n const service = getService('documentation');\n\n const documentationVersions = service.getDocumentationVersions().map((el) => el.version);\n\n if (_.isEmpty(version)) {\n return ctx.badRequest('Please provide a version.');\n }\n\n if (!documentationVersions.includes(version)) {\n return ctx.badRequest('The version you are trying to generate does not exist.');\n }\n\n try {\n strapi.reload.isWatching = false;\n await service.generateFullDoc(version);\n ctx.send({ ok: true });\n } finally {\n strapi.reload.isWatching = true;\n }\n },\n\n async deleteDoc(ctx: Koa.Context) {\n const { version } = ctx.params;\n\n const service = getService('documentation');\n\n const documentationVersions = service.getDocumentationVersions().map((el) => el.version);\n\n if (_.isEmpty(version)) {\n return ctx.badRequest('Please provide a version.');\n }\n\n if (!documentationVersions.includes(version)) {\n return ctx.badRequest('The version you are trying to delete does not exist.');\n }\n\n try {\n strapi.reload.isWatching = false;\n await service.deleteDocumentation(version);\n ctx.send({ ok: true });\n } finally {\n strapi.reload.isWatching = true;\n }\n },\n\n async updateSettings(ctx: Koa.Context) {\n const pluginStore = strapi.store({ type: 'plugin', name: 'documentation' });\n\n const data = await validation.validateSettings(ctx.request.body);\n\n const config: Config = {\n restrictedAccess: Boolean(data.restrictedAccess),\n };\n\n if (data.password) {\n config.password = await bcrypt.hash(data.password, 10);\n }\n\n await pluginStore.set({ key: 'config', value: config });\n\n return ctx.send({ ok: true });\n },\n};\n"],"names":["validation","validateSettings","validateYupSchema","yup","object","shape","restrictedAccess","boolean","password","string","min","matches","when","value","initSchema","required","getInfos","ctx","docService","getService","docVersions","getDocumentationVersions","documentationAccess","getDocumentationAccess","send","currentVersion","getDocumentationVersion","prefix","err","strapi","log","error","badRequest","index","next","major","minor","patch","params","version","extensionsDir","config","environment","dirs","dist","extensions","app","openAPISpecsPath","path","join","documentation","fs","readFileSync","layout","default","filledLayout","_","template","backendUrl","server","url","spec","JSON","stringify","parse","layoutPath","resolve","ensureFile","writeFile","basename","staticFolder","koaStatic","e","loginView","cheerio","require","query","toString","actionUrl","$","load","text","isEmpty","html","login","body","request","hash","store","type","name","key","get","isValid","bcrypt","compare","querystring","session","logged","redirect","regenerateDoc","service","documentationVersions","map","el","includes","reload","isWatching","generateFullDoc","ok","deleteDoc","deleteDocumentation","updateSettings","pluginStore","data","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,YAAAA,GAAAA,CAAIO,IAAI,CAAC;gBAAEqF,EAAAA,EAAI;AAAK,aAAA,CAAA;QACtB,CAAA,QAAU;YACRhF,MAAAA,CAAO6E,MAAM,CAACC,UAAU,GAAG,IAAA;AAC7B,QAAA;AACF,IAAA,CAAA;AAEA,IAAA,MAAMK,gBAAe/F,GAAgB,EAAA;QACnC,MAAMgG,WAAAA,GAAcpF,MAAAA,CAAO2D,KAAK,CAAC;YAAEC,IAAAA,EAAM,QAAA;YAAUC,IAAAA,EAAM;AAAgB,SAAA,CAAA;QAEzE,MAAMwB,IAAAA,GAAO,MAAMlH,UAAAA,CAAWC,gBAAgB,CAACgB,GAAAA,CAAIqE,OAAO,CAACD,IAAI,CAAA;AAE/D,QAAA,MAAM5C,MAAAA,GAAiB;YACrBnC,gBAAAA,EAAkB6G,OAAAA,CAAQD,KAAK5G,gBAAgB;AACjD,SAAA;QAEA,IAAI4G,IAAAA,CAAK1G,QAAQ,EAAE;YACjBiC,MAAAA,CAAOjC,QAAQ,GAAG,MAAMsF,MAAAA,CAAOP,IAAI,CAAC2B,IAAAA,CAAK1G,QAAQ,EAAE,EAAA,CAAA;AACrD,QAAA;QAEA,MAAMyG,WAAAA,CAAYG,GAAG,CAAC;YAAEzB,GAAAA,EAAK,QAAA;YAAU9E,KAAAA,EAAO4B;AAAO,SAAA,CAAA;QAErD,OAAOxB,GAAAA,CAAIO,IAAI,CAAC;YAAEqF,EAAAA,EAAI;AAAK,SAAA,CAAA;AAC7B,IAAA;AACF,CAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"documentation.mjs","sources":["../../../server/src/controllers/documentation.ts"],"sourcesContent":["import path from 'path';\nimport bcrypt from 'bcryptjs';\nimport fs from 'fs-extra';\nimport _ from 'lodash';\nimport koaStatic from 'koa-static';\nimport { yup, validateYupSchema } from '@strapi/utils';\n\nimport type Koa from 'koa';\nimport type {} from 'koa-body';\n\nimport { getService } from '../utils';\nimport type { Config } from '../types';\n\nconst validation = {\n validateSettings: validateYupSchema(\n yup.object().shape({\n restrictedAccess: yup.boolean(),\n password: yup\n .string()\n .min(8)\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/[a-z]/, '${path} must contain at least one lowercase character')\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/[A-Z]/, '${path} must contain at least one uppercase character')\n // eslint-disable-next-line no-template-curly-in-string -- Yup interpolates ${path} at validation time.\n .matches(/\\d/, '${path} must contain at least one number')\n .when('restrictedAccess', (value, initSchema) => {\n return value ? initSchema.required('password is required') : initSchema;\n }),\n })\n ),\n};\n\nexport default {\n async getInfos(ctx: Koa.Context) {\n try {\n const docService = getService('documentation');\n const docVersions = docService.getDocumentationVersions();\n const documentationAccess = await docService.getDocumentationAccess();\n\n ctx.send({\n docVersions,\n currentVersion: docService.getDocumentationVersion(),\n prefix: '/documentation',\n documentationAccess,\n });\n } catch (err) {\n strapi.log.error(err);\n ctx.badRequest();\n }\n },\n\n async index(ctx: Koa.Context, next: Koa.Next) {\n try {\n /**\n * We don't expose the specs using koa-static or something else due to security reasons.\n * That's why, we need to read the file localy and send the specs through it when we serve the Swagger UI.\n */\n const { major, minor, patch } = ctx.params;\n const version =\n major && minor && patch\n ? `${major}.${minor}.${patch}`\n : getService('documentation').getDocumentationVersion();\n\n const extensionsDir =\n strapi.config.environment === 'production'\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n\n const openAPISpecsPath = path.join(\n extensionsDir,\n 'documentation',\n 'documentation',\n version,\n 'full_documentation.json'\n );\n\n try {\n const documentation = fs.readFileSync(openAPISpecsPath, 'utf8');\n\n const layout = (await import('../public/index.html')).default;\n\n const filledLayout = _.template(layout)({\n backendUrl: strapi.config.server.url,\n spec: JSON.stringify(JSON.parse(documentation)),\n });\n\n try {\n const layoutPath = path.resolve(extensionsDir, 'documentation', 'public', 'index.html');\n await fs.ensureFile(layoutPath);\n await fs.writeFile(layoutPath, filledLayout);\n\n // Serve the file.\n ctx.url = path.basename(`${ctx.url}/index.html`);\n\n try {\n const staticFolder = path.resolve(extensionsDir, 'documentation', 'public');\n return koaStatic(staticFolder)(ctx, next);\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n },\n\n async loginView(ctx: Koa.Context, next: Koa.Next) {\n // lazy require cheerio\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const cheerio = require('cheerio');\n\n const { error } = ctx.query;\n\n try {\n const layout = (await import('../public/login.html')).default;\n\n const filledLayout = _.template(layout.toString())({\n actionUrl: `${strapi.config.server.url}/documentation/login`,\n });\n\n const $ = cheerio.load(filledLayout);\n\n $('.error').text(_.isEmpty(error) ? '' : 'Wrong password...');\n\n try {\n const layoutPath = path.resolve(\n strapi.dirs.app.extensions,\n 'documentation',\n 'public',\n 'login.html'\n );\n await fs.ensureFile(layoutPath);\n await fs.writeFile(layoutPath, $.html());\n\n ctx.url = path.basename(`${ctx.url}/login.html`);\n\n try {\n const staticFolder = path.resolve(strapi.dirs.app.extensions, 'documentation', 'public');\n return koaStatic(staticFolder)(ctx, next);\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n } catch (e) {\n strapi.log.error(e);\n }\n },\n\n async login(ctx: Koa.Context) {\n const {\n body: { password },\n } = ctx.request;\n\n const { password: hash } = (await strapi\n .store({ type: 'plugin', name: 'documentation', key: 'config' })\n .get()) as { password?: string };\n\n // A missing stored hash or a missing submitted password counts as a wrong password\n const isValid =\n typeof password === 'string' && typeof hash === 'string'\n ? await bcrypt.compare(password, hash)\n : false;\n\n let querystring = '?error=password';\n\n if (isValid && ctx.session) {\n ctx.session.documentation = {\n logged: true,\n };\n\n querystring = '';\n }\n\n ctx.redirect(`${strapi.config.server.url}/documentation${querystring}`);\n },\n\n async regenerateDoc(ctx: Koa.Context) {\n const { version } = ctx.request.body;\n\n const service = getService('documentation');\n\n const documentationVersions = service.getDocumentationVersions().map((el) => el.version);\n\n if (_.isEmpty(version)) {\n return ctx.badRequest('Please provide a version.');\n }\n\n if (!documentationVersions.includes(version)) {\n return ctx.badRequest('The version you are trying to generate does not exist.');\n }\n\n try {\n strapi.reload.isWatching = false;\n await service.generateFullDoc(version);\n ctx.send({ ok: true });\n } finally {\n strapi.reload.isWatching = true;\n }\n },\n\n async deleteDoc(ctx: Koa.Context) {\n const { version } = ctx.params;\n\n const service = getService('documentation');\n\n const documentationVersions = service.getDocumentationVersions().map((el) => el.version);\n\n if (_.isEmpty(version)) {\n return ctx.badRequest('Please provide a version.');\n }\n\n if (!documentationVersions.includes(version)) {\n return ctx.badRequest('The version you are trying to delete does not exist.');\n }\n\n try {\n strapi.reload.isWatching = false;\n await service.deleteDocumentation(version);\n ctx.send({ ok: true });\n } finally {\n strapi.reload.isWatching = true;\n }\n },\n\n async updateSettings(ctx: Koa.Context) {\n const pluginStore = strapi.store({ type: 'plugin', name: 'documentation' });\n\n const data = await validation.validateSettings(ctx.request.body);\n\n const config: Config = {\n restrictedAccess: Boolean(data.restrictedAccess),\n };\n\n if (data.password) {\n config.password = await bcrypt.hash(data.password, 10);\n }\n\n await pluginStore.set({ key: 'config', value: config });\n\n return ctx.send({ ok: true });\n },\n};\n"],"names":["validation","validateSettings","validateYupSchema","yup","object","shape","restrictedAccess","boolean","password","string","min","matches","when","value","initSchema","required","getInfos","ctx","docService","getService","docVersions","getDocumentationVersions","documentationAccess","getDocumentationAccess","send","currentVersion","getDocumentationVersion","prefix","err","strapi","log","error","badRequest","index","next","major","minor","patch","params","version","extensionsDir","config","environment","dirs","dist","extensions","app","openAPISpecsPath","path","join","documentation","fs","readFileSync","layout","default","filledLayout","_","template","backendUrl","server","url","spec","JSON","stringify","parse","layoutPath","resolve","ensureFile","writeFile","basename","staticFolder","koaStatic","e","loginView","cheerio","require","query","toString","actionUrl","$","load","text","isEmpty","html","login","body","request","hash","store","type","name","key","get","isValid","bcrypt","compare","querystring","session","logged","redirect","regenerateDoc","service","documentationVersions","map","el","includes","reload","isWatching","generateFullDoc","ok","deleteDoc","deleteDocumentation","updateSettings","pluginStore","data","Boolean","set"],"mappings":";;;;;;;;AAaA,MAAMA,UAAAA,GAAa;AACjBC,IAAAA,gBAAAA,EAAkBC,iBAAAA,CAChBC,GAAAA,CAAIC,MAAM,EAAA,CAAGC,KAAK,CAAC;AACjBC,QAAAA,gBAAAA,EAAkBH,IAAII,OAAO,EAAA;AAC7BC,QAAAA,QAAAA,EAAUL,IACPM,MAAM,EAAA,CACNC,GAAG,CAAC,EACL;SACCC,OAAO,CAAC,OAAA,EAAS,uDAAA,CAClB;SACCA,OAAO,CAAC,OAAA,EAAS,uDAAA,CAClB;AACCA,SAAAA,OAAO,CAAC,IAAA,EAAM,0CAAA,CAAA,CACdC,IAAI,CAAC,kBAAA,EAAoB,CAACC,KAAAA,EAAOC,UAAAA,GAAAA;AAChC,YAAA,OAAOD,KAAAA,GAAQC,UAAAA,CAAWC,QAAQ,CAAC,sBAAA,CAAA,GAA0BD,UAAAA;AAC/D,QAAA,CAAA;AACJ,KAAA,CAAA;AAEJ,CAAA;AAEA,oBAAe;AACb,IAAA,MAAME,UAASC,GAAgB,EAAA;QAC7B,IAAI;AACF,YAAA,MAAMC,aAAaC,UAAAA,CAAW,eAAA,CAAA;YAC9B,MAAMC,WAAAA,GAAcF,WAAWG,wBAAwB,EAAA;YACvD,MAAMC,mBAAAA,GAAsB,MAAMJ,UAAAA,CAAWK,sBAAsB,EAAA;AAEnEN,YAAAA,GAAAA,CAAIO,IAAI,CAAC;AACPJ,gBAAAA,WAAAA;AACAK,gBAAAA,cAAAA,EAAgBP,WAAWQ,uBAAuB,EAAA;gBAClDC,MAAAA,EAAQ,gBAAA;AACRL,gBAAAA;AACF,aAAA,CAAA;AACF,QAAA,CAAA,CAAE,OAAOM,GAAAA,EAAK;YACZC,MAAAA,CAAOC,GAAG,CAACC,KAAK,CAACH,G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16
16
|
const createService = ({ strapi })=>{
|
|
17
17
|
const config = strapi.config.get('plugin::documentation');
|
|
18
|
-
const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation.getPluginsThatNeedDocumentation(config);
|
|
18
|
+
const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation.getPluginsThatNeedDocumentation(strapi, config);
|
|
19
19
|
const overrideService = utils.getService('override');
|
|
20
20
|
return {
|
|
21
21
|
getDocumentationVersion () {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentation.js","sources":["../../../server/src/services/documentation.ts"],"sourcesContent":["import path from 'path';\nimport fs from 'fs-extra';\nimport { produce } from 'immer';\nimport type { Core } from '@strapi/types';\n\nimport { builApiEndpointPath, buildComponentSchema, getRelationTargetSchemaNames } from './helpers';\nimport { getPluginsThatNeedDocumentation } from './utils/get-plugins-that-need-documentation';\nimport { getService } from '../utils';\n\nimport type { Config, PluginConfig } from '../types';\n\nexport type Version = {\n version: string;\n generatedDate: string;\n url: string;\n};\n\nexport type DocumentationService = ReturnType<typeof createService>;\n\nconst createService = ({ strapi }: { strapi: Core.Strapi }) => {\n const config = strapi.config.get('plugin::documentation') as PluginConfig;\n const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation(config);\n const overrideService = getService('override');\n\n return {\n getDocumentationVersion() {\n return config.info.version;\n },\n\n getFullDocumentationPath() {\n // In production, documentation files live under dist/src/extensions/\n // after the build step. Use dist.extensions for reading.\n const extensionsDir =\n strapi.config.environment === 'production'\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n\n return path.join(extensionsDir, 'documentation', 'documentation');\n },\n\n getDocumentationVersions(): Version[] {\n return fs\n .readdirSync(this.getFullDocumentationPath())\n .map((version) => {\n try {\n const filePath = path.resolve(\n this.getFullDocumentationPath(),\n version,\n 'full_documentation.json'\n );\n\n const doc = JSON.parse(fs.readFileSync(filePath).toString());\n\n const generatedDate = doc.info['x-generation-date'];\n\n return { version, generatedDate, url: '' };\n } catch {\n return null;\n }\n })\n .filter((x) => x) as Version[];\n },\n\n /**\n * Returns settings stored in core-store\n */\n async getDocumentationAccess() {\n const { restrictedAccess } = (await strapi.store!({\n environment: '',\n type: 'plugin',\n name: 'documentation',\n key: 'config',\n }).get()) as Config;\n\n return { restrictedAccess };\n },\n\n getApiDocumentationPath(api: { name: string; getter: string }) {\n const isProduction = strapi.config.environment === 'production';\n\n if (api.getter === 'plugin') {\n const extensionsDir = isProduction\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n return path.join(extensionsDir, api.name, 'documentation');\n }\n\n const apiDir = isProduction ? strapi.dirs.dist.api : strapi.dirs.app.api;\n return path.join(apiDir, api.name, 'documentation');\n },\n\n async deleteDocumentation(version: string) {\n const apis = this.getPluginAndApiInfo();\n for (const api of apis) {\n await fs.remove(path.join(this.getApiDocumentationPath(api), version));\n }\n\n await fs.remove(path.join(this.getFullDocumentationPath(), version));\n },\n\n getPluginAndApiInfo() {\n const pluginsToDocument = pluginsThatNeedDocumentation.map((plugin) => {\n return {\n name: plugin,\n getter: 'plugin',\n ctNames: Object.keys(strapi.plugin(plugin).contentTypes),\n };\n });\n\n const apisToDocument = Object.keys(strapi.apis).map((api) => {\n return {\n name: api,\n getter: 'api',\n ctNames: Object.keys(strapi.api(api).contentTypes),\n };\n });\n\n return [...apisToDocument, ...pluginsToDocument];\n },\n\n /**\n * @description - Creates the Swagger json files\n */\n async generateFullDoc(versionOpt?: string) {\n const version = versionOpt ?? this.getDocumentationVersion();\n\n const apis = this.getPluginAndApiInfo();\n const apisThatNeedGeneratedDocumentation = apis.filter(\n ({ name }) => !overrideService.isEnabled(name)\n );\n\n // Initialize the generated documentation with defaults\n const generatedDocumentation = await produce(config, async (draft) => {\n if (draft.servers?.length === 0) {\n // When no servers found set the defaults\n const serverUrl = strapi.config.get('server.absoluteUrl');\n const apiPath = strapi.config.get('api.rest.prefix');\n draft.servers = [\n {\n url: `${serverUrl}${apiPath}`,\n description: 'Development server',\n },\n ];\n }\n\n if (!draft.components) {\n draft.components = {};\n }\n\n // Set the generated date\n draft.info['x-generation-date'] = new Date().toISOString();\n // Set the plugins that need documentation\n draft['x-strapi-config'].plugins = pluginsThatNeedDocumentation;\n\n // Delete the mutateDocumentation key from the config so it doesn't end up in the spec\n delete draft['x-strapi-config'].mutateDocumentation;\n\n const relationTargetSchemaNames = new Map(\n apisThatNeedGeneratedDocumentation.flatMap((api) => [\n ...getRelationTargetSchemaNames(api),\n ])\n );\n\n // Generate the documentation for each api and update the generatedDocumentation\n for (const api of apisThatNeedGeneratedDocumentation) {\n const newApiPath = builApiEndpointPath(api);\n const generatedSchemas = buildComponentSchema(api, relationTargetSchemaNames);\n\n if (generatedSchemas) {\n draft.components.schemas = { ...draft.components.schemas, ...generatedSchemas };\n }\n\n if (newApiPath) {\n draft.paths = { ...draft.paths, ...newApiPath };\n }\n }\n\n // When overrides are present update the generatedDocumentation\n if (overrideService.registeredOverrides.length > 0) {\n overrideService.registeredOverrides.forEach((override: Partial<PluginConfig>) => {\n // Only run the overrrides when no override version is provided,\n // or when the generated documentation version matches the override version\n if (!override?.info?.version || override.info.version === version) {\n if (override.tags) {\n // Merge override tags with the generated tags\n draft.tags = draft.tags || [];\n draft.tags.push(...override.tags);\n }\n\n if (override.paths) {\n // Merge override paths with the generated paths\n // The override will add a new path or replace the value of an existing path\n draft.paths = { ...draft.paths, ...override.paths };\n }\n\n if (override.components) {\n const keys = Object.keys(override.components) as Array<\n keyof typeof override.components\n >;\n\n keys.forEach((overrideKey) => {\n draft.components = draft.components || {};\n\n const overrideValue = override.components?.[overrideKey];\n const originalValue = draft.components?.[overrideKey];\n\n Object.assign(draft.components, {\n [overrideKey]: {\n ...originalValue,\n ...overrideValue,\n },\n });\n });\n }\n }\n });\n }\n });\n\n // Escape hatch, allow the user to provide a mutateDocumentation function that can alter any part of\n // the generated documentation before it is written to the file system\n const userMutatesDocumentation = config['x-strapi-config'].mutateDocumentation;\n\n const finalDocumentation = userMutatesDocumentation\n ? produce(generatedDocumentation, userMutatesDocumentation)\n : generatedDocumentation;\n\n // Get the file path for the final documentation\n const fullDocJsonPath = path.join(\n this.getFullDocumentationPath(),\n version,\n 'full_documentation.json'\n );\n // Write the documentation to the file system\n await fs.ensureFile(fullDocJsonPath);\n await fs.writeJson(fullDocJsonPath, finalDocumentation, { spaces: 2 });\n },\n };\n};\n\nexport default createService;\n"],"names":["createService","strapi","config","get","pluginsThatNeedDocumentation","getPluginsThatNeedDocumentation","overrideService","getService","getDocumentationVersion","info","version","getFullDocumentationPath","extensionsDir","environment","dirs","dist","extensions","app","path","join","getDocumentationVersions","fs","readdirSync","map","filePath","resolve","doc","JSON","parse","readFileSync","toString","generatedDate","url","filter","x","getDocumentationAccess","restrictedAccess","store","type","name","key","getApiDocumentationPath","api","isProduction","getter","apiDir","deleteDocumentation","apis","getPluginAndApiInfo","remove","pluginsToDocument","plugin","ctNames","Object","keys","contentTypes","apisToDocument","generateFullDoc","versionOpt","apisThatNeedGeneratedDocumentation","isEnabled","generatedDocumentation","produce","draft","servers","length","serverUrl","apiPath","description","components","Date","toISOString","plugins","mutateDocumentation","relationTargetSchemaNames","Map","flatMap","getRelationTargetSchemaNames","newApiPath","builApiEndpointPath","generatedSchemas","buildComponentSchema","schemas","paths","registeredOverrides","forEach","override","tags","push","overrideKey","overrideValue","originalValue","assign","userMutatesDocumentation","finalDocumentation","fullDocJsonPath","ensureFile","writeJson","spaces"],"mappings":";;;;;;;;;;;;;;;AAmBA,MAAMA,aAAAA,GAAgB,CAAC,EAAEC,MAAM,EAA2B,GAAA;AACxD,IAAA,MAAMC,MAAAA,GAASD,MAAAA,CAAOC,MAAM,CAACC,GAAG,CAAC,uBAAA,CAAA;AACjC,IAAA,MAAMC,+BAA+BC,+DAAAA,CAAgCH,MAAAA,CAAAA;AACrE,IAAA,MAAMI,kBAAkBC,gBAAAA,CAAW,UAAA,CAAA;IAEnC,OAAO;AACLC,QAAAA,uBAAAA,CAAAA,GAAAA;YACE,OA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,aAAAA,GAAgB5B,KAAAA,CAAMM,UAAU,GAAGoB,WAAAA,CAAY;AAErDpC,oCAAAA,MAAAA,CAAOuC,MAAM,CAAC7B,KAAAA,CAAMM,UAAU,EAAE;AAC9B,wCAAA,CAACoB,cAAc;AACb,4CAAA,GAAGE,aAAa;AAChB,4CAAA,GAAGD;AACL;AACF,qCAAA,CAAA;AACF,gCAAA,CAAA,CAAA;AACF,4BAAA;AACF,wBAAA;AACF,oBAAA,CAAA,CAAA;AACF,gBAAA;AACF,YAAA,CAAA,CAAA;;;AAIA,YAAA,MAAMG,wBAAAA,GAA2B3F,MAAM,CAAC,iBAAA,CAAkB,CAACuE,mBAAmB;AAE9E,YAAA,MAAMqB,kBAAAA,GAAqBD,wBAAAA,GACvB/B,aAAAA,CAAQD,sBAAAA,EAAwBgC,wBAAAA,CAAAA,GAChChC,sBAAAA;;YAGJ,MAAMkC,eAAAA,GAAkB7E,sBAAKC,IAAI,CAC/B,IAAI,CAACR,wBAAwB,IAC7BD,OAAAA,EACA,yBAAA,CAAA;;YAGF,MAAMW,mBAAAA,CAAG2E,UAAU,CAACD,eAAAA,CAAAA;AACpB,YAAA,MAAM1E,mBAAAA,CAAG4E,SAAS,CAACF,eAAAA,EAAiBD,kBAAAA,EAAoB;gBAAEI,MAAAA,EAAQ;AAAE,aAAA,CAAA;AACtE,QAAA;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"documentation.js","sources":["../../../server/src/services/documentation.ts"],"sourcesContent":["import path from 'path';\nimport fs from 'fs-extra';\nimport { produce } from 'immer';\nimport type { Core } from '@strapi/types';\n\nimport { builApiEndpointPath, buildComponentSchema, getRelationTargetSchemaNames } from './helpers';\nimport { getPluginsThatNeedDocumentation } from './utils/get-plugins-that-need-documentation';\nimport { getService } from '../utils';\n\nimport type { Config, PluginConfig } from '../types';\n\nexport type Version = {\n version: string;\n generatedDate: string;\n url: string;\n};\n\nexport type DocumentationService = ReturnType<typeof createService>;\n\nconst createService = ({ strapi }: { strapi: Core.Strapi }) => {\n const config = strapi.config.get('plugin::documentation') as PluginConfig;\n const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation(strapi, config);\n const overrideService = getService('override');\n\n return {\n getDocumentationVersion() {\n return config.info.version;\n },\n\n getFullDocumentationPath() {\n // In production, documentation files live under dist/src/extensions/\n // after the build step. Use dist.extensions for reading.\n const extensionsDir =\n strapi.config.environment === 'production'\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n\n return path.join(extensionsDir, 'documentation', 'documentation');\n },\n\n getDocumentationVersions(): Version[] {\n return fs\n .readdirSync(this.getFullDocumentationPath())\n .map((version) => {\n try {\n const filePath = path.resolve(\n this.getFullDocumentationPath(),\n version,\n 'full_documentation.json'\n );\n\n const doc = JSON.parse(fs.readFileSync(filePath).toString());\n\n const generatedDate = doc.info['x-generation-date'];\n\n return { version, generatedDate, url: '' };\n } catch {\n return null;\n }\n })\n .filter((x) => x) as Version[];\n },\n\n /**\n * Returns settings stored in core-store\n */\n async getDocumentationAccess() {\n const { restrictedAccess } = (await strapi.store!({\n environment: '',\n type: 'plugin',\n name: 'documentation',\n key: 'config',\n }).get()) as Config;\n\n return { restrictedAccess };\n },\n\n getApiDocumentationPath(api: { name: string; getter: string }) {\n const isProduction = strapi.config.environment === 'production';\n\n if (api.getter === 'plugin') {\n const extensionsDir = isProduction\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n return path.join(extensionsDir, api.name, 'documentation');\n }\n\n const apiDir = isProduction ? strapi.dirs.dist.api : strapi.dirs.app.api;\n return path.join(apiDir, api.name, 'documentation');\n },\n\n async deleteDocumentation(version: string) {\n const apis = this.getPluginAndApiInfo();\n for (const api of apis) {\n await fs.remove(path.join(this.getApiDocumentationPath(api), version));\n }\n\n await fs.remove(path.join(this.getFullDocumentationPath(), version));\n },\n\n getPluginAndApiInfo() {\n const pluginsToDocument = pluginsThatNeedDocumentation.map((plugin) => {\n return {\n name: plugin,\n getter: 'plugin',\n ctNames: Object.keys(strapi.plugin(plugin).contentTypes),\n };\n });\n\n const apisToDocument = Object.keys(strapi.apis).map((api) => {\n return {\n name: api,\n getter: 'api',\n ctNames: Object.keys(strapi.api(api).contentTypes),\n };\n });\n\n return [...apisToDocument, ...pluginsToDocument];\n },\n\n /**\n * @description - Creates the Swagger json files\n */\n async generateFullDoc(versionOpt?: string) {\n const version = versionOpt ?? this.getDocumentationVersion();\n\n const apis = this.getPluginAndApiInfo();\n const apisThatNeedGeneratedDocumentation = apis.filter(\n ({ name }) => !overrideService.isEnabled(name)\n );\n\n // Initialize the generated documentation with defaults\n const generatedDocumentation = await produce(config, async (draft) => {\n if (draft.servers?.length === 0) {\n // When no servers found set the defaults\n const serverUrl = strapi.config.get('server.absoluteUrl');\n const apiPath = strapi.config.get('api.rest.prefix');\n draft.servers = [\n {\n url: `${serverUrl}${apiPath}`,\n description: 'Development server',\n },\n ];\n }\n\n if (!draft.components) {\n draft.components = {};\n }\n\n // Set the generated date\n draft.info['x-generation-date'] = new Date().toISOString();\n // Set the plugins that need documentation\n draft['x-strapi-config'].plugins = pluginsThatNeedDocumentation;\n\n // Delete the mutateDocumentation key from the config so it doesn't end up in the spec\n delete draft['x-strapi-config'].mutateDocumentation;\n\n const relationTargetSchemaNames = new Map(\n apisThatNeedGeneratedDocumentation.flatMap((api) => [\n ...getRelationTargetSchemaNames(api),\n ])\n );\n\n // Generate the documentation for each api and update the generatedDocumentation\n for (const api of apisThatNeedGeneratedDocumentation) {\n const newApiPath = builApiEndpointPath(api);\n const generatedSchemas = buildComponentSchema(api, relationTargetSchemaNames);\n\n if (generatedSchemas) {\n draft.components.schemas = { ...draft.components.schemas, ...generatedSchemas };\n }\n\n if (newApiPath) {\n draft.paths = { ...draft.paths, ...newApiPath };\n }\n }\n\n // When overrides are present update the generatedDocumentation\n if (overrideService.registeredOverrides.length > 0) {\n overrideService.registeredOverrides.forEach((override: Partial<PluginConfig>) => {\n // Only run the overrrides when no override version is provided,\n // or when the generated documentation version matches the override version\n if (!override?.info?.version || override.info.version === version) {\n if (override.tags) {\n // Merge override tags with the generated tags\n draft.tags = draft.tags || [];\n draft.tags.push(...override.tags);\n }\n\n if (override.paths) {\n // Merge override paths with the generated paths\n // The override will add a new path or replace the value of an existing path\n draft.paths = { ...draft.paths, ...override.paths };\n }\n\n if (override.components) {\n const keys = Object.keys(override.components) as Array<\n keyof typeof override.components\n >;\n\n keys.forEach((overrideKey) => {\n draft.components = draft.components || {};\n\n const overrideValue = override.components?.[overrideKey];\n const originalValue = draft.components?.[overrideKey];\n\n Object.assign(draft.components, {\n [overrideKey]: {\n ...originalValue,\n ...overrideValue,\n },\n });\n });\n }\n }\n });\n }\n });\n\n // Escape hatch, allow the user to provide a mutateDocumentation function that can alter any part of\n // the generated documentation before it is written to the file system\n const userMutatesDocumentation = config['x-strapi-config'].mutateDocumentation;\n\n const finalDocumentation = userMutatesDocumentation\n ? produce(generatedDocumentation, userMutatesDocumentation)\n : generatedDocumentation;\n\n // Get the file path for the final documentation\n const fullDocJsonPath = path.join(\n this.getFullDocumentationPath(),\n version,\n 'full_documentation.json'\n );\n // Write the documentation to the file system\n await fs.ensureFile(fullDocJsonPath);\n await fs.writeJson(fullDocJsonPath, finalDocumentation, { spaces: 2 });\n },\n };\n};\n\nexport default createService;\n"],"names":["createService","strapi","config","get","pluginsThatNeedDocumentation","getPluginsThatNeedDocumentation","overrideService","getService","getDocumentationVersion","info","version","getFullDocumentationPath","extensionsDir","environment","dirs","dist","extensions","app","path","join","getDocumentationVersions","fs","readdirSync","map","filePath","resolve","doc","JSON","parse","readFileSync","toString","generatedDate","url","filter","x","getDocumentationAccess","restrictedAccess","store","type","name","key","getApiDocumentationPath","api","isProduction","getter","apiDir","deleteDocumentation","apis","getPluginAndApiInfo","remove","pluginsToDocument","plugin","ctNames","Object","keys","contentTypes","apisToDocument","generateFullDoc","versionOpt","apisThatNeedGeneratedDocumentation","isEnabled","generatedDocumentation","produce","draft","servers","length","serverUrl","apiPath","description","components","Date","toISOString","plugins","mutateDocumentation","relationTargetSchemaNames","Map","flatMap","getRelationTargetSchemaNames","newApiPath","builApiEndpointPath","generatedSchemas","buildComponentSchema","schemas","paths","registeredOverrides","forEach","override","tags","push","overrideKey","overrideValue","originalValue","assign","userMutatesDocumentation","finalDocumentation","fullDocJsonPath","ensureFile","writeJson","spaces"],"mappings":";;;;;;;;;;;;;;;AAmBA,MAAMA,aAAAA,GAAgB,CAAC,EAAEC,MAAM,EAA2B,GAAA;AACxD,IAAA,MAAMC,MAAAA,GAASD,MAAAA,CAAOC,MAAM,CAACC,GAAG,CAAC,uBAAA,CAAA;IACjC,MAAMC,4BAAAA,GAA+BC,gEAAgCJ,MAAAA,EAAQC,MAAAA,CAAAA;AAC7E,IAAA,MAAMI,kBAAkBC,gBAAAA,CAAW,UAAA,CAAA;IAEnC,OAAO;AACLC,QAAAA,uBAAAA,CAAAA,GAAAA;YACE,OAAON,MAAAA,CAAOO,IAAI,CAACC,OAAO;AAC5B,QAAA,CAAA;AAEAC,QAAAA,wBAAAA,CAAAA,GAAAA;;;AAGE,YAAA,MAAMC,gBACJX,MAAAA,CAAOC,MAAM,CAACW,WAAW,KAAK,eAC1BZ,MAAAA,CAAOa,IAAI,CAACC,IAAI,CAACC,UAAU,GAC3Bf,MAAAA,CAAOa,IAAI,CAACG,GAAG,CAACD,UAAU;AAEhC,YAAA,OAAOE,qBAAAA,CAAKC,IAAI,CAACP,aAAAA,EAAe,eAAA,EAAiB,eAAA,CAAA;AACnD,QAAA,CAAA;AAEAQ,QAAAA,wBAAAA,CAAAA,GAAAA;YACE,OAAOC,mBAAAA,CACJC,WAAW,CAAC,IAAI,CAACX,wBAAwB,EAAA,CAAA,CACzCY,GAAG,CAAC,CAACb,OAAAA,GAAAA;gBACJ,IAAI;oBACF,MAAMc,QAAAA,GAAWN,sBAAKO,OAAO,CAC3B,IAAI,CAACd,wBAAwB,IAC7BD,OAAAA,EACA,yBAAA,CAAA;oBAGF,MAAMgB,GAAAA,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mBAAAA,CAAG2E,UAAU,CAACD,eAAAA,CAAAA;AACpB,YAAA,MAAM1E,mBAAAA,CAAG4E,SAAS,CAACF,eAAAA,EAAiBD,kBAAAA,EAAoB;gBAAEI,MAAAA,EAAQ;AAAE,aAAA,CAAA;AACtE,QAAA;AACF,KAAA;AACF;;;;"}
|
|
@@ -8,7 +8,7 @@ import { getService } from '../utils.mjs';
|
|
|
8
8
|
|
|
9
9
|
const createService = ({ strapi })=>{
|
|
10
10
|
const config = strapi.config.get('plugin::documentation');
|
|
11
|
-
const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation(config);
|
|
11
|
+
const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation(strapi, config);
|
|
12
12
|
const overrideService = getService('override');
|
|
13
13
|
return {
|
|
14
14
|
getDocumentationVersion () {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentation.mjs","sources":["../../../server/src/services/documentation.ts"],"sourcesContent":["import path from 'path';\nimport fs from 'fs-extra';\nimport { produce } from 'immer';\nimport type { Core } from '@strapi/types';\n\nimport { builApiEndpointPath, buildComponentSchema, getRelationTargetSchemaNames } from './helpers';\nimport { getPluginsThatNeedDocumentation } from './utils/get-plugins-that-need-documentation';\nimport { getService } from '../utils';\n\nimport type { Config, PluginConfig } from '../types';\n\nexport type Version = {\n version: string;\n generatedDate: string;\n url: string;\n};\n\nexport type DocumentationService = ReturnType<typeof createService>;\n\nconst createService = ({ strapi }: { strapi: Core.Strapi }) => {\n const config = strapi.config.get('plugin::documentation') as PluginConfig;\n const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation(config);\n const overrideService = getService('override');\n\n return {\n getDocumentationVersion() {\n return config.info.version;\n },\n\n getFullDocumentationPath() {\n // In production, documentation files live under dist/src/extensions/\n // after the build step. Use dist.extensions for reading.\n const extensionsDir =\n strapi.config.environment === 'production'\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n\n return path.join(extensionsDir, 'documentation', 'documentation');\n },\n\n getDocumentationVersions(): Version[] {\n return fs\n .readdirSync(this.getFullDocumentationPath())\n .map((version) => {\n try {\n const filePath = path.resolve(\n this.getFullDocumentationPath(),\n version,\n 'full_documentation.json'\n );\n\n const doc = JSON.parse(fs.readFileSync(filePath).toString());\n\n const generatedDate = doc.info['x-generation-date'];\n\n return { version, generatedDate, url: '' };\n } catch {\n return null;\n }\n })\n .filter((x) => x) as Version[];\n },\n\n /**\n * Returns settings stored in core-store\n */\n async getDocumentationAccess() {\n const { restrictedAccess } = (await strapi.store!({\n environment: '',\n type: 'plugin',\n name: 'documentation',\n key: 'config',\n }).get()) as Config;\n\n return { restrictedAccess };\n },\n\n getApiDocumentationPath(api: { name: string; getter: string }) {\n const isProduction = strapi.config.environment === 'production';\n\n if (api.getter === 'plugin') {\n const extensionsDir = isProduction\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n return path.join(extensionsDir, api.name, 'documentation');\n }\n\n const apiDir = isProduction ? strapi.dirs.dist.api : strapi.dirs.app.api;\n return path.join(apiDir, api.name, 'documentation');\n },\n\n async deleteDocumentation(version: string) {\n const apis = this.getPluginAndApiInfo();\n for (const api of apis) {\n await fs.remove(path.join(this.getApiDocumentationPath(api), version));\n }\n\n await fs.remove(path.join(this.getFullDocumentationPath(), version));\n },\n\n getPluginAndApiInfo() {\n const pluginsToDocument = pluginsThatNeedDocumentation.map((plugin) => {\n return {\n name: plugin,\n getter: 'plugin',\n ctNames: Object.keys(strapi.plugin(plugin).contentTypes),\n };\n });\n\n const apisToDocument = Object.keys(strapi.apis).map((api) => {\n return {\n name: api,\n getter: 'api',\n ctNames: Object.keys(strapi.api(api).contentTypes),\n };\n });\n\n return [...apisToDocument, ...pluginsToDocument];\n },\n\n /**\n * @description - Creates the Swagger json files\n */\n async generateFullDoc(versionOpt?: string) {\n const version = versionOpt ?? this.getDocumentationVersion();\n\n const apis = this.getPluginAndApiInfo();\n const apisThatNeedGeneratedDocumentation = apis.filter(\n ({ name }) => !overrideService.isEnabled(name)\n );\n\n // Initialize the generated documentation with defaults\n const generatedDocumentation = await produce(config, async (draft) => {\n if (draft.servers?.length === 0) {\n // When no servers found set the defaults\n const serverUrl = strapi.config.get('server.absoluteUrl');\n const apiPath = strapi.config.get('api.rest.prefix');\n draft.servers = [\n {\n url: `${serverUrl}${apiPath}`,\n description: 'Development server',\n },\n ];\n }\n\n if (!draft.components) {\n draft.components = {};\n }\n\n // Set the generated date\n draft.info['x-generation-date'] = new Date().toISOString();\n // Set the plugins that need documentation\n draft['x-strapi-config'].plugins = pluginsThatNeedDocumentation;\n\n // Delete the mutateDocumentation key from the config so it doesn't end up in the spec\n delete draft['x-strapi-config'].mutateDocumentation;\n\n const relationTargetSchemaNames = new Map(\n apisThatNeedGeneratedDocumentation.flatMap((api) => [\n ...getRelationTargetSchemaNames(api),\n ])\n );\n\n // Generate the documentation for each api and update the generatedDocumentation\n for (const api of apisThatNeedGeneratedDocumentation) {\n const newApiPath = builApiEndpointPath(api);\n const generatedSchemas = buildComponentSchema(api, relationTargetSchemaNames);\n\n if (generatedSchemas) {\n draft.components.schemas = { ...draft.components.schemas, ...generatedSchemas };\n }\n\n if (newApiPath) {\n draft.paths = { ...draft.paths, ...newApiPath };\n }\n }\n\n // When overrides are present update the generatedDocumentation\n if (overrideService.registeredOverrides.length > 0) {\n overrideService.registeredOverrides.forEach((override: Partial<PluginConfig>) => {\n // Only run the overrrides when no override version is provided,\n // or when the generated documentation version matches the override version\n if (!override?.info?.version || override.info.version === version) {\n if (override.tags) {\n // Merge override tags with the generated tags\n draft.tags = draft.tags || [];\n draft.tags.push(...override.tags);\n }\n\n if (override.paths) {\n // Merge override paths with the generated paths\n // The override will add a new path or replace the value of an existing path\n draft.paths = { ...draft.paths, ...override.paths };\n }\n\n if (override.components) {\n const keys = Object.keys(override.components) as Array<\n keyof typeof override.components\n >;\n\n keys.forEach((overrideKey) => {\n draft.components = draft.components || {};\n\n const overrideValue = override.components?.[overrideKey];\n const originalValue = draft.components?.[overrideKey];\n\n Object.assign(draft.components, {\n [overrideKey]: {\n ...originalValue,\n ...overrideValue,\n },\n });\n });\n }\n }\n });\n }\n });\n\n // Escape hatch, allow the user to provide a mutateDocumentation function that can alter any part of\n // the generated documentation before it is written to the file system\n const userMutatesDocumentation = config['x-strapi-config'].mutateDocumentation;\n\n const finalDocumentation = userMutatesDocumentation\n ? produce(generatedDocumentation, userMutatesDocumentation)\n : generatedDocumentation;\n\n // Get the file path for the final documentation\n const fullDocJsonPath = path.join(\n this.getFullDocumentationPath(),\n version,\n 'full_documentation.json'\n );\n // Write the documentation to the file system\n await fs.ensureFile(fullDocJsonPath);\n await fs.writeJson(fullDocJsonPath, finalDocumentation, { spaces: 2 });\n },\n };\n};\n\nexport default createService;\n"],"names":["createService","strapi","config","get","pluginsThatNeedDocumentation","getPluginsThatNeedDocumentation","overrideService","getService","getDocumentationVersion","info","version","getFullDocumentationPath","extensionsDir","environment","dirs","dist","extensions","app","path","join","getDocumentationVersions","fs","readdirSync","map","filePath","resolve","doc","JSON","parse","readFileSync","toString","generatedDate","url","filter","x","getDocumentationAccess","restrictedAccess","store","type","name","key","getApiDocumentationPath","api","isProduction","getter","apiDir","deleteDocumentation","apis","getPluginAndApiInfo","remove","pluginsToDocument","plugin","ctNames","Object","keys","contentTypes","apisToDocument","generateFullDoc","versionOpt","apisThatNeedGeneratedDocumentation","isEnabled","generatedDocumentation","produce","draft","servers","length","serverUrl","apiPath","description","components","Date","toISOString","plugins","mutateDocumentation","relationTargetSchemaNames","Map","flatMap","getRelationTargetSchemaNames","newApiPath","builApiEndpointPath","generatedSchemas","buildComponentSchema","schemas","paths","registeredOverrides","forEach","override","tags","push","overrideKey","overrideValue","originalValue","assign","userMutatesDocumentation","finalDocumentation","fullDocJsonPath","ensureFile","writeJson","spaces"],"mappings":";;;;;;;;AAmBA,MAAMA,aAAAA,GAAgB,CAAC,EAAEC,MAAM,EAA2B,GAAA;AACxD,IAAA,MAAMC,MAAAA,GAASD,MAAAA,CA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AAC,CAACI,WAAAA,GAAAA;AACZ1B,oCAAAA,KAAAA,CAAMM,UAAU,GAAGN,KAAAA,CAAMM,UAAU,IAAI,EAAC;AAExC,oCAAA,MAAMqB,aAAAA,GAAgBJ,QAAAA,CAASjB,UAAU,GAAGoB,WAAAA,CAAY;AACxD,oCAAA,MAAME,aAAAA,GAAgB5B,KAAAA,CAAMM,UAAU,GAAGoB,WAAAA,CAAY;AAErDpC,oCAAAA,MAAAA,CAAOuC,MAAM,CAAC7B,KAAAA,CAAMM,UAAU,EAAE;AAC9B,wCAAA,CAACoB,cAAc;AACb,4CAAA,GAAGE,aAAa;AAChB,4CAAA,GAAGD;AACL;AACF,qCAAA,CAAA;AACF,gCAAA,CAAA,CAAA;AACF,4BAAA;AACF,wBAAA;AACF,oBAAA,CAAA,CAAA;AACF,gBAAA;AACF,YAAA,CAAA,CAAA;;;AAIA,YAAA,MAAMG,wBAAAA,GAA2B3F,MAAM,CAAC,iBAAA,CAAkB,CAACuE,mBAAmB;AAE9E,YAAA,MAAMqB,kBAAAA,GAAqBD,wBAAAA,GACvB/B,OAAAA,CAAQD,sBAAAA,EAAwBgC,wBAAAA,CAAAA,GAChChC,sBAAAA;;YAGJ,MAAMkC,eAAAA,GAAkB7E,KAAKC,IAAI,CAC/B,IAAI,CAACR,wBAAwB,IAC7BD,OAAAA,EACA,yBAAA,CAAA;;YAGF,MAAMW,EAAAA,CAAG2E,UAAU,CAACD,eAAAA,CAAAA;AACpB,YAAA,MAAM1E,EAAAA,CAAG4E,SAAS,CAACF,eAAAA,EAAiBD,kBAAAA,EAAoB;gBAAEI,MAAAA,EAAQ;AAAE,aAAA,CAAA;AACtE,QAAA;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"documentation.mjs","sources":["../../../server/src/services/documentation.ts"],"sourcesContent":["import path from 'path';\nimport fs from 'fs-extra';\nimport { produce } from 'immer';\nimport type { Core } from '@strapi/types';\n\nimport { builApiEndpointPath, buildComponentSchema, getRelationTargetSchemaNames } from './helpers';\nimport { getPluginsThatNeedDocumentation } from './utils/get-plugins-that-need-documentation';\nimport { getService } from '../utils';\n\nimport type { Config, PluginConfig } from '../types';\n\nexport type Version = {\n version: string;\n generatedDate: string;\n url: string;\n};\n\nexport type DocumentationService = ReturnType<typeof createService>;\n\nconst createService = ({ strapi }: { strapi: Core.Strapi }) => {\n const config = strapi.config.get('plugin::documentation') as PluginConfig;\n const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation(strapi, config);\n const overrideService = getService('override');\n\n return {\n getDocumentationVersion() {\n return config.info.version;\n },\n\n getFullDocumentationPath() {\n // In production, documentation files live under dist/src/extensions/\n // after the build step. Use dist.extensions for reading.\n const extensionsDir =\n strapi.config.environment === 'production'\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n\n return path.join(extensionsDir, 'documentation', 'documentation');\n },\n\n getDocumentationVersions(): Version[] {\n return fs\n .readdirSync(this.getFullDocumentationPath())\n .map((version) => {\n try {\n const filePath = path.resolve(\n this.getFullDocumentationPath(),\n version,\n 'full_documentation.json'\n );\n\n const doc = JSON.parse(fs.readFileSync(filePath).toString());\n\n const generatedDate = doc.info['x-generation-date'];\n\n return { version, generatedDate, url: '' };\n } catch {\n return null;\n }\n })\n .filter((x) => x) as Version[];\n },\n\n /**\n * Returns settings stored in core-store\n */\n async getDocumentationAccess() {\n const { restrictedAccess } = (await strapi.store!({\n environment: '',\n type: 'plugin',\n name: 'documentation',\n key: 'config',\n }).get()) as Config;\n\n return { restrictedAccess };\n },\n\n getApiDocumentationPath(api: { name: string; getter: string }) {\n const isProduction = strapi.config.environment === 'production';\n\n if (api.getter === 'plugin') {\n const extensionsDir = isProduction\n ? strapi.dirs.dist.extensions\n : strapi.dirs.app.extensions;\n return path.join(extensionsDir, api.name, 'documentation');\n }\n\n const apiDir = isProduction ? strapi.dirs.dist.api : strapi.dirs.app.api;\n return path.join(apiDir, api.name, 'documentation');\n },\n\n async deleteDocumentation(version: string) {\n const apis = this.getPluginAndApiInfo();\n for (const api of apis) {\n await fs.remove(path.join(this.getApiDocumentationPath(api), version));\n }\n\n await fs.remove(path.join(this.getFullDocumentationPath(), version));\n },\n\n getPluginAndApiInfo() {\n const pluginsToDocument = pluginsThatNeedDocumentation.map((plugin) => {\n return {\n name: plugin,\n getter: 'plugin',\n ctNames: Object.keys(strapi.plugin(plugin).contentTypes),\n };\n });\n\n const apisToDocument = Object.keys(strapi.apis).map((api) => {\n return {\n name: api,\n getter: 'api',\n ctNames: Object.keys(strapi.api(api).contentTypes),\n };\n });\n\n return [...apisToDocument, ...pluginsToDocument];\n },\n\n /**\n * @description - Creates the Swagger json files\n */\n async generateFullDoc(versionOpt?: string) {\n const version = versionOpt ?? this.getDocumentationVersion();\n\n const apis = this.getPluginAndApiInfo();\n const apisThatNeedGeneratedDocumentation = apis.filter(\n ({ name }) => !overrideService.isEnabled(name)\n );\n\n // Initialize the generated documentation with defaults\n const generatedDocumentation = await produce(config, async (draft) => {\n if (draft.servers?.length === 0) {\n // When no servers found set the defaults\n const serverUrl = strapi.config.get('server.absoluteUrl');\n const apiPath = strapi.config.get('api.rest.prefix');\n draft.servers = [\n {\n url: `${serverUrl}${apiPath}`,\n description: 'Development server',\n },\n ];\n }\n\n if (!draft.components) {\n draft.components = {};\n }\n\n // Set the generated date\n draft.info['x-generation-date'] = new Date().toISOString();\n // Set the plugins that need documentation\n draft['x-strapi-config'].plugins = pluginsThatNeedDocumentation;\n\n // Delete the mutateDocumentation key from the config so it doesn't end up in the spec\n delete draft['x-strapi-config'].mutateDocumentation;\n\n const relationTargetSchemaNames = new Map(\n apisThatNeedGeneratedDocumentation.flatMap((api) => [\n ...getRelationTargetSchemaNames(api),\n ])\n );\n\n // Generate the documentation for each api and update the generatedDocumentation\n for (const api of apisThatNeedGeneratedDocumentation) {\n const newApiPath = builApiEndpointPath(api);\n const generatedSchemas = buildComponentSchema(api, relationTargetSchemaNames);\n\n if (generatedSchemas) {\n draft.components.schemas = { ...draft.components.schemas, ...generatedSchemas };\n }\n\n if (newApiPath) {\n draft.paths = { ...draft.paths, ...newApiPath };\n }\n }\n\n // When overrides are present update the generatedDocumentation\n if (overrideService.registeredOverrides.length > 0) {\n overrideService.registeredOverrides.forEach((override: Partial<PluginConfig>) => {\n // Only run the overrrides when no override version is provided,\n // or when the generated documentation version matches the override version\n if (!override?.info?.version || override.info.version === version) {\n if (override.tags) {\n // Merge override tags with the generated tags\n draft.tags = draft.tags || [];\n draft.tags.push(...override.tags);\n }\n\n if (override.paths) {\n // Merge override paths with the generated paths\n // The override will add a new path or replace the value of an existing path\n draft.paths = { ...draft.paths, ...override.paths };\n }\n\n if (override.components) {\n const keys = Object.keys(override.components) as Array<\n keyof typeof override.components\n >;\n\n keys.forEach((overrideKey) => {\n draft.components = draft.components || {};\n\n const overrideValue = override.components?.[overrideKey];\n const originalValue = draft.components?.[overrideKey];\n\n Object.assign(draft.components, {\n [overrideKey]: {\n ...originalValue,\n ...overrideValue,\n },\n });\n });\n }\n }\n });\n }\n });\n\n // Escape hatch, allow the user to provide a mutateDocumentation function that can alter any part of\n // the generated documentation before it is written to the file system\n const userMutatesDocumentation = config['x-strapi-config'].mutateDocumentation;\n\n const finalDocumentation = userMutatesDocumentation\n ? produce(generatedDocumentation, userMutatesDocumentation)\n : generatedDocumentation;\n\n // Get the file path for the final documentation\n const fullDocJsonPath = path.join(\n this.getFullDocumentationPath(),\n version,\n 'full_documentation.json'\n );\n // Write the documentation to the file system\n await fs.ensureFile(fullDocJsonPath);\n await fs.writeJson(fullDocJsonPath, finalDocumentation, { spaces: 2 });\n },\n };\n};\n\nexport default createService;\n"],"names":["createService","strapi","config","get","pluginsThatNeedDocumentation","getPluginsThatNeedDocumentation","overrideService","getService","getDocumentationVersion","info","version","getFullDocumentationPath","extensionsDir","environment","dirs","dist","extensions","app","path","join","getDocumentationVersions","fs","readdirSync","map","filePath","resolve","doc","JSON","parse","readFileSync","toString","generatedDate","url","filter","x","getDocumentationAccess","restrictedAccess","store","type","name","key","getApiDocumentationPath","api","isProduction","getter","apiDir","deleteDocumentation","apis","getPluginAndApiInfo","remove","pluginsToDocument","plugin","ctNames","Object","keys","contentTypes","apisToDocument","generateFullDoc","versionOpt","apisThatNeedGeneratedDocumentation","isEnabled","generatedDocumentation","produce","draft","servers","length","serverUrl","apiPath","description","components","Date","toISOString","plugins","mutateDocumentation","relationTargetSchemaNames","Map","flatMap","getRelationTargetSchemaNames","newApiPath","builApiEndpointPath","generatedSchemas","buildComponentSchema","schemas","paths","registeredOverrides","forEach","override","tags","push","overrideKey","overrideValue","originalValue","assign","userMutatesDocumentation","finalDocumentation","fullDocJsonPath","ensureFile","writeJson","spaces"],"mappings":";;;;;;;;AAmBA,MAAMA,aAAAA,GAAgB,CAAC,EAAEC,MAAM,EAA2B,GAAA;AACxD,IAAA,MAAMC,MAAAA,GAASD,MAAAA,CAAOC,MAAM,CAACC,GAAG,CAAC,uBAAA,CAAA;IACjC,MAAMC,4BAAAA,GAA+BC,gCAAgCJ,MAAAA,EAAQC,MAAAA,CAAAA;AAC7E,IAAA,MAAMI,kBAAkBC,UAAAA,CAAW,UAAA,CAAA;IAEnC,OAAO;AACLC,QAAAA,uBAAAA,CAAAA,GAAAA;YACE,OAAON,MAAAA,CAAOO,IAAI,CAACC,OAAO;AAC5B,QAAA,CAAA;AAEAC,QAAAA,wBAAAA,CAAAA,GAAAA;;;AAGE,YAAA,MAAMC,gBACJX,MAAAA,CAAOC,MAAM,CAACW,WAAW,KAAK,eAC1BZ,MAAAA,CAAOa,IAAI,CAACC,IAAI,CAACC,UAAU,GAC3Bf,MAAAA,CAAOa,IAAI,CAACG,GAAG,CAACD,UAAU;AAEhC,YAAA,OAAOE,IAAAA,CAAKC,IAAI,CAACP,aAAAA,EAAe,eAAA,EAAiB,eAAA,CAAA;AACnD,QAAA,CAAA;AAEAQ,QAAAA,wBAAAA,CAAAA,GAAAA;YACE,OAAOC,EAAAA,CACJC,WAAW,CAAC,IAAI,CAACX,wBAAwB,EAA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AQD,sBAAAA,EAAwBgC,wBAAAA,CAAAA,GAChChC,sBAAAA;;YAGJ,MAAMkC,eAAAA,GAAkB7E,KAAKC,IAAI,CAC/B,IAAI,CAACR,wBAAwB,IAC7BD,OAAAA,EACA,yBAAA,CAAA;;YAGF,MAAMW,EAAAA,CAAG2E,UAAU,CAACD,eAAAA,CAAAA;AACpB,YAAA,MAAM1E,EAAAA,CAAG4E,SAAS,CAACF,eAAAA,EAAiBD,kBAAAA,EAAoB;gBAAEI,MAAAA,EAAQ;AAAE,aAAA,CAAA;AACtE,QAAA;AACF,KAAA;AACF;;;;"}
|
|
@@ -12,6 +12,14 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
12
12
|
|
|
13
13
|
var ___default = /*#__PURE__*/_interopDefault(_);
|
|
14
14
|
|
|
15
|
+
/**
|
|
16
|
+
* Attributes Strapi adds to content types for its own needs, hidden from the Content Manager
|
|
17
|
+
* and never accepted nor returned by the Content API, such as the position of a document in
|
|
18
|
+
* the custom order of its collection type.
|
|
19
|
+
*/ const isInternalAttribute = (attribute)=>{
|
|
20
|
+
const { visible, private: isPrivate } = attribute;
|
|
21
|
+
return visible === false && isPrivate === true;
|
|
22
|
+
};
|
|
15
23
|
const getRequiredAttributes = (allAttributes)=>{
|
|
16
24
|
const requiredAttributes = [];
|
|
17
25
|
for(const key in allAttributes){
|
|
@@ -30,7 +38,8 @@ const getRequiredAttributes = (allAttributes)=>{
|
|
|
30
38
|
* @property {object} apiInfo.routeInfo - The routes for the api
|
|
31
39
|
*
|
|
32
40
|
* @returns {object} Open API schemas
|
|
33
|
-
*/ const getAllSchemasForContentType = ({ routeInfo, attributes, uniqueName, relationTargetSchemaNames })=>{
|
|
41
|
+
*/ const getAllSchemasForContentType = ({ routeInfo, attributes: allAttributes, uniqueName, relationTargetSchemaNames })=>{
|
|
42
|
+
const attributes = ___default.default.omitBy(allAttributes, isInternalAttribute);
|
|
34
43
|
// Store response and request schemas in an object
|
|
35
44
|
let strapiComponentSchemas = {};
|
|
36
45
|
const schemas = {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-component-schema.js","sources":["../../../../server/src/services/helpers/build-component-schema.ts"],"sourcesContent":["import _ from 'lodash';\n\nimport type { OpenAPIV3 } from 'openapi-types';\nimport type { Core, Struct } from '@strapi/types';\n\nimport cleanSchemaAttributes from './utils/clean-schema-attributes';\nimport loopContentTypeNames from './utils/loop-content-type-names';\nimport pascalCase from './utils/pascal-case';\nimport { hasFindMethod } from './utils/routes';\n\nimport type { Api, ApiInfo } from '../../types';\n\nconst getRequiredAttributes = (allAttributes: Struct.SchemaAttributes) => {\n const requiredAttributes: string[] = [];\n\n for (const key in allAttributes) {\n if (allAttributes[key].required) {\n requiredAttributes.push(key);\n }\n }\n\n return requiredAttributes;\n};\n\n/**\n * @description Get all open api schema objects for a given content type\n *\n * @param {object} apiInfo\n * @property {string} apiInfo.uniqueName - Api name | Api name + Content type name\n * @property {object} apiInfo.attributes - Attributes on content type\n * @property {object} apiInfo.routeInfo - The routes for the api\n *\n * @returns {object} Open API schemas\n */\nconst getAllSchemasForContentType = ({\n routeInfo,\n attributes,\n uniqueName,\n relationTargetSchemaNames,\n}: ApiInfo & { relationTargetSchemaNames: Map<string, string> }) => {\n // Store response and request schemas in an object\n let strapiComponentSchemas = {};\n const schemas: OpenAPIV3.ComponentsObject = {};\n const typeName = pascalCase(uniqueName);\n\n // adds a ComponentSchema to the Schemas so it can be used as Ref\n const didAddStrapiComponentsToSchemas = (schemaName: string, schema: OpenAPIV3.SchemaObject) => {\n if (!Object.keys(schema) || !Object.keys(schema.properties!)) return false;\n\n // Add the Strapi components to the schema\n strapiComponentSchemas = {\n ...strapiComponentSchemas,\n [schemaName]: schema,\n };\n\n return true;\n };\n\n // Get all the route methods\n const routeMethods = new Set(routeInfo.routes.map((route: Core.Route) => route.method));\n\n const attributesToOmit = [\n 'createdAt',\n 'updatedAt',\n 'publishedAt',\n 'publishedBy',\n 'updatedBy',\n 'createdBy',\n ];\n\n const attributesForRequest = _.omit(attributes, attributesToOmit);\n // Get a list of required attribute names\n const requiredRequestAttributes = getRequiredAttributes(attributesForRequest);\n // Build the request schemas when the route has POST or PUT methods\n if (routeMethods.has('POST') || routeMethods.has('PUT')) {\n // Build localization requests schemas\n\n // Build the request schema\n Object.assign(schemas, {\n [`${typeName}Request`]: {\n type: 'object',\n required: ['data'],\n properties: {\n data: {\n ...(requiredRequestAttributes.length && { required: requiredRequestAttributes }),\n type: 'object',\n properties: cleanSchemaAttributes(attributesForRequest, {\n isRequest: true,\n didAddStrapiComponentsToSchemas,\n }),\n },\n },\n },\n });\n }\n\n // Check for routes that need to return a list\n const hasListOfEntities = routeInfo.routes.filter((route: Core.Route) =>\n hasFindMethod(route.handler)\n ).length;\n\n if (hasListOfEntities) {\n // Build the list response schema\n Object.assign(schemas, {\n [`${typeName}ListResponse`]: {\n type: 'object',\n properties: {\n data: {\n type: 'array',\n items: {\n $ref: `#/components/schemas/${typeName}`,\n },\n },\n meta: {\n type: 'object',\n properties: {\n pagination: {\n type: 'object',\n properties: {\n page: { type: 'integer' },\n pageSize: { type: 'integer', minimum: 25 },\n pageCount: { type: 'integer', maximum: 1 },\n total: { type: 'integer' },\n },\n },\n },\n },\n },\n },\n });\n }\n\n const requiredAttributes = getRequiredAttributes(attributes);\n // Build the response schema\n Object.assign(schemas, {\n [`${typeName}`]: {\n type: 'object',\n ...(requiredAttributes.length && { required: requiredAttributes }),\n properties: {\n id: { oneOf: [{ type: 'string' }, { type: 'number' }] },\n documentId: { type: 'string' },\n ...cleanSchemaAttributes(attributes, {\n relationTargetSchemaNames,\n didAddStrapiComponentsToSchemas,\n }),\n },\n },\n\n [`${typeName}Response`]: {\n type: 'object',\n properties: {\n data: {\n $ref: `#/components/schemas/${typeName}`,\n },\n meta: { type: 'object' },\n },\n },\n });\n\n return { ...schemas, ...strapiComponentSchemas };\n};\n\nconst getRelationTargetSchemaNames = (api: Api) => {\n const relationTargetSchemaNames = new Map<string, string>();\n\n loopContentTypeNames(api, ({ uid, uniqueName }) => {\n relationTargetSchemaNames.set(uid, pascalCase(uniqueName));\n return {};\n });\n\n return relationTargetSchemaNames;\n};\n\nconst buildComponentSchema = (\n api: Api,\n relationTargetSchemaNames = getRelationTargetSchemaNames(api)\n) => {\n // A reusable loop for building paths and component schemas\n // Uses the api param to build a new set of params for each content type\n // Passes these new params to the function provided\n return loopContentTypeNames(api, (apiInfo) =>\n getAllSchemasForContentType({ ...apiInfo, relationTargetSchemaNames })\n );\n};\n\nexport default buildComponentSchema;\nexport { getRelationTargetSchemaNames };\n"],"names":["getRequiredAttributes","allAttributes","requiredAttributes","key","required","push","getAllSchemasForContentType","routeInfo","attributes","uniqueName","relationTargetSchemaNames","strapiComponentSchemas","schemas","typeName","pascalCase","didAddStrapiComponentsToSchemas","schemaName","schema","Object","keys","properties","routeMethods","Set","routes","map","route","method","attributesToOmit","attributesForRequest","_","omit","requiredRequestAttributes","has","assign","type","data","length","cleanSchemaAttributes","isRequest","hasListOfEntities","filter","hasFindMethod","handler","items","$ref","meta","pagination","page","pageSize","minimum","pageCount","maximum","total","id","oneOf","documentId","getRelationTargetSchemaNames","api","Map","loopContentTypeNames","uid","set","buildComponentSchema","apiInfo"],"mappings":";;;;;;;;;;;;;;AAYA,MAAMA,wBAAwB,CAACC,aAAAA,GAAAA;AAC7B,IAAA,MAAMC,qBAA+B,EAAE;IAEvC,IAAK,MAAMC,OAAOF,aAAAA,CAAe;AAC/B,QAAA,IAAIA,aAAa,CAACE,GAAAA,CAAI,CAACC,QAAQ,EAAE;AAC/BF,YAAAA,kBAAAA,CAAmBG,IAAI,CAACF,GAAAA,CAAAA;AAC1B,QAAA;AACF,IAAA;IAEA,OAAOD,kBAAAA;AACT,CAAA;AAEA;;;;;;;;;IAUA,MAAMI,2BAAAA,GAA8B,CAAC,EACnCC,SAAS,EACTC,UAAU,EACVC,UAAU,EACVC,yBAAyB,EACoC,GAAA;;AAE7D,IAAA,IAAIC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AC9C,QAAA,OAAO,EAAC;AACV,IAAA,CAAA,CAAA;IAEA,OAAOC,yBAAAA;AACT;AAEA,MAAMoD,oBAAAA,GAAuB,CAC3BL,GAAAA,EACA/C,yBAAAA,GAA4B8C,6BAA6BC,GAAAA,CAAI,GAAA;;;;AAK7D,IAAA,OAAOE,oBAAAA,CAAqBF,GAAAA,EAAK,CAACM,OAAAA,GAChCzD,2BAAAA,CAA4B;AAAE,YAAA,GAAGyD,OAAO;AAAErD,YAAAA;AAA0B,SAAA,CAAA,CAAA;AAExE;;;;;"}
|
|
1
|
+
{"version":3,"file":"build-component-schema.js","sources":["../../../../server/src/services/helpers/build-component-schema.ts"],"sourcesContent":["import _ from 'lodash';\n\nimport type { OpenAPIV3 } from 'openapi-types';\nimport type { Core, Struct } from '@strapi/types';\n\nimport cleanSchemaAttributes from './utils/clean-schema-attributes';\nimport loopContentTypeNames from './utils/loop-content-type-names';\nimport pascalCase from './utils/pascal-case';\nimport { hasFindMethod } from './utils/routes';\n\nimport type { Api, ApiInfo } from '../../types';\n\n/**\n * Attributes Strapi adds to content types for its own needs, hidden from the Content Manager\n * and never accepted nor returned by the Content API, such as the position of a document in\n * the custom order of its collection type.\n */\nconst isInternalAttribute = (attribute: Struct.SchemaAttributes[string]) => {\n const { visible, private: isPrivate } = attribute as { visible?: boolean; private?: boolean };\n\n return visible === false && isPrivate === true;\n};\n\nconst getRequiredAttributes = (allAttributes: Struct.SchemaAttributes) => {\n const requiredAttributes: string[] = [];\n\n for (const key in allAttributes) {\n if (allAttributes[key].required) {\n requiredAttributes.push(key);\n }\n }\n\n return requiredAttributes;\n};\n\n/**\n * @description Get all open api schema objects for a given content type\n *\n * @param {object} apiInfo\n * @property {string} apiInfo.uniqueName - Api name | Api name + Content type name\n * @property {object} apiInfo.attributes - Attributes on content type\n * @property {object} apiInfo.routeInfo - The routes for the api\n *\n * @returns {object} Open API schemas\n */\nconst getAllSchemasForContentType = ({\n routeInfo,\n attributes: allAttributes,\n uniqueName,\n relationTargetSchemaNames,\n}: ApiInfo & { relationTargetSchemaNames: Map<string, string> }) => {\n const attributes = _.omitBy(allAttributes, isInternalAttribute) as Struct.SchemaAttributes;\n // Store response and request schemas in an object\n let strapiComponentSchemas = {};\n const schemas: OpenAPIV3.ComponentsObject = {};\n const typeName = pascalCase(uniqueName);\n\n // adds a ComponentSchema to the Schemas so it can be used as Ref\n const didAddStrapiComponentsToSchemas = (schemaName: string, schema: OpenAPIV3.SchemaObject) => {\n if (!Object.keys(schema) || !Object.keys(schema.properties!)) return false;\n\n // Add the Strapi components to the schema\n strapiComponentSchemas = {\n ...strapiComponentSchemas,\n [schemaName]: schema,\n };\n\n return true;\n };\n\n // Get all the route methods\n const routeMethods = new Set(routeInfo.routes.map((route: Core.Route) => route.method));\n\n const attributesToOmit = [\n 'createdAt',\n 'updatedAt',\n 'publishedAt',\n 'publishedBy',\n 'updatedBy',\n 'createdBy',\n ];\n\n const attributesForRequest = _.omit(attributes, attributesToOmit);\n // Get a list of required attribute names\n const requiredRequestAttributes = getRequiredAttributes(attributesForRequest);\n // Build the request schemas when the route has POST or PUT methods\n if (routeMethods.has('POST') || routeMethods.has('PUT')) {\n // Build localization requests schemas\n\n // Build the request schema\n Object.assign(schemas, {\n [`${typeName}Request`]: {\n type: 'object',\n required: ['data'],\n properties: {\n data: {\n ...(requiredRequestAttributes.length && { required: requiredRequestAttributes }),\n type: 'object',\n properties: cleanSchemaAttributes(attributesForRequest, {\n isRequest: true,\n didAddStrapiComponentsToSchemas,\n }),\n },\n },\n },\n });\n }\n\n // Check for routes that need to return a list\n const hasListOfEntities = routeInfo.routes.filter((route: Core.Route) =>\n hasFindMethod(route.handler)\n ).length;\n\n if (hasListOfEntities) {\n // Build the list response schema\n Object.assign(schemas, {\n [`${typeName}ListResponse`]: {\n type: 'object',\n properties: {\n data: {\n type: 'array',\n items: {\n $ref: `#/components/schemas/${typeName}`,\n },\n },\n meta: {\n type: 'object',\n properties: {\n pagination: {\n type: 'object',\n properties: {\n page: { type: 'integer' },\n pageSize: { type: 'integer', minimum: 25 },\n pageCount: { type: 'integer', maximum: 1 },\n total: { type: 'integer' },\n },\n },\n },\n },\n },\n },\n });\n }\n\n const requiredAttributes = getRequiredAttributes(attributes);\n // Build the response schema\n Object.assign(schemas, {\n [`${typeName}`]: {\n type: 'object',\n ...(requiredAttributes.length && { required: requiredAttributes }),\n properties: {\n id: { oneOf: [{ type: 'string' }, { type: 'number' }] },\n documentId: { type: 'string' },\n ...cleanSchemaAttributes(attributes, {\n relationTargetSchemaNames,\n didAddStrapiComponentsToSchemas,\n }),\n },\n },\n\n [`${typeName}Response`]: {\n type: 'object',\n properties: {\n data: {\n $ref: `#/components/schemas/${typeName}`,\n },\n meta: { type: 'object' },\n },\n },\n });\n\n return { ...schemas, ...strapiComponentSchemas };\n};\n\nconst getRelationTargetSchemaNames = (api: Api) => {\n const relationTargetSchemaNames = new Map<string, string>();\n\n loopContentTypeNames(api, ({ uid, uniqueName }) => {\n relationTargetSchemaNames.set(uid, pascalCase(uniqueName));\n return {};\n });\n\n return relationTargetSchemaNames;\n};\n\nconst buildComponentSchema = (\n api: Api,\n relationTargetSchemaNames = getRelationTargetSchemaNames(api)\n) => {\n // A reusable loop for building paths and component schemas\n // Uses the api param to build a new set of params for each content type\n // Passes these new params to the function provided\n return loopContentTypeNames(api, (apiInfo) =>\n getAllSchemasForContentType({ ...apiInfo, relationTargetSchemaNames })\n );\n};\n\nexport default buildComponentSchema;\nexport { getRelationTargetSchemaNames };\n"],"names":["isInternalAttribute","attribute","visible","private","isPrivate","getRequiredAttributes","allAttributes","requiredAttributes","key","required","push","getAllSchemasForContentType","routeInfo","attributes","uniqueName","relationTargetSchemaNames","_","omitBy","strapiComponentSchemas","schemas","typeName","pascalCase","didAddStrapiComponentsToSchemas","schemaName","schema","Object","keys","properties","routeMethods","Set","routes","map","route","method","attributesToOmit","attributesForRequest","omit","requiredRequestAttributes","has","assign","type","data","length","cleanSchemaAttributes","isRequest","hasListOfEntities","filter","hasFindMethod","handler","items","$ref","meta","pagination","page","pageSize","minimum","pageCount","maximum","total","id","oneOf","documentId","getRelationTargetSchemaNames","api","Map","loopContentTypeNames","uid","set","buildComponentSchema","apiInfo"],"mappings":";;;;;;;;;;;;;;AAYA;;;;IAKA,MAAMA,sBAAsB,CAACC,SAAAA,GAAAA;AAC3B,IAAA,MAAM,EAAEC,OAAO,EAAEC,OAAAA,EAASC,SAAS,EAAE,GAAGH,SAAAA;IAExC,OAAOC,OAAAA,KAAY,SAASE,SAAAA,KAAc,IAAA;AAC5C,CAAA;AAEA,MAAMC,wBAAwB,CAACC,aAAAA,GAAAA;AAC7B,IAAA,MAAMC,qBAA+B,EAAE;IAEvC,IAAK,MAAMC,OAAOF,aAAAA,CAAe;AAC/B,QAAA,IAAIA,aAAa,CAACE,GAAAA,CAAI,CAACC,QAAQ,EAAE;AAC/BF,YAAAA,kBAAAA,CAAmBG,IAAI,CAACF,GAAAA,CAAAA;AAC1B,QAAA;AACF,IAAA;IAEA,OAAOD,kBAAAA;AACT,CAAA;AAEA;;;;;;;;;AASC,IACD,MAAMI,2BAAAA,GAA8B,CAAC,EACnCC,SAAS,EACTC,UAAAA,EAAYP,aAAa,EACzBQ,UAAU,EACVC,yBAAyB,EACoC,GAAA;AAC7D,IAAA,MAAMF,UAAAA,GAAaG,kBAAAA,CAAEC,MAAM,CAACX,aAAAA,EAAeN,mBAAAA,CAAAA;;AAE3C,IAAA,IAAIkB,yBAAyB,EAAC;AAC9B,IAAA,MAAMC,UAAsC,EAAC;AAC7C,IAAA,MAAMC,WAAWC,UAAAA,CAAWP,UAAAA,CAAAA;;IAG5B,MAAMQ,+BAAAA,GAAkC,CAACC,UAAAA,EAAoBC,MAAAA,GAAAA;AAC3D,QAAA,IAAI,CAACC,MAAAA,CAAOC,IAAI,CAACF,MAAAA,CAAAA,IAAW,CAACC,MAAAA,CAAOC,IAAI,CAACF,MAAAA,CAAOG,UAAU,CAAA,EAAI,OAAO,KAAA;;QAGrET,sB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A;AAExE;;;;;"}
|
|
@@ -4,6 +4,14 @@ import loopContentTypeNames from './utils/loop-content-type-names.mjs';
|
|
|
4
4
|
import pascalCase from './utils/pascal-case.mjs';
|
|
5
5
|
import { hasFindMethod } from './utils/routes.mjs';
|
|
6
6
|
|
|
7
|
+
/**
|
|
8
|
+
* Attributes Strapi adds to content types for its own needs, hidden from the Content Manager
|
|
9
|
+
* and never accepted nor returned by the Content API, such as the position of a document in
|
|
10
|
+
* the custom order of its collection type.
|
|
11
|
+
*/ const isInternalAttribute = (attribute)=>{
|
|
12
|
+
const { visible, private: isPrivate } = attribute;
|
|
13
|
+
return visible === false && isPrivate === true;
|
|
14
|
+
};
|
|
7
15
|
const getRequiredAttributes = (allAttributes)=>{
|
|
8
16
|
const requiredAttributes = [];
|
|
9
17
|
for(const key in allAttributes){
|
|
@@ -22,7 +30,8 @@ const getRequiredAttributes = (allAttributes)=>{
|
|
|
22
30
|
* @property {object} apiInfo.routeInfo - The routes for the api
|
|
23
31
|
*
|
|
24
32
|
* @returns {object} Open API schemas
|
|
25
|
-
*/ const getAllSchemasForContentType = ({ routeInfo, attributes, uniqueName, relationTargetSchemaNames })=>{
|
|
33
|
+
*/ const getAllSchemasForContentType = ({ routeInfo, attributes: allAttributes, uniqueName, relationTargetSchemaNames })=>{
|
|
34
|
+
const attributes = _.omitBy(allAttributes, isInternalAttribute);
|
|
26
35
|
// Store response and request schemas in an object
|
|
27
36
|
let strapiComponentSchemas = {};
|
|
28
37
|
const schemas = {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-component-schema.mjs","sources":["../../../../server/src/services/helpers/build-component-schema.ts"],"sourcesContent":["import _ from 'lodash';\n\nimport type { OpenAPIV3 } from 'openapi-types';\nimport type { Core, Struct } from '@strapi/types';\n\nimport cleanSchemaAttributes from './utils/clean-schema-attributes';\nimport loopContentTypeNames from './utils/loop-content-type-names';\nimport pascalCase from './utils/pascal-case';\nimport { hasFindMethod } from './utils/routes';\n\nimport type { Api, ApiInfo } from '../../types';\n\nconst getRequiredAttributes = (allAttributes: Struct.SchemaAttributes) => {\n const requiredAttributes: string[] = [];\n\n for (const key in allAttributes) {\n if (allAttributes[key].required) {\n requiredAttributes.push(key);\n }\n }\n\n return requiredAttributes;\n};\n\n/**\n * @description Get all open api schema objects for a given content type\n *\n * @param {object} apiInfo\n * @property {string} apiInfo.uniqueName - Api name | Api name + Content type name\n * @property {object} apiInfo.attributes - Attributes on content type\n * @property {object} apiInfo.routeInfo - The routes for the api\n *\n * @returns {object} Open API schemas\n */\nconst getAllSchemasForContentType = ({\n routeInfo,\n attributes,\n uniqueName,\n relationTargetSchemaNames,\n}: ApiInfo & { relationTargetSchemaNames: Map<string, string> }) => {\n // Store response and request schemas in an object\n let strapiComponentSchemas = {};\n const schemas: OpenAPIV3.ComponentsObject = {};\n const typeName = pascalCase(uniqueName);\n\n // adds a ComponentSchema to the Schemas so it can be used as Ref\n const didAddStrapiComponentsToSchemas = (schemaName: string, schema: OpenAPIV3.SchemaObject) => {\n if (!Object.keys(schema) || !Object.keys(schema.properties!)) return false;\n\n // Add the Strapi components to the schema\n strapiComponentSchemas = {\n ...strapiComponentSchemas,\n [schemaName]: schema,\n };\n\n return true;\n };\n\n // Get all the route methods\n const routeMethods = new Set(routeInfo.routes.map((route: Core.Route) => route.method));\n\n const attributesToOmit = [\n 'createdAt',\n 'updatedAt',\n 'publishedAt',\n 'publishedBy',\n 'updatedBy',\n 'createdBy',\n ];\n\n const attributesForRequest = _.omit(attributes, attributesToOmit);\n // Get a list of required attribute names\n const requiredRequestAttributes = getRequiredAttributes(attributesForRequest);\n // Build the request schemas when the route has POST or PUT methods\n if (routeMethods.has('POST') || routeMethods.has('PUT')) {\n // Build localization requests schemas\n\n // Build the request schema\n Object.assign(schemas, {\n [`${typeName}Request`]: {\n type: 'object',\n required: ['data'],\n properties: {\n data: {\n ...(requiredRequestAttributes.length && { required: requiredRequestAttributes }),\n type: 'object',\n properties: cleanSchemaAttributes(attributesForRequest, {\n isRequest: true,\n didAddStrapiComponentsToSchemas,\n }),\n },\n },\n },\n });\n }\n\n // Check for routes that need to return a list\n const hasListOfEntities = routeInfo.routes.filter((route: Core.Route) =>\n hasFindMethod(route.handler)\n ).length;\n\n if (hasListOfEntities) {\n // Build the list response schema\n Object.assign(schemas, {\n [`${typeName}ListResponse`]: {\n type: 'object',\n properties: {\n data: {\n type: 'array',\n items: {\n $ref: `#/components/schemas/${typeName}`,\n },\n },\n meta: {\n type: 'object',\n properties: {\n pagination: {\n type: 'object',\n properties: {\n page: { type: 'integer' },\n pageSize: { type: 'integer', minimum: 25 },\n pageCount: { type: 'integer', maximum: 1 },\n total: { type: 'integer' },\n },\n },\n },\n },\n },\n },\n });\n }\n\n const requiredAttributes = getRequiredAttributes(attributes);\n // Build the response schema\n Object.assign(schemas, {\n [`${typeName}`]: {\n type: 'object',\n ...(requiredAttributes.length && { required: requiredAttributes }),\n properties: {\n id: { oneOf: [{ type: 'string' }, { type: 'number' }] },\n documentId: { type: 'string' },\n ...cleanSchemaAttributes(attributes, {\n relationTargetSchemaNames,\n didAddStrapiComponentsToSchemas,\n }),\n },\n },\n\n [`${typeName}Response`]: {\n type: 'object',\n properties: {\n data: {\n $ref: `#/components/schemas/${typeName}`,\n },\n meta: { type: 'object' },\n },\n },\n });\n\n return { ...schemas, ...strapiComponentSchemas };\n};\n\nconst getRelationTargetSchemaNames = (api: Api) => {\n const relationTargetSchemaNames = new Map<string, string>();\n\n loopContentTypeNames(api, ({ uid, uniqueName }) => {\n relationTargetSchemaNames.set(uid, pascalCase(uniqueName));\n return {};\n });\n\n return relationTargetSchemaNames;\n};\n\nconst buildComponentSchema = (\n api: Api,\n relationTargetSchemaNames = getRelationTargetSchemaNames(api)\n) => {\n // A reusable loop for building paths and component schemas\n // Uses the api param to build a new set of params for each content type\n // Passes these new params to the function provided\n return loopContentTypeNames(api, (apiInfo) =>\n getAllSchemasForContentType({ ...apiInfo, relationTargetSchemaNames })\n );\n};\n\nexport default buildComponentSchema;\nexport { getRelationTargetSchemaNames };\n"],"names":["getRequiredAttributes","allAttributes","requiredAttributes","key","required","push","getAllSchemasForContentType","routeInfo","attributes","uniqueName","relationTargetSchemaNames","strapiComponentSchemas","schemas","typeName","pascalCase","didAddStrapiComponentsToSchemas","schemaName","schema","Object","keys","properties","routeMethods","Set","routes","map","route","method","attributesToOmit","attributesForRequest","_","omit","requiredRequestAttributes","has","assign","type","data","length","cleanSchemaAttributes","isRequest","hasListOfEntities","filter","hasFindMethod","handler","items","$ref","meta","pagination","page","pageSize","minimum","pageCount","maximum","total","id","oneOf","documentId","getRelationTargetSchemaNames","api","Map","loopContentTypeNames","uid","set","buildComponentSchema","apiInfo"],"mappings":";;;;;;AAYA,MAAMA,wBAAwB,CAACC,aAAAA,GAAAA;AAC7B,IAAA,MAAMC,qBAA+B,EAAE;IAEvC,IAAK,MAAMC,OAAOF,aAAAA,CAAe;AAC/B,QAAA,IAAIA,aAAa,CAACE,GAAAA,CAAI,CAACC,QAAQ,EAAE;AAC/BF,YAAAA,kBAAAA,CAAmBG,IAAI,CAACF,GAAAA,CAAAA;AAC1B,QAAA;AACF,IAAA;IAEA,OAAOD,kBAAAA;AACT,CAAA;AAEA;;;;;;;;;IAUA,MAAMI,2BAAAA,GAA8B,CAAC,EACnCC,SAAS,EACTC,UAAU,EACVC,UAAU,EACVC,yBAAyB,EACoC,GAAA;;AAE7D,IAAA,IAAIC,yBAAyB,EAAC;AAC9B,IAAA,MAAMC,UAAsC,EAAC;AAC7C,IAAA,MAAMC,WAAWC,UAAAA,CAAWL,UAAAA,CAAAA;;IAG5B,MAAMM,+BAAAA,GAAkC,CAACC,UAAAA,EAAoBC,MAAAA,GAAAA;AAC3D,QAAA,IAAI,CAACC,MAAAA,CAAOC,IAAI,CAACF,MAAAA,CAAAA,IAAW,CAACC,MAAAA,CAAOC,IAAI,CAACF,MAAAA,CAAOG,UAAU,CAAA,EAAI,OAAO,KAAA;;QAGrET,sBAAAA,GAAyB;AAC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|
+
{"version":3,"file":"build-component-schema.mjs","sources":["../../../../server/src/services/helpers/build-component-schema.ts"],"sourcesContent":["import _ from 'lodash';\n\nimport type { OpenAPIV3 } from 'openapi-types';\nimport type { Core, Struct } from '@strapi/types';\n\nimport cleanSchemaAttributes from './utils/clean-schema-attributes';\nimport loopContentTypeNames from './utils/loop-content-type-names';\nimport pascalCase from './utils/pascal-case';\nimport { hasFindMethod } from './utils/routes';\n\nimport type { Api, ApiInfo } from '../../types';\n\n/**\n * Attributes Strapi adds to content types for its own needs, hidden from the Content Manager\n * and never accepted nor returned by the Content API, such as the position of a document in\n * the custom order of its collection type.\n */\nconst isInternalAttribute = (attribute: Struct.SchemaAttributes[string]) => {\n const { visible, private: isPrivate } = attribute as { visible?: boolean; private?: boolean };\n\n return visible === false && isPrivate === true;\n};\n\nconst getRequiredAttributes = (allAttributes: Struct.SchemaAttributes) => {\n const requiredAttributes: string[] = [];\n\n for (const key in allAttributes) {\n if (allAttributes[key].required) {\n requiredAttributes.push(key);\n }\n }\n\n return requiredAttributes;\n};\n\n/**\n * @description Get all open api schema objects for a given content type\n *\n * @param {object} apiInfo\n * @property {string} apiInfo.uniqueName - Api name | Api name + Content type name\n * @property {object} apiInfo.attributes - Attributes on content type\n * @property {object} apiInfo.routeInfo - The routes for the api\n *\n * @returns {object} Open API schemas\n */\nconst getAllSchemasForContentType = ({\n routeInfo,\n attributes: allAttributes,\n uniqueName,\n relationTargetSchemaNames,\n}: ApiInfo & { relationTargetSchemaNames: Map<string, string> }) => {\n const attributes = _.omitBy(allAttributes, isInternalAttribute) as Struct.SchemaAttributes;\n // Store response and request schemas in an object\n let strapiComponentSchemas = {};\n const schemas: OpenAPIV3.ComponentsObject = {};\n const typeName = pascalCase(uniqueName);\n\n // adds a ComponentSchema to the Schemas so it can be used as Ref\n const didAddStrapiComponentsToSchemas = (schemaName: string, schema: OpenAPIV3.SchemaObject) => {\n if (!Object.keys(schema) || !Object.keys(schema.properties!)) return false;\n\n // Add the Strapi components to the schema\n strapiComponentSchemas = {\n ...strapiComponentSchemas,\n [schemaName]: schema,\n };\n\n return true;\n };\n\n // Get all the route methods\n const routeMethods = new Set(routeInfo.routes.map((route: Core.Route) => route.method));\n\n const attributesToOmit = [\n 'createdAt',\n 'updatedAt',\n 'publishedAt',\n 'publishedBy',\n 'updatedBy',\n 'createdBy',\n ];\n\n const attributesForRequest = _.omit(attributes, attributesToOmit);\n // Get a list of required attribute names\n const requiredRequestAttributes = getRequiredAttributes(attributesForRequest);\n // Build the request schemas when the route has POST or PUT methods\n if (routeMethods.has('POST') || routeMethods.has('PUT')) {\n // Build localization requests schemas\n\n // Build the request schema\n Object.assign(schemas, {\n [`${typeName}Request`]: {\n type: 'object',\n required: ['data'],\n properties: {\n data: {\n ...(requiredRequestAttributes.length && { required: requiredRequestAttributes }),\n type: 'object',\n properties: cleanSchemaAttributes(attributesForRequest, {\n isRequest: true,\n didAddStrapiComponentsToSchemas,\n }),\n },\n },\n },\n });\n }\n\n // Check for routes that need to return a list\n const hasListOfEntities = routeInfo.routes.filter((route: Core.Route) =>\n hasFindMethod(route.handler)\n ).length;\n\n if (hasListOfEntities) {\n // Build the list response schema\n Object.assign(schemas, {\n [`${typeName}ListResponse`]: {\n type: 'object',\n properties: {\n data: {\n type: 'array',\n items: {\n $ref: `#/components/schemas/${typeName}`,\n },\n },\n meta: {\n type: 'object',\n properties: {\n pagination: {\n type: 'object',\n properties: {\n page: { type: 'integer' },\n pageSize: { type: 'integer', minimum: 25 },\n pageCount: { type: 'integer', maximum: 1 },\n total: { type: 'integer' },\n },\n },\n },\n },\n },\n },\n });\n }\n\n const requiredAttributes = getRequiredAttributes(attributes);\n // Build the response schema\n Object.assign(schemas, {\n [`${typeName}`]: {\n type: 'object',\n ...(requiredAttributes.length && { required: requiredAttributes }),\n properties: {\n id: { oneOf: [{ type: 'string' }, { type: 'number' }] },\n documentId: { type: 'string' },\n ...cleanSchemaAttributes(attributes, {\n relationTargetSchemaNames,\n didAddStrapiComponentsToSchemas,\n }),\n },\n },\n\n [`${typeName}Response`]: {\n type: 'object',\n properties: {\n data: {\n $ref: `#/components/schemas/${typeName}`,\n },\n meta: { type: 'object' },\n },\n },\n });\n\n return { ...schemas, ...strapiComponentSchemas };\n};\n\nconst getRelationTargetSchemaNames = (api: Api) => {\n const relationTargetSchemaNames = new Map<string, string>();\n\n loopContentTypeNames(api, ({ uid, uniqueName }) => {\n relationTargetSchemaNames.set(uid, pascalCase(uniqueName));\n return {};\n });\n\n return relationTargetSchemaNames;\n};\n\nconst buildComponentSchema = (\n api: Api,\n relationTargetSchemaNames = getRelationTargetSchemaNames(api)\n) => {\n // A reusable loop for building paths and component schemas\n // Uses the api param to build a new set of params for each content type\n // Passes these new params to the function provided\n return loopContentTypeNames(api, (apiInfo) =>\n getAllSchemasForContentType({ ...apiInfo, relationTargetSchemaNames })\n );\n};\n\nexport default buildComponentSchema;\nexport { getRelationTargetSchemaNames };\n"],"names":["isInternalAttribute","attribute","visible","private","isPrivate","getRequiredAttributes","allAttributes","requiredAttributes","key","required","push","getAllSchemasForContentType","routeInfo","attributes","uniqueName","relationTargetSchemaNames","_","omitBy","strapiComponentSchemas","schemas","typeName","pascalCase","didAddStrapiComponentsToSchemas","schemaName","schema","Object","keys","properties","routeMethods","Set","routes","map","route","method","attributesToOmit","attributesForRequest","omit","requiredRequestAttributes","has","assign","type","data","length","cleanSchemaAttributes","isRequest","hasListOfEntities","filter","hasFindMethod","handler","items","$ref","meta","pagination","page","pageSize","minimum","pageCount","maximum","total","id","oneOf","documentId","getRelationTargetSchemaNames","api","Map","loopContentTypeNames","uid","set","buildComponentSchema","apiInfo"],"mappings":";;;;;;AAYA;;;;IAKA,MAAMA,sBAAsB,CAACC,SAAAA,GAAAA;AAC3B,IAAA,MAAM,EAAEC,OAAO,EAAEC,OAAAA,EAASC,SAAS,EAAE,GAAGH,SAAAA;IAExC,OAAOC,OAAAA,KAAY,SAASE,SAAAA,KAAc,IAAA;AAC5C,CAAA;AAEA,MAA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Nb,UAAAA,EAAY;gBACVc,IAAAA,EAAM;oBACJS,IAAAA,EAAM,CAAC,qBAAqB,EAAE9B,QAAAA,CAAAA;AAChC,iBAAA;gBACA+B,IAAAA,EAAM;oBAAEX,IAAAA,EAAM;AAAS;AACzB;AACF;AACF,KAAA,CAAA;IAEA,OAAO;AAAE,QAAA,GAAGrB,OAAO;AAAE,QAAA,GAAGD;AAAuB,KAAA;AACjD,CAAA;AAEA,MAAM4C,+BAA+B,CAACC,GAAAA,GAAAA;AACpC,IAAA,MAAMhD,4BAA4B,IAAIiD,GAAAA,EAAAA;AAEtCC,IAAAA,oBAAAA,CAAqBF,KAAK,CAAC,EAAEG,GAAG,EAAEpD,UAAU,EAAE,GAAA;QAC5CC,yBAAAA,CAA0BoD,GAAG,CAACD,GAAAA,EAAK7C,UAAAA,CAAWP,UAAAA,CAAAA,CAAAA;AAC9C,QAAA,OAAO,EAAC;AACV,IAAA,CAAA,CAAA;IAEA,OAAOC,yBAAAA;AACT;AAEA,MAAMqD,oBAAAA,GAAuB,CAC3BL,GAAAA,EACAhD,yBAAAA,GAA4B+C,6BAA6BC,GAAAA,CAAI,GAAA;;;;AAK7D,IAAA,OAAOE,oBAAAA,CAAqBF,GAAAA,EAAK,CAACM,OAAAA,GAChC1D,2BAAAA,CAA4B;AAAE,YAAA,GAAG0D,OAAO;AAAEtD,YAAAA;AAA0B,SAAA,CAAA,CAAA;AAExE;;;;"}
|
|
@@ -23,19 +23,31 @@ const createService = ({ strapi })=>{
|
|
|
23
23
|
},
|
|
24
24
|
registerOverride (override, opts) {
|
|
25
25
|
const { pluginOrigin, excludeFromGeneration = [] } = opts ?? {};
|
|
26
|
-
const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation.getPluginsThatNeedDocumentation(strapi.config.get('plugin::documentation'));
|
|
26
|
+
const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation.getPluginsThatNeedDocumentation(strapi, strapi.config.get('plugin::documentation'));
|
|
27
27
|
// Don't apply the override if the plugin is not in the list of plugins that need documentation
|
|
28
28
|
if (pluginOrigin && !pluginsThatNeedDocumentation.includes(pluginOrigin)) return;
|
|
29
|
-
if (excludeFromGeneration.length) {
|
|
30
|
-
this.excludeFromGeneration(excludeFromGeneration);
|
|
31
|
-
}
|
|
32
29
|
let overrideToRegister = override;
|
|
33
30
|
// Parse yaml if we receive a string
|
|
34
31
|
if (typeof override === 'string') {
|
|
35
32
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
36
|
-
overrideToRegister = require('yaml').parse(
|
|
33
|
+
overrideToRegister = require('yaml').parse(override);
|
|
34
|
+
}
|
|
35
|
+
// Only an object can hold OpenAPI parts, YAML can also parse to a scalar, an array or null.
|
|
36
|
+
// Warn and skip instead of throwing, as this runs during register and must not prevent boot
|
|
37
|
+
if (typeof overrideToRegister !== 'object' || overrideToRegister === null || Array.isArray(overrideToRegister) === true) {
|
|
38
|
+
let receivedType = typeof overrideToRegister;
|
|
39
|
+
if (overrideToRegister === null) {
|
|
40
|
+
receivedType = 'null';
|
|
41
|
+
} else if (Array.isArray(overrideToRegister) === true) {
|
|
42
|
+
receivedType = 'array';
|
|
43
|
+
}
|
|
44
|
+
strapi.log.warn(`[documentation] Ignoring override from "${pluginOrigin ?? 'app'}": expected an object, received ${receivedType}`);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
// Exclude apis only once the override is valid, so a skipped override changes nothing
|
|
48
|
+
if (excludeFromGeneration.length > 0) {
|
|
49
|
+
this.excludeFromGeneration(excludeFromGeneration);
|
|
37
50
|
}
|
|
38
|
-
// receive an object we can register it directly
|
|
39
51
|
registeredOverrides.push(overrideToRegister);
|
|
40
52
|
}
|
|
41
53
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"override.js","sources":["../../../server/src/services/override.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nimport { getPluginsThatNeedDocumentation } from './utils/get-plugins-that-need-documentation';\nimport type { PluginConfig } from '../types';\n\nexport type OverrideService = ReturnType<typeof createService>;\n\nconst createService = ({ strapi }: { strapi: Core.Strapi }) => {\n const registeredOverrides: Partial<PluginConfig>[] = [];\n const excludedFromGeneration: string[] = [];\n\n return {\n registeredOverrides,\n excludedFromGeneration,\n /**\n *\n * @param {(string | string[])} api - The name of the api or and array of apis to exclude from generation\n */\n excludeFromGeneration(api: string | string[]) {\n if (Array.isArray(api)) {\n excludedFromGeneration.push(...api);\n\n return;\n }\n\n excludedFromGeneration.push(api);\n },\n\n isEnabled(name: string) {\n return excludedFromGeneration.includes(name);\n },\n\n registerOverride(\n override: Partial<PluginConfig
|
|
1
|
+
{"version":3,"file":"override.js","sources":["../../../server/src/services/override.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nimport { getPluginsThatNeedDocumentation } from './utils/get-plugins-that-need-documentation';\nimport type { PluginConfig } from '../types';\n\nexport type OverrideService = ReturnType<typeof createService>;\n\nconst createService = ({ strapi }: { strapi: Core.Strapi }) => {\n const registeredOverrides: Partial<PluginConfig>[] = [];\n const excludedFromGeneration: string[] = [];\n\n return {\n registeredOverrides,\n excludedFromGeneration,\n /**\n *\n * @param {(string | string[])} api - The name of the api or and array of apis to exclude from generation\n */\n excludeFromGeneration(api: string | string[]) {\n if (Array.isArray(api)) {\n excludedFromGeneration.push(...api);\n\n return;\n }\n\n excludedFromGeneration.push(api);\n },\n\n isEnabled(name: string) {\n return excludedFromGeneration.includes(name);\n },\n\n registerOverride(\n override: Partial<PluginConfig> | string,\n opts?: { pluginOrigin: string; excludeFromGeneration?: string[] }\n ) {\n const { pluginOrigin, excludeFromGeneration = [] } = opts ?? {};\n\n const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation(\n strapi,\n strapi.config.get('plugin::documentation')\n );\n // Don't apply the override if the plugin is not in the list of plugins that need documentation\n if (pluginOrigin && !pluginsThatNeedDocumentation.includes(pluginOrigin)) return;\n\n let overrideToRegister: unknown = override;\n // Parse yaml if we receive a string\n if (typeof override === 'string') {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n overrideToRegister = require('yaml').parse(override);\n }\n\n // Only an object can hold OpenAPI parts, YAML can also parse to a scalar, an array or null.\n // Warn and skip instead of throwing, as this runs during register and must not prevent boot\n if (\n typeof overrideToRegister !== 'object' ||\n overrideToRegister === null ||\n Array.isArray(overrideToRegister) === true\n ) {\n let receivedType: string = typeof overrideToRegister;\n if (overrideToRegister === null) {\n receivedType = 'null';\n } else if (Array.isArray(overrideToRegister) === true) {\n receivedType = 'array';\n }\n\n strapi.log.warn(\n `[documentation] Ignoring override from \"${pluginOrigin ?? 'app'}\": expected an object, received ${receivedType}`\n );\n\n return;\n }\n\n // Exclude apis only once the override is valid, so a skipped override changes nothing\n if (excludeFromGeneration.length > 0) {\n this.excludeFromGeneration(excludeFromGeneration);\n }\n\n registeredOverrides.push(overrideToRegister as Partial<PluginConfig>);\n },\n };\n};\n\nexport default createService;\n"],"names":["createService","strapi","registeredOverrides","excludedFromGeneration","excludeFromGeneration","api","Array","isArray","push","isEnabled","name","includes","registerOverride","override","opts","pluginOrigin","pluginsThatNeedDocumentation","getPluginsThatNeedDocumentation","config","get","overrideToRegister","require","parse","receivedType","log","warn","length"],"mappings":";;;;AAOA,MAAMA,aAAAA,GAAgB,CAAC,EAAEC,MAAM,EAA2B,GAAA;AACxD,IAAA,MAAMC,sBAA+C,EAAE;AACvD,IAAA,MAAMC,yBAAmC,EAAE;IAE3C,OAAO;AACLD,QAAAA,mBAAAA;AACAC,QAAAA,sBAAAA;AACA;;;AAGC,QACDC,uBAAsBC,GAAsB,EAAA;YAC1C,IAAIC,KAAAA,CAAMC,OAAO,CAACF,GAAAA,CAAAA,EAAM;AACtBF,gBAAAA,sBAAAA,CAAuBK,IAAI,CAAA,GAAIH,GAAAA,CAAAA;AAE/B,gBAAA;AACF,YAAA;AAEAF,YAAAA,sBAAAA,CAAuBK,IAAI,CAACH,GAAAA,CAAAA;AAC9B,QAAA,CAAA;AAEAI,QAAAA,SAAAA,CAAAA,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,CAACA,qBAAAA,CAAAA;AAC7B,YAAA;AAEAF,YAAAA,mBAAAA,CAAoBM,IAAI,CAACY,kBAAAA,CAAAA;AAC3B,QAAA;AACF,KAAA;AACF;;;;"}
|
|
@@ -21,19 +21,31 @@ const createService = ({ strapi })=>{
|
|
|
21
21
|
},
|
|
22
22
|
registerOverride (override, opts) {
|
|
23
23
|
const { pluginOrigin, excludeFromGeneration = [] } = opts ?? {};
|
|
24
|
-
const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation(strapi.config.get('plugin::documentation'));
|
|
24
|
+
const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation(strapi, strapi.config.get('plugin::documentation'));
|
|
25
25
|
// Don't apply the override if the plugin is not in the list of plugins that need documentation
|
|
26
26
|
if (pluginOrigin && !pluginsThatNeedDocumentation.includes(pluginOrigin)) return;
|
|
27
|
-
if (excludeFromGeneration.length) {
|
|
28
|
-
this.excludeFromGeneration(excludeFromGeneration);
|
|
29
|
-
}
|
|
30
27
|
let overrideToRegister = override;
|
|
31
28
|
// Parse yaml if we receive a string
|
|
32
29
|
if (typeof override === 'string') {
|
|
33
30
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
34
|
-
overrideToRegister = require('yaml').parse(
|
|
31
|
+
overrideToRegister = require('yaml').parse(override);
|
|
32
|
+
}
|
|
33
|
+
// Only an object can hold OpenAPI parts, YAML can also parse to a scalar, an array or null.
|
|
34
|
+
// Warn and skip instead of throwing, as this runs during register and must not prevent boot
|
|
35
|
+
if (typeof overrideToRegister !== 'object' || overrideToRegister === null || Array.isArray(overrideToRegister) === true) {
|
|
36
|
+
let receivedType = typeof overrideToRegister;
|
|
37
|
+
if (overrideToRegister === null) {
|
|
38
|
+
receivedType = 'null';
|
|
39
|
+
} else if (Array.isArray(overrideToRegister) === true) {
|
|
40
|
+
receivedType = 'array';
|
|
41
|
+
}
|
|
42
|
+
strapi.log.warn(`[documentation] Ignoring override from "${pluginOrigin ?? 'app'}": expected an object, received ${receivedType}`);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
// Exclude apis only once the override is valid, so a skipped override changes nothing
|
|
46
|
+
if (excludeFromGeneration.length > 0) {
|
|
47
|
+
this.excludeFromGeneration(excludeFromGeneration);
|
|
35
48
|
}
|
|
36
|
-
// receive an object we can register it directly
|
|
37
49
|
registeredOverrides.push(overrideToRegister);
|
|
38
50
|
}
|
|
39
51
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"override.mjs","sources":["../../../server/src/services/override.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nimport { getPluginsThatNeedDocumentation } from './utils/get-plugins-that-need-documentation';\nimport type { PluginConfig } from '../types';\n\nexport type OverrideService = ReturnType<typeof createService>;\n\nconst createService = ({ strapi }: { strapi: Core.Strapi }) => {\n const registeredOverrides: Partial<PluginConfig>[] = [];\n const excludedFromGeneration: string[] = [];\n\n return {\n registeredOverrides,\n excludedFromGeneration,\n /**\n *\n * @param {(string | string[])} api - The name of the api or and array of apis to exclude from generation\n */\n excludeFromGeneration(api: string | string[]) {\n if (Array.isArray(api)) {\n excludedFromGeneration.push(...api);\n\n return;\n }\n\n excludedFromGeneration.push(api);\n },\n\n isEnabled(name: string) {\n return excludedFromGeneration.includes(name);\n },\n\n registerOverride(\n override: Partial<PluginConfig
|
|
1
|
+
{"version":3,"file":"override.mjs","sources":["../../../server/src/services/override.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nimport { getPluginsThatNeedDocumentation } from './utils/get-plugins-that-need-documentation';\nimport type { PluginConfig } from '../types';\n\nexport type OverrideService = ReturnType<typeof createService>;\n\nconst createService = ({ strapi }: { strapi: Core.Strapi }) => {\n const registeredOverrides: Partial<PluginConfig>[] = [];\n const excludedFromGeneration: string[] = [];\n\n return {\n registeredOverrides,\n excludedFromGeneration,\n /**\n *\n * @param {(string | string[])} api - The name of the api or and array of apis to exclude from generation\n */\n excludeFromGeneration(api: string | string[]) {\n if (Array.isArray(api)) {\n excludedFromGeneration.push(...api);\n\n return;\n }\n\n excludedFromGeneration.push(api);\n },\n\n isEnabled(name: string) {\n return excludedFromGeneration.includes(name);\n },\n\n registerOverride(\n override: Partial<PluginConfig> | string,\n opts?: { pluginOrigin: string; excludeFromGeneration?: string[] }\n ) {\n const { pluginOrigin, excludeFromGeneration = [] } = opts ?? {};\n\n const pluginsThatNeedDocumentation = getPluginsThatNeedDocumentation(\n strapi,\n strapi.config.get('plugin::documentation')\n );\n // Don't apply the override if the plugin is not in the list of plugins that need documentation\n if (pluginOrigin && !pluginsThatNeedDocumentation.includes(pluginOrigin)) return;\n\n let overrideToRegister: unknown = override;\n // Parse yaml if we receive a string\n if (typeof override === 'string') {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n overrideToRegister = require('yaml').parse(override);\n }\n\n // Only an object can hold OpenAPI parts, YAML can also parse to a scalar, an array or null.\n // Warn and skip instead of throwing, as this runs during register and must not prevent boot\n if (\n typeof overrideToRegister !== 'object' ||\n overrideToRegister === null ||\n Array.isArray(overrideToRegister) === true\n ) {\n let receivedType: string = typeof overrideToRegister;\n if (overrideToRegister === null) {\n receivedType = 'null';\n } else if (Array.isArray(overrideToRegister) === true) {\n receivedType = 'array';\n }\n\n strapi.log.warn(\n `[documentation] Ignoring override from \"${pluginOrigin ?? 'app'}\": expected an object, received ${receivedType}`\n );\n\n return;\n }\n\n // Exclude apis only once the override is valid, so a skipped override changes nothing\n if (excludeFromGeneration.length > 0) {\n this.excludeFromGeneration(excludeFromGeneration);\n }\n\n registeredOverrides.push(overrideToRegister as Partial<PluginConfig>);\n },\n };\n};\n\nexport default createService;\n"],"names":["createService","strapi","registeredOverrides","excludedFromGeneration","excludeFromGeneration","api","Array","isArray","push","isEnabled","name","includes","registerOverride","override","opts","pluginOrigin","pluginsThatNeedDocumentation","getPluginsThatNeedDocumentation","config","get","overrideToRegister","require","parse","receivedType","log","warn","length"],"mappings":";;AAOA,MAAMA,aAAAA,GAAgB,CAAC,EAAEC,M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A;AAClC,gBAAA,IAAIA,uBAAuB,IAAA,EAAM;oBAC/BG,YAAAA,GAAe,MAAA;AACjB,gBAAA,CAAA,MAAO,IAAIjB,KAAAA,CAAMC,OAAO,CAACa,wBAAwB,IAAA,EAAM;oBACrDG,YAAAA,GAAe,OAAA;AACjB,gBAAA;gBAEAtB,MAAAA,CAAOuB,GAAG,CAACC,IAAI,CACb,CAAC,wCAAwC,EAAEV,YAAAA,IAAgB,KAAA,CAAM,gCAAgC,EAAEQ,YAAAA,CAAAA,CAAc,CAAA;AAGnH,gBAAA;AACF,YAAA;;YAGA,IAAInB,qBAAAA,CAAsBsB,MAAM,GAAG,CAAA,EAAG;gBACpC,IAAI,CAACtB,qBAAqB,CAACA,qBAAAA,CAAAA;AAC7B,YAAA;AAEAF,YAAAA,mBAAAA,CAAoBM,IAAI,CAACY,kBAAAA,CAAAA;AAC3B,QAAA;AACF,KAAA;AACF;;;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const getPluginsThatNeedDocumentation = (config)=>{
|
|
3
|
+
const getPluginsThatNeedDocumentation = (strapi, config)=>{
|
|
4
4
|
// Default plugins that need documentation generated
|
|
5
5
|
const defaultPlugins = [
|
|
6
6
|
'upload',
|
|
@@ -9,8 +9,8 @@ const getPluginsThatNeedDocumentation = (config)=>{
|
|
|
9
9
|
// User specified plugins that need documentation generated
|
|
10
10
|
const userPluginsConfig = config['x-strapi-config'].plugins;
|
|
11
11
|
if (userPluginsConfig === null) {
|
|
12
|
-
// The user hasn't specified any plugins to document, use the defaults
|
|
13
|
-
return defaultPlugins;
|
|
12
|
+
// The user hasn't specified any plugins to document, use the defaults that are installed
|
|
13
|
+
return defaultPlugins.filter((plugin)=>strapi.plugin(plugin) !== undefined);
|
|
14
14
|
}
|
|
15
15
|
if (userPluginsConfig.length) {
|
|
16
16
|
// The user has specified certain plugins to document, use them
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-plugins-that-need-documentation.js","sources":["../../../../server/src/services/utils/get-plugins-that-need-documentation.ts"],"sourcesContent":["import type { PluginConfig } from '../../types';\n\nconst getPluginsThatNeedDocumentation = (config: PluginConfig) => {\n // Default plugins that need documentation generated\n const defaultPlugins = ['upload', 'users-permissions'];\n\n // User specified plugins that need documentation generated\n const userPluginsConfig = config['x-strapi-config'].plugins;\n\n if (userPluginsConfig === null) {\n // The user hasn't specified any plugins to document, use the defaults\n return defaultPlugins;\n }\n\n if (userPluginsConfig.length) {\n // The user has specified certain plugins to document, use them\n return userPluginsConfig;\n }\n\n // The user has specified that no plugins should be documented\n return [];\n};\n\nexport { getPluginsThatNeedDocumentation };\n"],"names":["getPluginsThatNeedDocumentation","config","defaultPlugins","userPluginsConfig","plugins","length"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"get-plugins-that-need-documentation.js","sources":["../../../../server/src/services/utils/get-plugins-that-need-documentation.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nimport type { PluginConfig } from '../../types';\n\nconst getPluginsThatNeedDocumentation = (strapi: Core.Strapi, config: PluginConfig) => {\n // Default plugins that need documentation generated\n const defaultPlugins = ['upload', 'users-permissions'];\n\n // User specified plugins that need documentation generated\n const userPluginsConfig = config['x-strapi-config'].plugins;\n\n if (userPluginsConfig === null) {\n // The user hasn't specified any plugins to document, use the defaults that are installed\n return defaultPlugins.filter((plugin) => strapi.plugin(plugin) !== undefined);\n }\n\n if (userPluginsConfig.length) {\n // The user has specified certain plugins to document, use them\n return userPluginsConfig;\n }\n\n // The user has specified that no plugins should be documented\n return [];\n};\n\nexport { getPluginsThatNeedDocumentation };\n"],"names":["getPluginsThatNeedDocumentation","strapi","config","defaultPlugins","userPluginsConfig","plugins","filter","plugin","undefined","length"],"mappings":";;AAIA,MAAMA,+BAAAA,GAAkC,CAACC,MAAAA,EAAqBC,MAAAA,GAAAA;;AAE5D,IAAA,MAAMC,cAAAA,GAAiB;AAAC,QAAA,QAAA;AAAU,QAAA;AAAoB,KAAA;;AAGtD,IAAA,MAAMC,iBAAAA,GAAoBF,MAAM,CAAC,iBAAA,CAAkB,CAACG,OAAO;AAE3D,IAAA,IAAID,sBAAsB,IAAA,EAAM;;QAE9B,OAAOD,cAAAA,CAAeG,MAAM,CAAC,CAACC,SAAWN,MAAAA,CAAOM,MAAM,CAACA,MAAAA,CAAAA,KAAYC,SAAAA,CAAAA;AACrE,IAAA;IAEA,IAAIJ,iBAAAA,CAAkBK,MAAM,EAAE;;QAE5B,OAAOL,iBAAAA;AACT,IAAA;;AAGA,IAAA,OAAO,EAAE;AACX;;;;"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const getPluginsThatNeedDocumentation = (config)=>{
|
|
1
|
+
const getPluginsThatNeedDocumentation = (strapi, config)=>{
|
|
2
2
|
// Default plugins that need documentation generated
|
|
3
3
|
const defaultPlugins = [
|
|
4
4
|
'upload',
|
|
@@ -7,8 +7,8 @@ const getPluginsThatNeedDocumentation = (config)=>{
|
|
|
7
7
|
// User specified plugins that need documentation generated
|
|
8
8
|
const userPluginsConfig = config['x-strapi-config'].plugins;
|
|
9
9
|
if (userPluginsConfig === null) {
|
|
10
|
-
// The user hasn't specified any plugins to document, use the defaults
|
|
11
|
-
return defaultPlugins;
|
|
10
|
+
// The user hasn't specified any plugins to document, use the defaults that are installed
|
|
11
|
+
return defaultPlugins.filter((plugin)=>strapi.plugin(plugin) !== undefined);
|
|
12
12
|
}
|
|
13
13
|
if (userPluginsConfig.length) {
|
|
14
14
|
// The user has specified certain plugins to document, use them
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-plugins-that-need-documentation.mjs","sources":["../../../../server/src/services/utils/get-plugins-that-need-documentation.ts"],"sourcesContent":["import type { PluginConfig } from '../../types';\n\nconst getPluginsThatNeedDocumentation = (config: PluginConfig) => {\n // Default plugins that need documentation generated\n const defaultPlugins = ['upload', 'users-permissions'];\n\n // User specified plugins that need documentation generated\n const userPluginsConfig = config['x-strapi-config'].plugins;\n\n if (userPluginsConfig === null) {\n // The user hasn't specified any plugins to document, use the defaults\n return defaultPlugins;\n }\n\n if (userPluginsConfig.length) {\n // The user has specified certain plugins to document, use them\n return userPluginsConfig;\n }\n\n // The user has specified that no plugins should be documented\n return [];\n};\n\nexport { getPluginsThatNeedDocumentation };\n"],"names":["getPluginsThatNeedDocumentation","config","defaultPlugins","userPluginsConfig","plugins","length"],"mappings":"
|
|
1
|
+
{"version":3,"file":"get-plugins-that-need-documentation.mjs","sources":["../../../../server/src/services/utils/get-plugins-that-need-documentation.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nimport type { PluginConfig } from '../../types';\n\nconst getPluginsThatNeedDocumentation = (strapi: Core.Strapi, config: PluginConfig) => {\n // Default plugins that need documentation generated\n const defaultPlugins = ['upload', 'users-permissions'];\n\n // User specified plugins that need documentation generated\n const userPluginsConfig = config['x-strapi-config'].plugins;\n\n if (userPluginsConfig === null) {\n // The user hasn't specified any plugins to document, use the defaults that are installed\n return defaultPlugins.filter((plugin) => strapi.plugin(plugin) !== undefined);\n }\n\n if (userPluginsConfig.length) {\n // The user has specified certain plugins to document, use them\n return userPluginsConfig;\n }\n\n // The user has specified that no plugins should be documented\n return [];\n};\n\nexport { getPluginsThatNeedDocumentation };\n"],"names":["getPluginsThatNeedDocumentation","strapi","config","defaultPlugins","userPluginsConfig","plugins","filter","plugin","undefined","length"],"mappings":"AAIA,MAAMA,+BAAAA,GAAkC,CAACC,MAAAA,EAAqBC,MAAAA,GAAAA;;AAE5D,IAAA,MAAMC,cAAAA,GAAiB;AAAC,QAAA,QAAA;AAAU,QAAA;AAAoB,KAAA;;AAGtD,IAAA,MAAMC,iBAAAA,GAAoBF,MAAM,CAAC,iBAAA,CAAkB,CAACG,OAAO;AAE3D,IAAA,IAAID,sBAAsB,IAAA,EAAM;;QAE9B,OAAOD,cAAAA,CAAeG,MAAM,CAAC,CAACC,SAAWN,MAAAA,CAAOM,MAAM,CAACA,MAAAA,CAAAA,KAAYC,SAAAA,CAAAA;AACrE,IAAA;IAEA,IAAIJ,iBAAAA,CAAkBK,MAAM,EAAE;;QAE5B,OAAOL,iBAAAA;AACT,IAAA;;AAGA,IAAA,OAAO,EAAE;AACX;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentation.d.ts","sourceRoot":"","sources":["../../../../server/src/controllers/documentation.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;;kBA2BL,GAAG,CAAC,OAAO;eAkBd,GAAG,CAAC,OAAO,QAAQ,GAAG,CAAC,IAAI;mBA4DvB,GAAG,CAAC,OAAO,QAAQ,GAAG,CAAC,IAAI;eA4C/B,GAAG,CAAC,OAAO;
|
|
1
|
+
{"version":3,"file":"documentation.d.ts","sourceRoot":"","sources":["../../../../server/src/controllers/documentation.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;;kBA2BL,GAAG,CAAC,OAAO;eAkBd,GAAG,CAAC,OAAO,QAAQ,GAAG,CAAC,IAAI;mBA4DvB,GAAG,CAAC,OAAO,QAAQ,GAAG,CAAC,IAAI;eA4C/B,GAAG,CAAC,OAAO;uBA4BH,GAAG,CAAC,OAAO;mBAwBf,GAAG,CAAC,OAAO;wBAwBN,GAAG,CAAC,OAAO;;AAvMvC,wBAwNE"}
|
|
@@ -79,7 +79,7 @@ declare const _default: {
|
|
|
79
79
|
excludedFromGeneration: string[];
|
|
80
80
|
excludeFromGeneration(api: string | string[]): void;
|
|
81
81
|
isEnabled(name: string): boolean;
|
|
82
|
-
registerOverride(override: Partial<import("./types").PluginConfig
|
|
82
|
+
registerOverride(override: Partial<import("./types").PluginConfig> | string, opts?: {
|
|
83
83
|
pluginOrigin: string;
|
|
84
84
|
excludeFromGeneration?: string[];
|
|
85
85
|
}): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../server/src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../server/src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qCAcgrB,CAAC;;;;;AARvtB,wBAOE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-component-schema.d.ts","sourceRoot":"","sources":["../../../../../server/src/services/helpers/build-component-schema.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,GAAG,EAAW,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"build-component-schema.d.ts","sourceRoot":"","sources":["../../../../../server/src/services/helpers/build-component-schema.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,GAAG,EAAW,MAAM,aAAa,CAAC;AAoKhD,QAAA,MAAM,4BAA4B,GAAI,KAAK,GAAG,wBAS7C,CAAC;AAEF,QAAA,MAAM,oBAAoB,GACxB,KAAK,GAAG,EACR,+CAA6D,OAQ9D,CAAC;AAEF,eAAe,oBAAoB,CAAC;AACpC,OAAO,EAAE,4BAA4B,EAAE,CAAC"}
|
|
@@ -29,7 +29,7 @@ declare const _default: {
|
|
|
29
29
|
excludedFromGeneration: string[];
|
|
30
30
|
excludeFromGeneration(api: string | string[]): void;
|
|
31
31
|
isEnabled(name: string): boolean;
|
|
32
|
-
registerOverride(override: Partial<import("../types").PluginConfig
|
|
32
|
+
registerOverride(override: Partial<import("../types").PluginConfig> | string, opts?: {
|
|
33
33
|
pluginOrigin: string;
|
|
34
34
|
excludeFromGeneration?: string[];
|
|
35
35
|
}): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../server/src/services/index.ts"],"names":[],"mappings":"AAEA,OAAsB,EAAE,KAAK,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAiB,EAAE,KAAK,eAAe,EAAE,MAAM,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../server/src/services/index.ts"],"names":[],"mappings":"AAEA,OAAsB,EAAE,KAAK,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAiB,EAAE,KAAK,eAAe,EAAE,MAAM,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iCAWwoB,CAAC;;;;AATrsB,wBAGE;AAEF,MAAM,MAAM,QAAQ,GAAG;IACrB,aAAa,EAAE,oBAAoB,CAAC;IACpC,QAAQ,EAAE,eAAe,CAAC;CAC3B,CAAC"}
|
|
@@ -12,7 +12,7 @@ declare const createService: ({ strapi }: {
|
|
|
12
12
|
*/
|
|
13
13
|
excludeFromGeneration(api: string | string[]): void;
|
|
14
14
|
isEnabled(name: string): boolean;
|
|
15
|
-
registerOverride(override: Partial<PluginConfig
|
|
15
|
+
registerOverride(override: Partial<PluginConfig> | string, opts?: {
|
|
16
16
|
pluginOrigin: string;
|
|
17
17
|
excludeFromGeneration?: string[];
|
|
18
18
|
}): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"override.d.ts","sourceRoot":"","sources":["../../../../server/src/services/override.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAG1C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE7C,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC;AAE/D,QAAA,MAAM,aAAa,GAAI,YAAY;IAAE,MAAM,EAAE,IAAI,CAAC,MAAM,CAAA;CAAE;;;IAOtD;;;OAGG;+BACwB,MAAM,GAAG,MAAM,EAAE;oBAU5B,MAAM;+BAKV,OAAO,CAAC,YAAY,CAAC,
|
|
1
|
+
{"version":3,"file":"override.d.ts","sourceRoot":"","sources":["../../../../server/src/services/override.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAG1C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE7C,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC;AAE/D,QAAA,MAAM,aAAa,GAAI,YAAY;IAAE,MAAM,EAAE,IAAI,CAAC,MAAM,CAAA;CAAE;;;IAOtD;;;OAGG;+BACwB,MAAM,GAAG,MAAM,EAAE;oBAU5B,MAAM;+BAKV,OAAO,CAAC,YAAY,CAAC,GAAG,MAAM,SACjC;QAAE,YAAY,EAAE,MAAM,CAAC;QAAC,qBAAqB,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE;CA+CtE,CAAC;AAEF,eAAe,aAAa,CAAC"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
+
import type { Core } from '@strapi/types';
|
|
1
2
|
import type { PluginConfig } from '../../types';
|
|
2
|
-
declare const getPluginsThatNeedDocumentation: (config: PluginConfig) => string[];
|
|
3
|
+
declare const getPluginsThatNeedDocumentation: (strapi: Core.Strapi, config: PluginConfig) => string[];
|
|
3
4
|
export { getPluginsThatNeedDocumentation };
|
|
4
5
|
//# sourceMappingURL=get-plugins-that-need-documentation.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-plugins-that-need-documentation.d.ts","sourceRoot":"","sources":["../../../../../server/src/services/utils/get-plugins-that-need-documentation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,QAAA,MAAM,+BAA+B,GAAI,QAAQ,YAAY,
|
|
1
|
+
{"version":3,"file":"get-plugins-that-need-documentation.d.ts","sourceRoot":"","sources":["../../../../../server/src/services/utils/get-plugins-that-need-documentation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE1C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,QAAA,MAAM,+BAA+B,GAAI,QAAQ,IAAI,CAAC,MAAM,EAAE,QAAQ,YAAY,aAmBjF,CAAC;AAEF,OAAO,EAAE,+BAA+B,EAAE,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@strapi/plugin-documentation",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.61.1",
|
|
4
4
|
"description": "Create an OpenAPI Document and visualize your API with SWAGGER UI.",
|
|
5
5
|
"homepage": "https://strapi.io",
|
|
6
6
|
"bugs": {
|
|
@@ -57,16 +57,16 @@
|
|
|
57
57
|
"test:front:watch": "run -T cross-env IS_EE=true jest --config ./jest.config.front.js --watchAll",
|
|
58
58
|
"test:ts:front": "run -T tsc -p admin/tsconfig.json",
|
|
59
59
|
"test:ts:back": "run -T tsc -p server/tsconfig.json",
|
|
60
|
-
"
|
|
61
|
-
"test:unit:
|
|
62
|
-
"watch": "
|
|
60
|
+
"watch": "run -T rollup -c -w",
|
|
61
|
+
"test:unit:vitest": "vitest run",
|
|
62
|
+
"test:unit:vitest:watch": "vitest --watch"
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
65
|
"@reduxjs/toolkit": "1.9.7",
|
|
66
|
-
"@strapi/admin": "5.
|
|
66
|
+
"@strapi/admin": "5.61.1",
|
|
67
67
|
"@strapi/design-system": "2.2.4",
|
|
68
68
|
"@strapi/icons": "2.2.4",
|
|
69
|
-
"@strapi/utils": "5.
|
|
69
|
+
"@strapi/utils": "5.61.1",
|
|
70
70
|
"bcryptjs": "2.4.3",
|
|
71
71
|
"cheerio": "^1.2.0",
|
|
72
72
|
"formik": "2.4.9",
|
|
@@ -82,9 +82,9 @@
|
|
|
82
82
|
},
|
|
83
83
|
"devDependencies": {
|
|
84
84
|
"@apidevtools/swagger-parser": "^10.1.0",
|
|
85
|
-
"@strapi/admin-test-utils": "5.
|
|
86
|
-
"@strapi/strapi": "5.
|
|
87
|
-
"@strapi/types": "5.
|
|
85
|
+
"@strapi/admin-test-utils": "5.61.1",
|
|
86
|
+
"@strapi/strapi": "5.61.1",
|
|
87
|
+
"@strapi/types": "5.61.1",
|
|
88
88
|
"@testing-library/dom": "10.4.1",
|
|
89
89
|
"@testing-library/jest-dom": "6.9.1",
|
|
90
90
|
"@testing-library/react": "16.3.2",
|
|
@@ -92,7 +92,7 @@
|
|
|
92
92
|
"@types/fs-extra": "11.0.4",
|
|
93
93
|
"@types/jest": "29.5.2",
|
|
94
94
|
"@types/koa": "2.15.2",
|
|
95
|
-
"@types/node": "20.
|
|
95
|
+
"@types/node": "22.20.0",
|
|
96
96
|
"@types/swagger-ui-dist": "3.30.4",
|
|
97
97
|
"jest": "29.6.0",
|
|
98
98
|
"koa": "2.16.4",
|
|
@@ -103,7 +103,9 @@
|
|
|
103
103
|
"react": "18.3.1",
|
|
104
104
|
"react-dom": "18.3.1",
|
|
105
105
|
"react-router-dom": "6.30.6",
|
|
106
|
-
"styled-components": "6.4.1"
|
|
106
|
+
"styled-components": "6.4.1",
|
|
107
|
+
"vitest": "catalog:",
|
|
108
|
+
"vitest-config": "5.61.1"
|
|
107
109
|
},
|
|
108
110
|
"peerDependencies": {
|
|
109
111
|
"@strapi/strapi": "^5.0.0",
|
|
@@ -113,7 +115,7 @@
|
|
|
113
115
|
"styled-components": "^6.0.0"
|
|
114
116
|
},
|
|
115
117
|
"engines": {
|
|
116
|
-
"node": ">=
|
|
118
|
+
"node": ">=22.0.0 <=26.x.x",
|
|
117
119
|
"npm": ">=6.0.0"
|
|
118
120
|
},
|
|
119
121
|
"strapi": {
|