node_modules ignore

This commit is contained in:
2025-05-08 23:43:47 +02:00
parent e19d52f172
commit 4574544c9f
65041 changed files with 10593536 additions and 0 deletions

37
server/node_modules/@strapi/core/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,37 @@
Copyright (c) 2015-present Strapi Solutions SAS
Portions of the Strapi software are licensed as follows:
* All software that resides under an "ee/" directory (the “EE Software”), if that directory exists, is licensed under the license defined below.
Enterprise License
If you or the company you represent has entered into a written agreement referencing the Enterprise Edition of the Strapi source code available at
https://github.com/strapi/strapi, then such agreement applies to your use of the Enterprise Edition of the Strapi Software. If you or the company you
represent is using the Enterprise Edition of the Strapi Software in connection with a subscription to our cloud offering, then the agreement you have
agreed to with respect to our cloud offering and the licenses included in such agreement apply to your use of the Enterprise Edition of the Strapi Software.
Otherwise, the Strapi Enterprise Software License Agreement (found here https://strapi.io/enterprise-terms) applies to your use of the Enterprise Edition of the Strapi Software.
BY ACCESSING OR USING THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE RELEVANT REFERENCED AGREEMENT.
IF YOU ARE NOT AUTHORIZED TO ACCEPT THESE TERMS ON BEHALF OF THE COMPANY YOU REPRESENT OR IF YOU DO NOT AGREE TO ALL OF THE RELEVANT TERMS AND CONDITIONS REFERENCED AND YOU
HAVE NOT OTHERWISE EXECUTED A WRITTEN AGREEMENT WITH STRAPI, YOU ARE NOT AUTHORIZED TO ACCESS OR USE OR ALLOW ANY USER TO ACCESS OR USE ANY PART OF
THE ENTERPRISE EDITION OF THE STRAPI SOFTWARE. YOUR ACCESS RIGHTS ARE CONDITIONAL ON YOUR CONSENT TO THE RELEVANT REFERENCED TERMS TO THE EXCLUSION OF ALL OTHER TERMS;
IF THE RELEVANT REFERENCED TERMS ARE CONSIDERED AN OFFER BY YOU, ACCEPTANCE IS EXPRESSLY LIMITED TO THE RELEVANT REFERENCED TERMS.
* All software outside of the above-mentioned directories or restrictions above is available under the "MIT Expat" license as set forth below.
MIT Expat License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1
server/node_modules/@strapi/core/README.md generated vendored Normal file
View File

@@ -0,0 +1 @@
# `@strapi/core`

91
server/node_modules/@strapi/core/dist/Strapi.d.ts generated vendored Normal file
View File

@@ -0,0 +1,91 @@
import { Logger } from '@strapi/logger';
import { Database } from '@strapi/database';
import type { Core, Modules, UID, Schema } from '@strapi/types';
import { Container } from './container';
import { FeaturesService } from './services/features';
declare class Strapi extends Container implements Core.Strapi {
app: any;
isLoaded: boolean;
internal_config: Record<string, unknown>;
constructor(opts: StrapiOptions);
get admin(): Core.Module;
get EE(): boolean;
get ee(): Core.Strapi['ee'];
get dirs(): Core.StrapiDirectories;
get reload(): Core.Reloader;
get db(): Database;
get requestContext(): Modules.RequestContext.RequestContext;
get customFields(): Modules.CustomFields.CustomFields;
get entityValidator(): Modules.EntityValidator.EntityValidator;
/**
* @deprecated `strapi.entityService` will be removed in the next major version
*/
get entityService(): Modules.EntityService.EntityService;
get documents(): Modules.Documents.Service;
get features(): FeaturesService;
get fetch(): Modules.Fetch.Fetch;
get cron(): Modules.Cron.CronService;
get log(): Logger;
get startupLogger(): Core.StartupLogger;
get eventHub(): Modules.EventHub.EventHub;
get fs(): Core.StrapiFS;
get server(): Modules.Server.Server;
get telemetry(): Modules.Metrics.TelemetryService;
get store(): Modules.CoreStore.CoreStore;
get config(): any;
get services(): any;
service(uid: UID.Service): any;
get controllers(): any;
controller(uid: UID.Controller): any;
get contentTypes(): Schema.ContentTypes;
contentType(name: UID.ContentType): any;
get components(): Schema.Components;
get policies(): any;
policy(name: string): any;
get middlewares(): any;
middleware(name: string): any;
get plugins(): Record<string, Core.Plugin>;
plugin(name: string): Core.Plugin;
get hooks(): any;
hook(name: string): any;
get apis(): any;
api(name: string): Core.Module;
get auth(): any;
get contentAPI(): any;
get sanitizers(): any;
get validators(): any;
start(): Promise<this>;
registerInternalServices(): void;
sendStartupTelemetry(): void;
openAdmin({ isInitialized }: {
isInitialized: boolean;
}): Promise<void>;
postListen(): Promise<void>;
/**
* Add behaviors to the server
*/
listen(): Promise<void>;
stopWithError(err: unknown, customMessage?: string): never;
stop(exitCode?: number): never;
load(): Promise<this>;
register(): Promise<this>;
bootstrap(): Promise<this>;
configureGlobalProxy(): void;
destroy(): Promise<void>;
runPluginsLifecycles(lifecycleName: 'register' | 'bootstrap' | 'destroy'): Promise<void>;
runUserLifecycles(lifecycleName: 'register' | 'bootstrap' | 'destroy'): Promise<void>;
getModel(uid: UID.ContentType): Schema.ContentType;
getModel(uid: UID.Component): Schema.Component;
/**
* @deprecated Use `strapi.db.query` instead
*/
query(uid: UID.Schema): import("@strapi/database/dist/entity-manager").Repository;
}
export interface StrapiOptions {
appDir: string;
distDir: string;
autoReload?: boolean;
serveAdminPanel?: boolean;
}
export default Strapi;
//# sourceMappingURL=Strapi.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Strapi.d.ts","sourceRoot":"","sources":["../src/Strapi.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,OAAO,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAQhE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAgBxC,OAAO,EAAE,eAAe,EAAyB,MAAM,qBAAqB,CAAC;AAM7E,cAAM,MAAO,SAAQ,SAAU,YAAW,IAAI,CAAC,MAAM;IACnD,GAAG,EAAE,GAAG,CAAC;IAET,QAAQ,EAAE,OAAO,CAAS;IAE1B,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAM;gBAElC,IAAI,EAAE,aAAa;IAY/B,IAAI,KAAK,IAAI,IAAI,CAAC,MAAM,CAEvB;IAED,IAAI,EAAE,IAAI,OAAO,CAEhB;IAED,IAAI,EAAE,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAE1B;IAED,IAAI,IAAI,IAAI,IAAI,CAAC,iBAAiB,CAEjC;IAED,IAAI,MAAM,IAAI,IAAI,CAAC,QAAQ,CAE1B;IAED,IAAI,EAAE,IAAI,QAAQ,CAEjB;IAED,IAAI,cAAc,IAAI,OAAO,CAAC,cAAc,CAAC,cAAc,CAE1D;IAED,IAAI,YAAY,IAAI,OAAO,CAAC,YAAY,CAAC,YAAY,CAEpD;IAED,IAAI,eAAe,IAAI,OAAO,CAAC,eAAe,CAAC,eAAe,CAE7D;IAED;;OAEG;IACH,IAAI,aAAa,IAAI,OAAO,CAAC,aAAa,CAAC,aAAa,CAEvD;IAED,IAAI,SAAS,IAAI,OAAO,CAAC,SAAS,CAAC,OAAO,CAEzC;IAED,IAAI,QAAQ,IAAI,eAAe,CAE9B;IAED,IAAI,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,KAAK,CAE/B;IAED,IAAI,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,WAAW,CAEnC;IAED,IAAI,GAAG,IAAI,MAAM,CAEhB;IAED,IAAI,aAAa,IAAI,IAAI,CAAC,aAAa,CAEtC;IAED,IAAI,QAAQ,IAAI,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAExC;IAED,IAAI,EAAE,IAAI,IAAI,CAAC,QAAQ,CAEtB;IAED,IAAI,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,CAElC;IAED,IAAI,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC,gBAAgB,CAEhD;IAED,IAAI,KAAK,IAAI,OAAO,CAAC,SAAS,CAAC,SAAS,CAEvC;IAED,IAAI,MAAM,QAET;IAED,IAAI,QAAQ,QAEX;IAED,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO;IAIxB,IAAI,WAAW,QAEd;IAED,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,UAAU;IAI9B,IAAI,YAAY,IAAI,MAAM,CAAC,YAAY,CAEtC;IAED,WAAW,CAAC,IAAI,EAAE,GAAG,CAAC,WAAW;IAIjC,IAAI,UAAU,IAAI,MAAM,CAAC,UAAU,CAElC;IAED,IAAI,QAAQ,QAEX;IAED,MAAM,CAAC,IAAI,EAAE,MAAM;IAInB,IAAI,WAAW,QAEd;IAED,UAAU,CAAC,IAAI,EAAE,MAAM;IAIvB,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAEzC;IAED,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC,MAAM;IAIjC,IAAI,KAAK,QAER;IAED,IAAI,CAAC,IAAI,EAAE,MAAM;IAIjB,IAAI,IAAI,QAEP;IAED,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC,MAAM;IAI9B,IAAI,IAAI,QAEP;IAED,IAAI,UAAU,QAEb;IAED,IAAI,UAAU,QAEb;IAED,IAAI,UAAU,QAEb;IAEK,KAAK;IAeX,wBAAwB;IA6CxB,oBAAoB;IAwBd,SAAS,CAAC,EAAE,aAAa,EAAE,EAAE;QAAE,aAAa,EAAE,OAAO,CAAA;KAAE;IAevD,UAAU;IAUhB;;OAEG;IACG,MAAM;IAwBZ,aAAa,CAAC,GAAG,EAAE,OAAO,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,KAAK;IAU1D,IAAI,CAAC,QAAQ,SAAI,GAAG,KAAK;IAWnB,IAAI;IASJ,QAAQ;IAiBR,SAAS;IAkEf,oBAAoB;IAsBd,OAAO;IAwBP,oBAAoB,CAAC,aAAa,EAAE,UAAU,GAAG,WAAW,GAAG,SAAS;IAKxE,iBAAiB,CAAC,aAAa,EAAE,UAAU,GAAG,WAAW,GAAG,SAAS;IAQ3E,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW;IAClD,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS;IAW9C;;OAEG;IACH,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM;CAGtB;AAED,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,eAAe,MAAM,CAAC"}

455
server/node_modules/@strapi/core/dist/Strapi.js generated vendored Normal file
View File

@@ -0,0 +1,455 @@
'use strict';
var globalAgent = require('global-agent');
var path = require('path');
var _ = require('lodash');
var fp = require('lodash/fp');
var logger = require('@strapi/logger');
var database = require('@strapi/database');
var tsUtils = require('@strapi/typescript-utils');
var index$8 = require('./configuration/index.js');
var factories = require('./factories.js');
var openBrowser = require('./utils/open-browser.js');
var isInitialized = require('./utils/is-initialized.js');
var index = require('./ee/index.js');
require('package-json');
require('configstore');
require('semver');
require('boxen');
require('chalk');
require('@strapi/utils');
var fetch = require('./utils/fetch.js');
var convertCustomFieldType = require('./utils/convert-custom-field-type.js');
var startupLogger = require('./utils/startup-logger.js');
var transformContentTypesToModels = require('./utils/transform-content-types-to-models.js');
var lifecycles = require('./utils/lifecycles.js');
require('node:path');
var container = require('./container.js');
var fs = require('./services/fs.js');
var eventHub = require('./services/event-hub.js');
var index$3 = require('./services/server/index.js');
var reloader = require('./services/reloader.js');
var index$7 = require('./providers/index.js');
var index$5 = require('./services/entity-service/index.js');
var queryParams = require('./services/query-params.js');
var index$4 = require('./services/entity-validator/index.js');
var requestContext = require('./services/request-context.js');
var index$2 = require('./services/auth/index.js');
var customFields = require('./services/custom-fields.js');
var index$1 = require('./services/content-api/index.js');
var dynamicZones = require('./services/utils/dynamic-zones.js');
var features = require('./services/features.js');
var index$6 = require('./services/document-service/index.js');
var coreStore = require('./services/core-store.js');
var config = require('./services/config.js');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var globalAgent__namespace = /*#__PURE__*/_interopNamespaceDefault(globalAgent);
class Strapi extends container.Container {
get admin() {
return this.get('admin');
}
get EE() {
return index.isEE;
}
get ee() {
return index;
}
get dirs() {
return this.config.get('dirs');
}
get reload() {
return this.get('reload');
}
get db() {
return this.get('db');
}
get requestContext() {
return this.get('requestContext');
}
get customFields() {
return this.get('customFields');
}
get entityValidator() {
return this.get('entityValidator');
}
/**
* @deprecated `strapi.entityService` will be removed in the next major version
*/ get entityService() {
return this.get('entityService');
}
get documents() {
return this.get('documents');
}
get features() {
return this.get('features');
}
get fetch() {
return this.get('fetch');
}
get cron() {
return this.get('cron');
}
get log() {
return this.get('logger');
}
get startupLogger() {
return this.get('startupLogger');
}
get eventHub() {
return this.get('eventHub');
}
get fs() {
return this.get('fs');
}
get server() {
return this.get('server');
}
get telemetry() {
return this.get('telemetry');
}
get store() {
return this.get('coreStore');
}
get config() {
return this.get('config');
}
get services() {
return this.get('services').getAll();
}
service(uid) {
return this.get('services').get(uid);
}
get controllers() {
return this.get('controllers').getAll();
}
controller(uid) {
return this.get('controllers').get(uid);
}
get contentTypes() {
return this.get('content-types').getAll();
}
contentType(name) {
return this.get('content-types').get(name);
}
get components() {
return this.get('components').getAll();
}
get policies() {
return this.get('policies').getAll();
}
policy(name) {
return this.get('policies').get(name);
}
get middlewares() {
return this.get('middlewares').getAll();
}
middleware(name) {
return this.get('middlewares').get(name);
}
get plugins() {
return this.get('plugins').getAll();
}
plugin(name) {
return this.get('plugins').get(name);
}
get hooks() {
return this.get('hooks').getAll();
}
hook(name) {
return this.get('hooks').get(name);
}
get apis() {
return this.get('apis').getAll();
}
api(name) {
return this.get('apis').get(name);
}
get auth() {
return this.get('auth');
}
get contentAPI() {
return this.get('content-api');
}
get sanitizers() {
return this.get('sanitizers');
}
get validators() {
return this.get('validators');
}
async start() {
try {
if (!this.isLoaded) {
await this.load();
}
await this.listen();
return this;
} catch (error) {
return this.stopWithError(error);
}
}
// TODO: split into more providers
registerInternalServices() {
const config$1 = config.createConfigProvider(this.internal_config, this);
const logger$1 = logger.createLogger({
level: 'http',
...config$1.get('logger'),
...config$1.get('server.logger.config')
});
// Instantiate the Strapi container
this.add('config', ()=>config$1).add('query-params', queryParams(this)).add('content-api', index$1(this)).add('auth', index$2()).add('server', ()=>index$3.createServer(this)).add('fs', ()=>fs(this)).add('eventHub', ()=>eventHub()).add('startupLogger', ()=>startupLogger.createStartupLogger(this)).add('logger', ()=>logger$1).add('fetch', ()=>fetch.createStrapiFetch(this)).add('features', ()=>features.createFeaturesService(this)).add('requestContext', requestContext).add('customFields', customFields(this)).add('entityValidator', index$4).add('entityService', ()=>index$5({
strapi: this,
db: this.db
})).add('documents', ()=>index$6.createDocumentService(this)).add('db', ()=>{
const tsDir = tsUtils.resolveOutDirSync(this.dirs.app.root);
const tsMigrationsEnabled = this.config.get('database.settings.useTypescriptMigrations') === true && tsDir;
const projectDir = tsMigrationsEnabled ? tsDir : this.dirs.app.root;
return new database.Database(_.merge(this.config.get('database'), {
logger: logger$1,
settings: {
migrations: {
dir: path.join(projectDir, 'database/migrations')
}
}
}));
}).add('reload', ()=>reloader.createReloader(this));
}
sendStartupTelemetry() {
// Emit started event.
// do not await to avoid slower startup
// This event is anonymous
this.telemetry.send('didStartServer', {
groupProperties: {
database: this.config.get('database.connection.client'),
plugins: Object.keys(this.plugins),
numberOfAllContentTypes: _.size(this.contentTypes),
numberOfComponents: _.size(this.components),
numberOfDynamicZones: dynamicZones(),
numberOfCustomControllers: Object.values(this.controllers).filter(// TODO: Fix this at the content API loader level to prevent future types issues
(controller)=>controller !== undefined && factories.isCustomController(controller)).length,
environment: this.config.environment
}
}).catch(this.log.error);
}
async openAdmin({ isInitialized }) {
const shouldOpenAdmin = this.config.get('environment') === 'development' && this.config.get('admin.autoOpen', true) !== false;
if (shouldOpenAdmin && !isInitialized) {
try {
await openBrowser.openBrowser(this.config);
this.telemetry.send('didOpenTab');
} catch (e) {
this.telemetry.send('didNotOpenTab');
}
}
}
async postListen() {
const isInitialized$1 = await isInitialized.isInitialized(this);
this.startupLogger.logStartupMessage({
isInitialized: isInitialized$1
});
this.log.info('Strapi started successfully');
this.sendStartupTelemetry();
this.openAdmin({
isInitialized: isInitialized$1
});
}
/**
* Add behaviors to the server
*/ async listen() {
return new Promise((resolve, reject)=>{
const onListen = async ()=>{
try {
await this.postListen();
resolve();
} catch (error) {
reject(error);
}
};
const listenSocket = this.config.get('server.socket');
if (listenSocket) {
this.server.listen(listenSocket, onListen);
} else {
const { host, port } = this.config.get('server');
this.server.listen(port, host, onListen);
}
});
}
stopWithError(err, customMessage) {
this.log.debug(`⛔️ Server wasn't able to start properly.`);
if (customMessage) {
this.log.error(customMessage);
}
this.log.error(err);
return this.stop();
}
stop(exitCode = 1) {
this.destroy();
if (this.config.get('autoReload')) {
process.send?.('stop');
}
// Kill process
process.exit(exitCode);
}
async load() {
await this.register();
await this.bootstrap();
this.isLoaded = true;
return this;
}
async register() {
// @ts-expect-error: init is internal
this.ee.init(this.dirs.app.root, this.log);
for (const provider of index$7.providers){
await provider.register?.(this);
}
await this.runPluginsLifecycles(lifecycles.LIFECYCLES.REGISTER);
await this.runUserLifecycles(lifecycles.LIFECYCLES.REGISTER);
// NOTE: Swap type customField for underlying data type
convertCustomFieldType.convertCustomFieldType(this);
return this;
}
async bootstrap() {
this.configureGlobalProxy();
const models = [
...transformContentTypesToModels.transformContentTypesToModels([
...Object.values(this.contentTypes),
...Object.values(this.components)
], this.db.metadata.identifiers),
...this.get('models').get()
];
await this.db.init({
models
});
let oldContentTypes;
if (await this.db.getSchemaConnection().hasTable(coreStore.coreStoreModel.tableName)) {
oldContentTypes = await this.store.get({
type: 'strapi',
name: 'content_types',
key: 'schema'
});
}
await this.hook('strapi::content-types.beforeSync').call({
oldContentTypes,
contentTypes: this.contentTypes
});
const status = await this.db.schema.sync();
// if schemas have changed, run repairs
if (status === 'CHANGED') {
await this.db.repair.removeOrphanMorphType({
pivot: 'component_type'
});
}
if (this.EE) {
await index.checkLicense({
strapi: this
});
}
await this.hook('strapi::content-types.afterSync').call({
oldContentTypes,
contentTypes: this.contentTypes
});
await this.store.set({
type: 'strapi',
name: 'content_types',
key: 'schema',
value: this.contentTypes
});
await this.server.initMiddlewares();
this.server.initRouting();
await this.contentAPI.permissions.registerActions();
await this.runPluginsLifecycles(lifecycles.LIFECYCLES.BOOTSTRAP);
for (const provider of index$7.providers){
await provider.bootstrap?.(this);
}
await this.runUserLifecycles(lifecycles.LIFECYCLES.BOOTSTRAP);
return this;
}
configureGlobalProxy() {
const globalProxy = this.config.get('server.proxy.global');
const httpProxy = this.config.get('server.proxy.http') || globalProxy;
const httpsProxy = this.config.get('server.proxy.https') || globalProxy;
if (!httpProxy && !httpsProxy) {
return;
}
globalAgent__namespace.bootstrap();
if (httpProxy) {
this.log.info(`Using HTTP proxy: ${httpProxy}`);
global.GLOBAL_AGENT.HTTP_PROXY = httpProxy;
}
if (httpsProxy) {
this.log.info(`Using HTTPS proxy: ${httpsProxy}`);
global.GLOBAL_AGENT.HTTPS_PROXY = httpsProxy;
}
}
async destroy() {
this.log.info('Shutting down Strapi');
await this.runPluginsLifecycles(lifecycles.LIFECYCLES.DESTROY);
for (const provider of index$7.providers){
await provider.destroy?.(this);
}
await this.runUserLifecycles(lifecycles.LIFECYCLES.DESTROY);
await this.server.destroy();
this.eventHub.destroy();
await this.db?.destroy();
process.removeAllListeners();
// @ts-expect-error: Allow clean delete of global.strapi to allow re-instanciation
delete global.strapi;
this.log.info('Strapi has been shut down');
}
async runPluginsLifecycles(lifecycleName) {
// plugins
await this.get('modules')[lifecycleName]();
}
async runUserLifecycles(lifecycleName) {
// user
const userLifecycleFunction = this.app && this.app[lifecycleName];
if (fp.isFunction(userLifecycleFunction)) {
await userLifecycleFunction({
strapi: this
});
}
}
getModel(uid) {
if (uid in this.contentTypes) {
return this.contentTypes[uid];
}
if (uid in this.components) {
return this.components[uid];
}
}
/**
* @deprecated Use `strapi.db.query` instead
*/ query(uid) {
return this.db.query(uid);
}
constructor(opts){
super();
this.isLoaded = false;
this.internal_config = {};
this.internal_config = index$8.loadConfiguration(opts);
this.registerInternalServices();
for (const provider of index$7.providers){
provider.init?.(this);
}
}
}
module.exports = Strapi;
//# sourceMappingURL=Strapi.js.map

1
server/node_modules/@strapi/core/dist/Strapi.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

434
server/node_modules/@strapi/core/dist/Strapi.mjs generated vendored Normal file
View File

@@ -0,0 +1,434 @@
import * as globalAgent from 'global-agent';
import path from 'path';
import _ from 'lodash';
import { isFunction } from 'lodash/fp';
import { createLogger } from '@strapi/logger';
import { Database } from '@strapi/database';
import tsUtils from '@strapi/typescript-utils';
import { loadConfiguration } from './configuration/index.mjs';
import { isCustomController } from './factories.mjs';
import { openBrowser } from './utils/open-browser.mjs';
import { isInitialized } from './utils/is-initialized.mjs';
import index from './ee/index.mjs';
import 'package-json';
import 'configstore';
import 'semver';
import 'boxen';
import 'chalk';
import '@strapi/utils';
import { createStrapiFetch } from './utils/fetch.mjs';
import { convertCustomFieldType } from './utils/convert-custom-field-type.mjs';
import { createStartupLogger } from './utils/startup-logger.mjs';
import { transformContentTypesToModels } from './utils/transform-content-types-to-models.mjs';
import { LIFECYCLES } from './utils/lifecycles.mjs';
import 'node:path';
import { Container } from './container.mjs';
import createStrapiFs from './services/fs.mjs';
import createEventHub from './services/event-hub.mjs';
import { createServer } from './services/server/index.mjs';
import { createReloader } from './services/reloader.mjs';
import { providers } from './providers/index.mjs';
import createEntityService from './services/entity-service/index.mjs';
import createQueryParamService from './services/query-params.mjs';
import entityValidator from './services/entity-validator/index.mjs';
import requestCtx from './services/request-context.mjs';
import createAuthentication from './services/auth/index.mjs';
import createCustomFields from './services/custom-fields.mjs';
import createContentAPI from './services/content-api/index.mjs';
import getNumberOfDynamicZones from './services/utils/dynamic-zones.mjs';
import { createFeaturesService } from './services/features.mjs';
import { createDocumentService } from './services/document-service/index.mjs';
import { coreStoreModel } from './services/core-store.mjs';
import { createConfigProvider } from './services/config.mjs';
class Strapi extends Container {
get admin() {
return this.get('admin');
}
get EE() {
return index.isEE;
}
get ee() {
return index;
}
get dirs() {
return this.config.get('dirs');
}
get reload() {
return this.get('reload');
}
get db() {
return this.get('db');
}
get requestContext() {
return this.get('requestContext');
}
get customFields() {
return this.get('customFields');
}
get entityValidator() {
return this.get('entityValidator');
}
/**
* @deprecated `strapi.entityService` will be removed in the next major version
*/ get entityService() {
return this.get('entityService');
}
get documents() {
return this.get('documents');
}
get features() {
return this.get('features');
}
get fetch() {
return this.get('fetch');
}
get cron() {
return this.get('cron');
}
get log() {
return this.get('logger');
}
get startupLogger() {
return this.get('startupLogger');
}
get eventHub() {
return this.get('eventHub');
}
get fs() {
return this.get('fs');
}
get server() {
return this.get('server');
}
get telemetry() {
return this.get('telemetry');
}
get store() {
return this.get('coreStore');
}
get config() {
return this.get('config');
}
get services() {
return this.get('services').getAll();
}
service(uid) {
return this.get('services').get(uid);
}
get controllers() {
return this.get('controllers').getAll();
}
controller(uid) {
return this.get('controllers').get(uid);
}
get contentTypes() {
return this.get('content-types').getAll();
}
contentType(name) {
return this.get('content-types').get(name);
}
get components() {
return this.get('components').getAll();
}
get policies() {
return this.get('policies').getAll();
}
policy(name) {
return this.get('policies').get(name);
}
get middlewares() {
return this.get('middlewares').getAll();
}
middleware(name) {
return this.get('middlewares').get(name);
}
get plugins() {
return this.get('plugins').getAll();
}
plugin(name) {
return this.get('plugins').get(name);
}
get hooks() {
return this.get('hooks').getAll();
}
hook(name) {
return this.get('hooks').get(name);
}
get apis() {
return this.get('apis').getAll();
}
api(name) {
return this.get('apis').get(name);
}
get auth() {
return this.get('auth');
}
get contentAPI() {
return this.get('content-api');
}
get sanitizers() {
return this.get('sanitizers');
}
get validators() {
return this.get('validators');
}
async start() {
try {
if (!this.isLoaded) {
await this.load();
}
await this.listen();
return this;
} catch (error) {
return this.stopWithError(error);
}
}
// TODO: split into more providers
registerInternalServices() {
const config = createConfigProvider(this.internal_config, this);
const logger = createLogger({
level: 'http',
...config.get('logger'),
...config.get('server.logger.config')
});
// Instantiate the Strapi container
this.add('config', ()=>config).add('query-params', createQueryParamService(this)).add('content-api', createContentAPI(this)).add('auth', createAuthentication()).add('server', ()=>createServer(this)).add('fs', ()=>createStrapiFs(this)).add('eventHub', ()=>createEventHub()).add('startupLogger', ()=>createStartupLogger(this)).add('logger', ()=>logger).add('fetch', ()=>createStrapiFetch(this)).add('features', ()=>createFeaturesService(this)).add('requestContext', requestCtx).add('customFields', createCustomFields(this)).add('entityValidator', entityValidator).add('entityService', ()=>createEntityService({
strapi: this,
db: this.db
})).add('documents', ()=>createDocumentService(this)).add('db', ()=>{
const tsDir = tsUtils.resolveOutDirSync(this.dirs.app.root);
const tsMigrationsEnabled = this.config.get('database.settings.useTypescriptMigrations') === true && tsDir;
const projectDir = tsMigrationsEnabled ? tsDir : this.dirs.app.root;
return new Database(_.merge(this.config.get('database'), {
logger,
settings: {
migrations: {
dir: path.join(projectDir, 'database/migrations')
}
}
}));
}).add('reload', ()=>createReloader(this));
}
sendStartupTelemetry() {
// Emit started event.
// do not await to avoid slower startup
// This event is anonymous
this.telemetry.send('didStartServer', {
groupProperties: {
database: this.config.get('database.connection.client'),
plugins: Object.keys(this.plugins),
numberOfAllContentTypes: _.size(this.contentTypes),
numberOfComponents: _.size(this.components),
numberOfDynamicZones: getNumberOfDynamicZones(),
numberOfCustomControllers: Object.values(this.controllers).filter(// TODO: Fix this at the content API loader level to prevent future types issues
(controller)=>controller !== undefined && isCustomController(controller)).length,
environment: this.config.environment
}
}).catch(this.log.error);
}
async openAdmin({ isInitialized }) {
const shouldOpenAdmin = this.config.get('environment') === 'development' && this.config.get('admin.autoOpen', true) !== false;
if (shouldOpenAdmin && !isInitialized) {
try {
await openBrowser(this.config);
this.telemetry.send('didOpenTab');
} catch (e) {
this.telemetry.send('didNotOpenTab');
}
}
}
async postListen() {
const isInitialized$1 = await isInitialized(this);
this.startupLogger.logStartupMessage({
isInitialized: isInitialized$1
});
this.log.info('Strapi started successfully');
this.sendStartupTelemetry();
this.openAdmin({
isInitialized: isInitialized$1
});
}
/**
* Add behaviors to the server
*/ async listen() {
return new Promise((resolve, reject)=>{
const onListen = async ()=>{
try {
await this.postListen();
resolve();
} catch (error) {
reject(error);
}
};
const listenSocket = this.config.get('server.socket');
if (listenSocket) {
this.server.listen(listenSocket, onListen);
} else {
const { host, port } = this.config.get('server');
this.server.listen(port, host, onListen);
}
});
}
stopWithError(err, customMessage) {
this.log.debug(`⛔️ Server wasn't able to start properly.`);
if (customMessage) {
this.log.error(customMessage);
}
this.log.error(err);
return this.stop();
}
stop(exitCode = 1) {
this.destroy();
if (this.config.get('autoReload')) {
process.send?.('stop');
}
// Kill process
process.exit(exitCode);
}
async load() {
await this.register();
await this.bootstrap();
this.isLoaded = true;
return this;
}
async register() {
// @ts-expect-error: init is internal
this.ee.init(this.dirs.app.root, this.log);
for (const provider of providers){
await provider.register?.(this);
}
await this.runPluginsLifecycles(LIFECYCLES.REGISTER);
await this.runUserLifecycles(LIFECYCLES.REGISTER);
// NOTE: Swap type customField for underlying data type
convertCustomFieldType(this);
return this;
}
async bootstrap() {
this.configureGlobalProxy();
const models = [
...transformContentTypesToModels([
...Object.values(this.contentTypes),
...Object.values(this.components)
], this.db.metadata.identifiers),
...this.get('models').get()
];
await this.db.init({
models
});
let oldContentTypes;
if (await this.db.getSchemaConnection().hasTable(coreStoreModel.tableName)) {
oldContentTypes = await this.store.get({
type: 'strapi',
name: 'content_types',
key: 'schema'
});
}
await this.hook('strapi::content-types.beforeSync').call({
oldContentTypes,
contentTypes: this.contentTypes
});
const status = await this.db.schema.sync();
// if schemas have changed, run repairs
if (status === 'CHANGED') {
await this.db.repair.removeOrphanMorphType({
pivot: 'component_type'
});
}
if (this.EE) {
await index.checkLicense({
strapi: this
});
}
await this.hook('strapi::content-types.afterSync').call({
oldContentTypes,
contentTypes: this.contentTypes
});
await this.store.set({
type: 'strapi',
name: 'content_types',
key: 'schema',
value: this.contentTypes
});
await this.server.initMiddlewares();
this.server.initRouting();
await this.contentAPI.permissions.registerActions();
await this.runPluginsLifecycles(LIFECYCLES.BOOTSTRAP);
for (const provider of providers){
await provider.bootstrap?.(this);
}
await this.runUserLifecycles(LIFECYCLES.BOOTSTRAP);
return this;
}
configureGlobalProxy() {
const globalProxy = this.config.get('server.proxy.global');
const httpProxy = this.config.get('server.proxy.http') || globalProxy;
const httpsProxy = this.config.get('server.proxy.https') || globalProxy;
if (!httpProxy && !httpsProxy) {
return;
}
globalAgent.bootstrap();
if (httpProxy) {
this.log.info(`Using HTTP proxy: ${httpProxy}`);
global.GLOBAL_AGENT.HTTP_PROXY = httpProxy;
}
if (httpsProxy) {
this.log.info(`Using HTTPS proxy: ${httpsProxy}`);
global.GLOBAL_AGENT.HTTPS_PROXY = httpsProxy;
}
}
async destroy() {
this.log.info('Shutting down Strapi');
await this.runPluginsLifecycles(LIFECYCLES.DESTROY);
for (const provider of providers){
await provider.destroy?.(this);
}
await this.runUserLifecycles(LIFECYCLES.DESTROY);
await this.server.destroy();
this.eventHub.destroy();
await this.db?.destroy();
process.removeAllListeners();
// @ts-expect-error: Allow clean delete of global.strapi to allow re-instanciation
delete global.strapi;
this.log.info('Strapi has been shut down');
}
async runPluginsLifecycles(lifecycleName) {
// plugins
await this.get('modules')[lifecycleName]();
}
async runUserLifecycles(lifecycleName) {
// user
const userLifecycleFunction = this.app && this.app[lifecycleName];
if (isFunction(userLifecycleFunction)) {
await userLifecycleFunction({
strapi: this
});
}
}
getModel(uid) {
if (uid in this.contentTypes) {
return this.contentTypes[uid];
}
if (uid in this.components) {
return this.components[uid];
}
}
/**
* @deprecated Use `strapi.db.query` instead
*/ query(uid) {
return this.db.query(uid);
}
constructor(opts){
super();
this.isLoaded = false;
this.internal_config = {};
this.internal_config = loadConfiguration(opts);
this.registerInternalServices();
for (const provider of providers){
provider.init?.(this);
}
}
}
export { Strapi as default };
//# sourceMappingURL=Strapi.mjs.map

1
server/node_modules/@strapi/core/dist/Strapi.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

10
server/node_modules/@strapi/core/dist/compile.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
interface Options {
appDir?: string;
ignoreDiagnostics?: boolean;
}
export default function compile(options?: Options): Promise<{
appDir: string;
distDir: any;
}>;
export {};
//# sourceMappingURL=compile.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../src/compile.ts"],"names":[],"mappings":"AAEA,UAAU,OAAO;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED,wBAA8B,OAAO,CAAC,OAAO,CAAC,EAAE,OAAO;;;GActD"}

27
server/node_modules/@strapi/core/dist/compile.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
'use strict';
var tsUtils = require('@strapi/typescript-utils');
async function compile(options) {
const { appDir = process.cwd(), ignoreDiagnostics = false } = options ?? {};
const isTSProject = await tsUtils.isUsingTypeScript(appDir);
const outDir = await tsUtils.resolveOutDir(appDir);
if (isTSProject) {
await tsUtils.compile(appDir, {
configOptions: {
options: {
incremental: true
},
ignoreDiagnostics
}
});
}
const distDir = isTSProject ? outDir : appDir;
return {
appDir,
distDir
};
}
module.exports = compile;
//# sourceMappingURL=compile.js.map

1
server/node_modules/@strapi/core/dist/compile.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"compile.js","sources":["../src/compile.ts"],"sourcesContent":["import tsUtils from '@strapi/typescript-utils';\n\ninterface Options {\n appDir?: string;\n ignoreDiagnostics?: boolean;\n}\n\nexport default async function compile(options?: Options) {\n const { appDir = process.cwd(), ignoreDiagnostics = false } = options ?? {};\n const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n const outDir = await tsUtils.resolveOutDir(appDir);\n\n if (isTSProject) {\n await tsUtils.compile(appDir, {\n configOptions: { options: { incremental: true }, ignoreDiagnostics },\n });\n }\n\n const distDir = isTSProject ? outDir : appDir;\n\n return { appDir, distDir };\n}\n"],"names":["compile","options","appDir","process","cwd","ignoreDiagnostics","isTSProject","tsUtils","isUsingTypeScript","outDir","resolveOutDir","configOptions","incremental","distDir"],"mappings":";;;;AAOe,eAAeA,QAAQC,OAAiB,EAAA;IACrD,MAAM,EAAEC,MAASC,GAAAA,OAAAA,CAAQC,GAAG,EAAE,EAAEC,iBAAAA,GAAoB,KAAK,EAAE,GAAGJ,OAAAA,IAAW,EAAC;AAC1E,IAAA,MAAMK,WAAc,GAAA,MAAMC,OAAQC,CAAAA,iBAAiB,CAACN,MAAAA,CAAAA;AACpD,IAAA,MAAMO,MAAS,GAAA,MAAMF,OAAQG,CAAAA,aAAa,CAACR,MAAAA,CAAAA;AAE3C,IAAA,IAAII,WAAa,EAAA;QACf,MAAMC,OAAAA,CAAQP,OAAO,CAACE,MAAQ,EAAA;YAC5BS,aAAe,EAAA;gBAAEV,OAAS,EAAA;oBAAEW,WAAa,EAAA;AAAK,iBAAA;AAAGP,gBAAAA;AAAkB;AACrE,SAAA,CAAA;AACF;IAEA,MAAMQ,OAAAA,GAAUP,cAAcG,MAASP,GAAAA,MAAAA;IAEvC,OAAO;AAAEA,QAAAA,MAAAA;AAAQW,QAAAA;AAAQ,KAAA;AAC3B;;;;"}

25
server/node_modules/@strapi/core/dist/compile.mjs generated vendored Normal file
View File

@@ -0,0 +1,25 @@
import tsUtils from '@strapi/typescript-utils';
async function compile(options) {
const { appDir = process.cwd(), ignoreDiagnostics = false } = options ?? {};
const isTSProject = await tsUtils.isUsingTypeScript(appDir);
const outDir = await tsUtils.resolveOutDir(appDir);
if (isTSProject) {
await tsUtils.compile(appDir, {
configOptions: {
options: {
incremental: true
},
ignoreDiagnostics
}
});
}
const distDir = isTSProject ? outDir : appDir;
return {
appDir,
distDir
};
}
export { compile as default };
//# sourceMappingURL=compile.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"compile.mjs","sources":["../src/compile.ts"],"sourcesContent":["import tsUtils from '@strapi/typescript-utils';\n\ninterface Options {\n appDir?: string;\n ignoreDiagnostics?: boolean;\n}\n\nexport default async function compile(options?: Options) {\n const { appDir = process.cwd(), ignoreDiagnostics = false } = options ?? {};\n const isTSProject = await tsUtils.isUsingTypeScript(appDir);\n const outDir = await tsUtils.resolveOutDir(appDir);\n\n if (isTSProject) {\n await tsUtils.compile(appDir, {\n configOptions: { options: { incremental: true }, ignoreDiagnostics },\n });\n }\n\n const distDir = isTSProject ? outDir : appDir;\n\n return { appDir, distDir };\n}\n"],"names":["compile","options","appDir","process","cwd","ignoreDiagnostics","isTSProject","tsUtils","isUsingTypeScript","outDir","resolveOutDir","configOptions","incremental","distDir"],"mappings":";;AAOe,eAAeA,QAAQC,OAAiB,EAAA;IACrD,MAAM,EAAEC,MAASC,GAAAA,OAAAA,CAAQC,GAAG,EAAE,EAAEC,iBAAAA,GAAoB,KAAK,EAAE,GAAGJ,OAAAA,IAAW,EAAC;AAC1E,IAAA,MAAMK,WAAc,GAAA,MAAMC,OAAQC,CAAAA,iBAAiB,CAACN,MAAAA,CAAAA;AACpD,IAAA,MAAMO,MAAS,GAAA,MAAMF,OAAQG,CAAAA,aAAa,CAACR,MAAAA,CAAAA;AAE3C,IAAA,IAAII,WAAa,EAAA;QACf,MAAMC,OAAAA,CAAQP,OAAO,CAACE,MAAQ,EAAA;YAC5BS,aAAe,EAAA;gBAAEV,OAAS,EAAA;oBAAEW,WAAa,EAAA;AAAK,iBAAA;AAAGP,gBAAAA;AAAkB;AACrE,SAAA,CAAA;AACF;IAEA,MAAMQ,OAAAA,GAAUP,cAAcG,MAASP,GAAAA,MAAAA;IAEvC,OAAO;AAAEA,QAAAA,MAAAA;AAAQW,QAAAA;AAAQ,KAAA;AAC3B;;;;"}

View File

@@ -0,0 +1,3 @@
declare const _default: (dir: string) => Record<string, unknown>;
export default _default;
//# sourceMappingURL=config-loader.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"config-loader.d.ts","sourceRoot":"","sources":["../../src/configuration/config-loader.ts"],"names":[],"mappings":"8BA2DqB,MAAM;AAA3B,wBAoFE"}

View File

@@ -0,0 +1,119 @@
'use strict';
var path = require('path');
var fs = require('fs');
var loadConfigFile = require('../utils/load-config-file.js');
const VALID_EXTENSIONS = [
'.js',
'.json'
];
// These filenames are restricted, but will also emit a warning that the filename is probably a mistake
const MISTAKEN_FILENAMES = {
middleware: 'middlewares',
plugin: 'plugins'
};
// the following are restricted to prevent conflicts with existing STRAPI_* env vars or root level config options
// must all be lowercase to match validator
const RESTRICTED_FILENAMES = [
// existing env vars
'uuid',
'hosting',
'license',
'enforce',
'disable',
'enable',
'telemetry',
// reserved for future internal use
'strapi',
'internal',
// root level config options
// TODO: it would be better to move these out of the root config and allow them to be loaded
'launchedAt',
'serveAdminPanel',
'autoReload',
'environment',
'packageJsonStrapi',
'info',
'autoReload',
'dirs',
// probably mistaken/typo filenames
...Object.keys(MISTAKEN_FILENAMES)
];
// Existing Strapi configuration files
const STRAPI_CONFIG_FILENAMES = [
'admin',
'server',
'api',
'database',
'middlewares',
'plugins',
'features'
];
// Note: we don't have access to strapi logger at this point so we can't use it
const logWarning = (message)=>{
console.warn(message);
};
var loadConfigDir = ((dir)=>{
if (!fs.existsSync(dir)) return {};
const allFiles = fs.readdirSync(dir, {
withFileTypes: true
});
const seenFilenames = new Set();
const configFiles = allFiles.reduce((acc, file)=>{
const baseName = path.basename(file.name, path.extname(file.name));
const baseNameLower = baseName.toLowerCase();
const extension = path.extname(file.name);
const extensionLower = extension.toLowerCase();
if (!file.isFile()) {
return acc;
}
if (!VALID_EXTENSIONS.includes(extensionLower)) {
logWarning(`Config file not loaded, extension must be one of ${VALID_EXTENSIONS.join(',')}): ${file.name}`);
return acc;
}
if (RESTRICTED_FILENAMES.includes(baseNameLower)) {
logWarning(`Config file not loaded, restricted filename: ${file.name}`);
// suggest the filename they probably meant
if (baseNameLower in MISTAKEN_FILENAMES) {
console.log(`Did you mean ${MISTAKEN_FILENAMES[baseNameLower]}]} ?`);
}
return acc;
}
// restricted names and Strapi configs are also restricted from being prefixes
const restrictedPrefix = [
...RESTRICTED_FILENAMES,
...STRAPI_CONFIG_FILENAMES
].find((restrictedName)=>restrictedName.startsWith(baseNameLower) && restrictedName !== baseNameLower);
if (restrictedPrefix) {
logWarning(`Config file not loaded, filename cannot start with ${restrictedPrefix}: ${file.name}`);
}
/**
* Note: If user config files contain non-alpha-numeric characters, we won't be able to auto-load env
* into them.
*
* For the initial feature, we will only load our internal configs, but later when we provide a method
* to define the shape of custom configs, we will need to warn that those filenames can't be loaded
* for technical limitations on env variable names
* */ // if (!/^[A-Za-z0-9]+$/.test(baseName)) {
// logWarning("Using a non-alphanumeric config file name prevents Strapi from auto-loading it from environment variables.")
// }
// filter filenames without case-insensitive uniqueness
if (seenFilenames.has(baseNameLower)) {
logWarning(`Config file not loaded, case-insensitive name matches other config file: ${file.name}`);
return acc;
}
seenFilenames.add(baseNameLower);
// If file passes all filters, add it to the accumulator
acc.push(file);
return acc;
}, []);
return configFiles.reduce((acc, file)=>{
const key = path.basename(file.name, path.extname(file.name));
acc[key] = loadConfigFile.loadConfigFile(path.resolve(dir, file.name));
return acc;
}, {});
});
module.exports = loadConfigDir;
//# sourceMappingURL=config-loader.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,117 @@
import path from 'path';
import fs from 'fs';
import { loadConfigFile } from '../utils/load-config-file.mjs';
const VALID_EXTENSIONS = [
'.js',
'.json'
];
// These filenames are restricted, but will also emit a warning that the filename is probably a mistake
const MISTAKEN_FILENAMES = {
middleware: 'middlewares',
plugin: 'plugins'
};
// the following are restricted to prevent conflicts with existing STRAPI_* env vars or root level config options
// must all be lowercase to match validator
const RESTRICTED_FILENAMES = [
// existing env vars
'uuid',
'hosting',
'license',
'enforce',
'disable',
'enable',
'telemetry',
// reserved for future internal use
'strapi',
'internal',
// root level config options
// TODO: it would be better to move these out of the root config and allow them to be loaded
'launchedAt',
'serveAdminPanel',
'autoReload',
'environment',
'packageJsonStrapi',
'info',
'autoReload',
'dirs',
// probably mistaken/typo filenames
...Object.keys(MISTAKEN_FILENAMES)
];
// Existing Strapi configuration files
const STRAPI_CONFIG_FILENAMES = [
'admin',
'server',
'api',
'database',
'middlewares',
'plugins',
'features'
];
// Note: we don't have access to strapi logger at this point so we can't use it
const logWarning = (message)=>{
console.warn(message);
};
var loadConfigDir = ((dir)=>{
if (!fs.existsSync(dir)) return {};
const allFiles = fs.readdirSync(dir, {
withFileTypes: true
});
const seenFilenames = new Set();
const configFiles = allFiles.reduce((acc, file)=>{
const baseName = path.basename(file.name, path.extname(file.name));
const baseNameLower = baseName.toLowerCase();
const extension = path.extname(file.name);
const extensionLower = extension.toLowerCase();
if (!file.isFile()) {
return acc;
}
if (!VALID_EXTENSIONS.includes(extensionLower)) {
logWarning(`Config file not loaded, extension must be one of ${VALID_EXTENSIONS.join(',')}): ${file.name}`);
return acc;
}
if (RESTRICTED_FILENAMES.includes(baseNameLower)) {
logWarning(`Config file not loaded, restricted filename: ${file.name}`);
// suggest the filename they probably meant
if (baseNameLower in MISTAKEN_FILENAMES) {
console.log(`Did you mean ${MISTAKEN_FILENAMES[baseNameLower]}]} ?`);
}
return acc;
}
// restricted names and Strapi configs are also restricted from being prefixes
const restrictedPrefix = [
...RESTRICTED_FILENAMES,
...STRAPI_CONFIG_FILENAMES
].find((restrictedName)=>restrictedName.startsWith(baseNameLower) && restrictedName !== baseNameLower);
if (restrictedPrefix) {
logWarning(`Config file not loaded, filename cannot start with ${restrictedPrefix}: ${file.name}`);
}
/**
* Note: If user config files contain non-alpha-numeric characters, we won't be able to auto-load env
* into them.
*
* For the initial feature, we will only load our internal configs, but later when we provide a method
* to define the shape of custom configs, we will need to warn that those filenames can't be loaded
* for technical limitations on env variable names
* */ // if (!/^[A-Za-z0-9]+$/.test(baseName)) {
// logWarning("Using a non-alphanumeric config file name prevents Strapi from auto-loading it from environment variables.")
// }
// filter filenames without case-insensitive uniqueness
if (seenFilenames.has(baseNameLower)) {
logWarning(`Config file not loaded, case-insensitive name matches other config file: ${file.name}`);
return acc;
}
seenFilenames.add(baseNameLower);
// If file passes all filters, add it to the accumulator
acc.push(file);
return acc;
}, []);
return configFiles.reduce((acc, file)=>{
const key = path.basename(file.name, path.extname(file.name));
acc[key] = loadConfigFile(path.resolve(dir, file.name));
return acc;
}, {});
});
export { loadConfigDir as default };
//# sourceMappingURL=config-loader.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,10 @@
import type { Core } from '@strapi/types';
import type { StrapiOptions } from '../Strapi';
export type Options = {
app: string;
dist: string;
};
export declare const getDirs: ({ appDir, distDir }: StrapiOptions, config: {
server: Partial<Core.Config.Server>;
}) => Core.StrapiDirectories;
//# sourceMappingURL=get-dirs.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"get-dirs.d.ts","sourceRoot":"","sources":["../../src/configuration/get-dirs.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAE/C,MAAM,MAAM,OAAO,GAAG;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,eAAO,MAAM,OAAO,wBACG,aAAa,UAC1B;IAAE,MAAM,EAAE,QAAQ,KAAK,MAAM,CAAC,MAAM,CAAC,CAAA;CAAE,KAC9C,KAAK,iBAwBN,CAAC"}

View File

@@ -0,0 +1,33 @@
'use strict';
var path = require('path');
var fp = require('lodash/fp');
const getDirs = ({ appDir, distDir }, config)=>({
dist: {
root: distDir,
src: path.join(distDir, 'src'),
api: path.join(distDir, 'src', 'api'),
components: path.join(distDir, 'src', 'components'),
extensions: path.join(distDir, 'src', 'extensions'),
policies: path.join(distDir, 'src', 'policies'),
middlewares: path.join(distDir, 'src', 'middlewares'),
config: path.join(distDir, 'config')
},
app: {
root: appDir,
src: path.join(appDir, 'src'),
api: path.join(appDir, 'src', 'api'),
components: path.join(appDir, 'src', 'components'),
extensions: path.join(appDir, 'src', 'extensions'),
policies: path.join(appDir, 'src', 'policies'),
middlewares: path.join(appDir, 'src', 'middlewares'),
config: path.join(appDir, 'config')
},
static: {
public: path.resolve(appDir, fp.get('server.dirs.public', config))
}
});
exports.getDirs = getDirs;
//# sourceMappingURL=get-dirs.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"get-dirs.js","sources":["../../src/configuration/get-dirs.ts"],"sourcesContent":["import { join, resolve } from 'path';\nimport { get } from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\nimport type { StrapiOptions } from '../Strapi';\n\nexport type Options = {\n app: string;\n dist: string;\n};\n\nexport const getDirs = (\n { appDir, distDir }: StrapiOptions,\n config: { server: Partial<Core.Config.Server> }\n): Core.StrapiDirectories => ({\n dist: {\n root: distDir,\n src: join(distDir, 'src'),\n api: join(distDir, 'src', 'api'),\n components: join(distDir, 'src', 'components'),\n extensions: join(distDir, 'src', 'extensions'),\n policies: join(distDir, 'src', 'policies'),\n middlewares: join(distDir, 'src', 'middlewares'),\n config: join(distDir, 'config'),\n },\n app: {\n root: appDir,\n src: join(appDir, 'src'),\n api: join(appDir, 'src', 'api'),\n components: join(appDir, 'src', 'components'),\n extensions: join(appDir, 'src', 'extensions'),\n policies: join(appDir, 'src', 'policies'),\n middlewares: join(appDir, 'src', 'middlewares'),\n config: join(appDir, 'config'),\n },\n static: {\n public: resolve(appDir, get('server.dirs.public', config)),\n },\n});\n"],"names":["getDirs","appDir","distDir","config","dist","root","src","join","api","components","extensions","policies","middlewares","app","static","public","resolve","get"],"mappings":";;;;;AAWO,MAAMA,OAAU,GAAA,CACrB,EAAEC,MAAM,EAAEC,OAAO,EAAiB,EAClCC,MAAAA,IAC4B;QAC5BC,IAAM,EAAA;YACJC,IAAMH,EAAAA,OAAAA;AACNI,YAAAA,GAAAA,EAAKC,UAAKL,OAAS,EAAA,KAAA,CAAA;YACnBM,GAAKD,EAAAA,SAAAA,CAAKL,SAAS,KAAO,EAAA,KAAA,CAAA;YAC1BO,UAAYF,EAAAA,SAAAA,CAAKL,SAAS,KAAO,EAAA,YAAA,CAAA;YACjCQ,UAAYH,EAAAA,SAAAA,CAAKL,SAAS,KAAO,EAAA,YAAA,CAAA;YACjCS,QAAUJ,EAAAA,SAAAA,CAAKL,SAAS,KAAO,EAAA,UAAA,CAAA;YAC/BU,WAAaL,EAAAA,SAAAA,CAAKL,SAAS,KAAO,EAAA,aAAA,CAAA;AAClCC,YAAAA,MAAAA,EAAQI,UAAKL,OAAS,EAAA,QAAA;AACxB,SAAA;QACAW,GAAK,EAAA;YACHR,IAAMJ,EAAAA,MAAAA;AACNK,YAAAA,GAAAA,EAAKC,UAAKN,MAAQ,EAAA,KAAA,CAAA;YAClBO,GAAKD,EAAAA,SAAAA,CAAKN,QAAQ,KAAO,EAAA,KAAA,CAAA;YACzBQ,UAAYF,EAAAA,SAAAA,CAAKN,QAAQ,KAAO,EAAA,YAAA,CAAA;YAChCS,UAAYH,EAAAA,SAAAA,CAAKN,QAAQ,KAAO,EAAA,YAAA,CAAA;YAChCU,QAAUJ,EAAAA,SAAAA,CAAKN,QAAQ,KAAO,EAAA,UAAA,CAAA;YAC9BW,WAAaL,EAAAA,SAAAA,CAAKN,QAAQ,KAAO,EAAA,aAAA,CAAA;AACjCE,YAAAA,MAAAA,EAAQI,UAAKN,MAAQ,EAAA,QAAA;AACvB,SAAA;QACAa,MAAQ,EAAA;YACNC,MAAQC,EAAAA,YAAAA,CAAQf,MAAQgB,EAAAA,MAAAA,CAAI,oBAAsBd,EAAAA,MAAAA,CAAAA;AACpD;AACF,KAAA;;;;"}

View File

@@ -0,0 +1,31 @@
import { join, resolve } from 'path';
import { get } from 'lodash/fp';
const getDirs = ({ appDir, distDir }, config)=>({
dist: {
root: distDir,
src: join(distDir, 'src'),
api: join(distDir, 'src', 'api'),
components: join(distDir, 'src', 'components'),
extensions: join(distDir, 'src', 'extensions'),
policies: join(distDir, 'src', 'policies'),
middlewares: join(distDir, 'src', 'middlewares'),
config: join(distDir, 'config')
},
app: {
root: appDir,
src: join(appDir, 'src'),
api: join(appDir, 'src', 'api'),
components: join(appDir, 'src', 'components'),
extensions: join(appDir, 'src', 'extensions'),
policies: join(appDir, 'src', 'policies'),
middlewares: join(appDir, 'src', 'middlewares'),
config: join(appDir, 'config')
},
static: {
public: resolve(appDir, get('server.dirs.public', config))
}
});
export { getDirs };
//# sourceMappingURL=get-dirs.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"get-dirs.mjs","sources":["../../src/configuration/get-dirs.ts"],"sourcesContent":["import { join, resolve } from 'path';\nimport { get } from 'lodash/fp';\n\nimport type { Core } from '@strapi/types';\nimport type { StrapiOptions } from '../Strapi';\n\nexport type Options = {\n app: string;\n dist: string;\n};\n\nexport const getDirs = (\n { appDir, distDir }: StrapiOptions,\n config: { server: Partial<Core.Config.Server> }\n): Core.StrapiDirectories => ({\n dist: {\n root: distDir,\n src: join(distDir, 'src'),\n api: join(distDir, 'src', 'api'),\n components: join(distDir, 'src', 'components'),\n extensions: join(distDir, 'src', 'extensions'),\n policies: join(distDir, 'src', 'policies'),\n middlewares: join(distDir, 'src', 'middlewares'),\n config: join(distDir, 'config'),\n },\n app: {\n root: appDir,\n src: join(appDir, 'src'),\n api: join(appDir, 'src', 'api'),\n components: join(appDir, 'src', 'components'),\n extensions: join(appDir, 'src', 'extensions'),\n policies: join(appDir, 'src', 'policies'),\n middlewares: join(appDir, 'src', 'middlewares'),\n config: join(appDir, 'config'),\n },\n static: {\n public: resolve(appDir, get('server.dirs.public', config)),\n },\n});\n"],"names":["getDirs","appDir","distDir","config","dist","root","src","join","api","components","extensions","policies","middlewares","app","static","public","resolve","get"],"mappings":";;;AAWO,MAAMA,OAAU,GAAA,CACrB,EAAEC,MAAM,EAAEC,OAAO,EAAiB,EAClCC,MAAAA,IAC4B;QAC5BC,IAAM,EAAA;YACJC,IAAMH,EAAAA,OAAAA;AACNI,YAAAA,GAAAA,EAAKC,KAAKL,OAAS,EAAA,KAAA,CAAA;YACnBM,GAAKD,EAAAA,IAAAA,CAAKL,SAAS,KAAO,EAAA,KAAA,CAAA;YAC1BO,UAAYF,EAAAA,IAAAA,CAAKL,SAAS,KAAO,EAAA,YAAA,CAAA;YACjCQ,UAAYH,EAAAA,IAAAA,CAAKL,SAAS,KAAO,EAAA,YAAA,CAAA;YACjCS,QAAUJ,EAAAA,IAAAA,CAAKL,SAAS,KAAO,EAAA,UAAA,CAAA;YAC/BU,WAAaL,EAAAA,IAAAA,CAAKL,SAAS,KAAO,EAAA,aAAA,CAAA;AAClCC,YAAAA,MAAAA,EAAQI,KAAKL,OAAS,EAAA,QAAA;AACxB,SAAA;QACAW,GAAK,EAAA;YACHR,IAAMJ,EAAAA,MAAAA;AACNK,YAAAA,GAAAA,EAAKC,KAAKN,MAAQ,EAAA,KAAA,CAAA;YAClBO,GAAKD,EAAAA,IAAAA,CAAKN,QAAQ,KAAO,EAAA,KAAA,CAAA;YACzBQ,UAAYF,EAAAA,IAAAA,CAAKN,QAAQ,KAAO,EAAA,YAAA,CAAA;YAChCS,UAAYH,EAAAA,IAAAA,CAAKN,QAAQ,KAAO,EAAA,YAAA,CAAA;YAChCU,QAAUJ,EAAAA,IAAAA,CAAKN,QAAQ,KAAO,EAAA,UAAA,CAAA;YAC9BW,WAAaL,EAAAA,IAAAA,CAAKN,QAAQ,KAAO,EAAA,aAAA,CAAA;AACjCE,YAAAA,MAAAA,EAAQI,KAAKN,MAAQ,EAAA,QAAA;AACvB,SAAA;QACAa,MAAQ,EAAA;YACNC,MAAQC,EAAAA,OAAAA,CAAQf,MAAQgB,EAAAA,GAAAA,CAAI,oBAAsBd,EAAAA,MAAAA,CAAAA;AACpD;AACF,KAAA;;;;"}

View File

@@ -0,0 +1,49 @@
import _ from 'lodash';
import type { StrapiOptions } from '../Strapi';
export declare const loadConfiguration: (opts: StrapiOptions) => {
launchedAt: number;
autoReload: boolean;
environment: string | undefined;
uuid: any;
installId: any;
packageJsonStrapi: Pick<any, string | number | symbol>;
info: any;
admin: {
serveAdminPanel: boolean;
};
} & {
server: {
host: string;
port: number;
proxy: false;
cron: {
enabled: false;
};
admin: {
autoOpen: false;
};
dirs: {
public: string;
};
transfer: {
remote: {
enabled: true;
};
};
logger: {
updates: {
enabled: true;
};
startup: {
enabled: true;
};
};
};
admin: {};
api: {
rest: {
prefix: string;
};
};
} & _.Omit<Record<string, unknown>, "plugins"> & Record<string, unknown>;
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/configuration/index.ts"],"names":[],"mappings":"AAGA,OAAO,CAAC,MAAM,QAAQ,CAAC;AAUvB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAqC/C,eAAO,MAAM,iBAAiB,SAAU,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wEAkDpD,CAAC"}

View File

@@ -0,0 +1,92 @@
'use strict';
var os = require('os');
var path = require('path');
var _ = require('lodash');
var fp = require('lodash/fp');
var dotenv = require('dotenv');
var strapiUtils = require('@strapi/utils');
var urls = require('./urls.js');
var configLoader = require('./config-loader.js');
var getDirs = require('./get-dirs.js');
var _package = require('../package.json.js');
dotenv.config({
path: process.env.ENV_PATH
});
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const defaultConfig = {
server: {
host: process.env.HOST || os.hostname() || 'localhost',
port: Number(process.env.PORT) || 1337,
proxy: false,
cron: {
enabled: false
},
admin: {
autoOpen: false
},
dirs: {
public: './public'
},
transfer: {
remote: {
enabled: true
}
},
logger: {
updates: {
enabled: true
},
startup: {
enabled: true
}
}
},
admin: {},
api: {
rest: {
prefix: '/api'
}
}
};
const loadConfiguration = (opts)=>{
const { appDir, distDir, autoReload = false, serveAdminPanel = true } = opts;
const pkgJSON = require(path.resolve(appDir, 'package.json'));
const configDir = path.resolve(distDir || process.cwd(), 'config');
const rootConfig = {
launchedAt: Date.now(),
autoReload,
environment: process.env.NODE_ENV,
uuid: _.get(pkgJSON, 'strapi.uuid'),
installId: _.get(pkgJSON, 'strapi.installId'),
packageJsonStrapi: _.omit(_.get(pkgJSON, 'strapi', {}), 'uuid'),
info: {
...pkgJSON,
strapi: _package.version
},
admin: {
serveAdminPanel
}
};
// See packages/core/core/src/domain/module/index.ts for plugin config loading
const baseConfig = fp.omit('plugins', configLoader(configDir)); // plugin config will be loaded later
const envDir = path.resolve(configDir, 'env', process.env.NODE_ENV);
const envConfig = configLoader(envDir);
const config = _.merge(rootConfig, defaultConfig, baseConfig, envConfig);
const { serverUrl, adminUrl } = urls.getConfigUrls(config);
const serverAbsoluteUrl = urls.getAbsoluteServerUrl(config);
const adminAbsoluteUrl = urls.getAbsoluteAdminUrl(config);
const sameOrigin = new URL(adminAbsoluteUrl).origin === new URL(serverAbsoluteUrl).origin;
const adminPath = sameOrigin ? adminUrl.replace(strapiUtils.strings.getCommonPath(serverUrl, adminUrl), '') : new URL(adminUrl).pathname;
_.set(config, 'server.url', serverUrl);
_.set(config, 'server.absoluteUrl', serverAbsoluteUrl);
_.set(config, 'admin.url', adminUrl);
_.set(config, 'admin.path', adminPath);
_.set(config, 'admin.absoluteUrl', adminAbsoluteUrl);
_.set(config, 'dirs', getDirs.getDirs(opts, config));
return config;
};
exports.loadConfiguration = loadConfiguration;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,90 @@
import os from 'os';
import path from 'path';
import _ from 'lodash';
import { omit } from 'lodash/fp';
import dotenv from 'dotenv';
import { strings } from '@strapi/utils';
import { getConfigUrls, getAbsoluteServerUrl, getAbsoluteAdminUrl } from './urls.mjs';
import loadConfigDir from './config-loader.mjs';
import { getDirs } from './get-dirs.mjs';
import { version } from '../package.json.mjs';
dotenv.config({
path: process.env.ENV_PATH
});
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
const defaultConfig = {
server: {
host: process.env.HOST || os.hostname() || 'localhost',
port: Number(process.env.PORT) || 1337,
proxy: false,
cron: {
enabled: false
},
admin: {
autoOpen: false
},
dirs: {
public: './public'
},
transfer: {
remote: {
enabled: true
}
},
logger: {
updates: {
enabled: true
},
startup: {
enabled: true
}
}
},
admin: {},
api: {
rest: {
prefix: '/api'
}
}
};
const loadConfiguration = (opts)=>{
const { appDir, distDir, autoReload = false, serveAdminPanel = true } = opts;
const pkgJSON = require(path.resolve(appDir, 'package.json'));
const configDir = path.resolve(distDir || process.cwd(), 'config');
const rootConfig = {
launchedAt: Date.now(),
autoReload,
environment: process.env.NODE_ENV,
uuid: _.get(pkgJSON, 'strapi.uuid'),
installId: _.get(pkgJSON, 'strapi.installId'),
packageJsonStrapi: _.omit(_.get(pkgJSON, 'strapi', {}), 'uuid'),
info: {
...pkgJSON,
strapi: version
},
admin: {
serveAdminPanel
}
};
// See packages/core/core/src/domain/module/index.ts for plugin config loading
const baseConfig = omit('plugins', loadConfigDir(configDir)); // plugin config will be loaded later
const envDir = path.resolve(configDir, 'env', process.env.NODE_ENV);
const envConfig = loadConfigDir(envDir);
const config = _.merge(rootConfig, defaultConfig, baseConfig, envConfig);
const { serverUrl, adminUrl } = getConfigUrls(config);
const serverAbsoluteUrl = getAbsoluteServerUrl(config);
const adminAbsoluteUrl = getAbsoluteAdminUrl(config);
const sameOrigin = new URL(adminAbsoluteUrl).origin === new URL(serverAbsoluteUrl).origin;
const adminPath = sameOrigin ? adminUrl.replace(strings.getCommonPath(serverUrl, adminUrl), '') : new URL(adminUrl).pathname;
_.set(config, 'server.url', serverUrl);
_.set(config, 'server.absoluteUrl', serverAbsoluteUrl);
_.set(config, 'admin.url', adminUrl);
_.set(config, 'admin.path', adminPath);
_.set(config, 'admin.absoluteUrl', adminAbsoluteUrl);
_.set(config, 'dirs', getDirs(opts, config));
return config;
};
export { loadConfiguration };
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
export declare const getConfigUrls: (config: Record<string, unknown>, forAdminBuild?: boolean) => {
serverUrl: string;
adminUrl: string;
adminPath: string;
};
export declare const getAbsoluteAdminUrl: (config: Record<string, unknown>, forAdminBuild?: boolean) => string;
export declare const getAbsoluteServerUrl: (config: Record<string, unknown>, forAdminBuild?: boolean) => string;
//# sourceMappingURL=urls.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"urls.d.ts","sourceRoot":"","sources":["../../src/configuration/urls.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,aAAa,WAAY,OAAO,MAAM,EAAE,OAAO,CAAC;;;;CA0D5D,CAAC;AA6BF,eAAO,MAAM,mBAAmB,WAzBrB,OAAO,MAAM,EAAE,OAAO,CAAC,oCAyBwB,CAAC;AAC3D,eAAO,MAAM,oBAAoB,WA1BtB,OAAO,MAAM,EAAE,OAAO,CAAC,oCA0B0B,CAAC"}

View File

@@ -0,0 +1,81 @@
'use strict';
var _ = require('lodash');
var strapiUtils = require('@strapi/utils');
var node_net = require('node:net');
const getConfigUrls = (config, forAdminBuild = false)=>{
const serverConfig = config.server;
const adminConfig = config.admin;
// Defines serverUrl value
let serverUrl = _.get(serverConfig, 'url', '');
serverUrl = _.trim(serverUrl, '/ ');
if (typeof serverUrl !== 'string') {
throw new Error('Invalid server url config. Make sure the url is a string.');
}
if (serverUrl.startsWith('http')) {
try {
serverUrl = _.trim(new URL(serverConfig.url).toString(), '/');
} catch (e) {
throw new Error('Invalid server url config. Make sure the url defined in server.js is valid.');
}
} else if (serverUrl !== '') {
serverUrl = `/${serverUrl}`;
}
// Defines adminUrl value
let adminUrl = _.get(adminConfig, 'url', '/admin');
adminUrl = _.trim(adminUrl, '/ ');
if (typeof adminUrl !== 'string') {
throw new Error('Invalid admin url config. Make sure the url is a non-empty string.');
}
if (adminUrl.startsWith('http')) {
try {
adminUrl = _.trim(new URL(adminUrl).toString(), '/');
} catch (e) {
throw new Error('Invalid admin url config. Make sure the url defined in server.js is valid.');
}
} else {
adminUrl = `${serverUrl}/${adminUrl}`;
}
// Defines adminPath value
let adminPath = adminUrl;
if (serverUrl.startsWith('http') && adminUrl.startsWith('http') && new URL(adminUrl).origin === new URL(serverUrl).origin && !forAdminBuild) {
adminPath = adminUrl.replace(strapiUtils.strings.getCommonPath(serverUrl, adminUrl), '');
adminPath = `/${_.trim(adminPath, '/')}`;
} else if (adminUrl.startsWith('http')) {
adminPath = new URL(adminUrl).pathname;
}
return {
serverUrl,
adminUrl,
adminPath
};
};
const getAbsoluteUrl = (adminOrServer)=>(config, forAdminBuild = false)=>{
const { serverUrl, adminUrl } = getConfigUrls(config, forAdminBuild);
const url = adminOrServer === 'server' ? serverUrl : adminUrl;
if (url.startsWith('http')) {
return url;
}
const serverConfig = config.server;
const isLocalhost = config.environment === 'development' && [
'127.0.0.1',
'0.0.0.0',
'::1',
'::'
].includes(serverConfig.host);
if (isLocalhost) {
return `http://localhost:${serverConfig.port}${url}`;
}
if (node_net.isIP(serverConfig.host) === 6) {
return `http://[${serverConfig.host}]:${serverConfig.port}${url}`;
}
return `http://${serverConfig.host}:${serverConfig.port}${url}`;
};
const getAbsoluteAdminUrl = getAbsoluteUrl('admin');
const getAbsoluteServerUrl = getAbsoluteUrl('server');
exports.getAbsoluteAdminUrl = getAbsoluteAdminUrl;
exports.getAbsoluteServerUrl = getAbsoluteServerUrl;
exports.getConfigUrls = getConfigUrls;
//# sourceMappingURL=urls.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,77 @@
import _ from 'lodash';
import { strings } from '@strapi/utils';
import { isIP } from 'node:net';
const getConfigUrls = (config, forAdminBuild = false)=>{
const serverConfig = config.server;
const adminConfig = config.admin;
// Defines serverUrl value
let serverUrl = _.get(serverConfig, 'url', '');
serverUrl = _.trim(serverUrl, '/ ');
if (typeof serverUrl !== 'string') {
throw new Error('Invalid server url config. Make sure the url is a string.');
}
if (serverUrl.startsWith('http')) {
try {
serverUrl = _.trim(new URL(serverConfig.url).toString(), '/');
} catch (e) {
throw new Error('Invalid server url config. Make sure the url defined in server.js is valid.');
}
} else if (serverUrl !== '') {
serverUrl = `/${serverUrl}`;
}
// Defines adminUrl value
let adminUrl = _.get(adminConfig, 'url', '/admin');
adminUrl = _.trim(adminUrl, '/ ');
if (typeof adminUrl !== 'string') {
throw new Error('Invalid admin url config. Make sure the url is a non-empty string.');
}
if (adminUrl.startsWith('http')) {
try {
adminUrl = _.trim(new URL(adminUrl).toString(), '/');
} catch (e) {
throw new Error('Invalid admin url config. Make sure the url defined in server.js is valid.');
}
} else {
adminUrl = `${serverUrl}/${adminUrl}`;
}
// Defines adminPath value
let adminPath = adminUrl;
if (serverUrl.startsWith('http') && adminUrl.startsWith('http') && new URL(adminUrl).origin === new URL(serverUrl).origin && !forAdminBuild) {
adminPath = adminUrl.replace(strings.getCommonPath(serverUrl, adminUrl), '');
adminPath = `/${_.trim(adminPath, '/')}`;
} else if (adminUrl.startsWith('http')) {
adminPath = new URL(adminUrl).pathname;
}
return {
serverUrl,
adminUrl,
adminPath
};
};
const getAbsoluteUrl = (adminOrServer)=>(config, forAdminBuild = false)=>{
const { serverUrl, adminUrl } = getConfigUrls(config, forAdminBuild);
const url = adminOrServer === 'server' ? serverUrl : adminUrl;
if (url.startsWith('http')) {
return url;
}
const serverConfig = config.server;
const isLocalhost = config.environment === 'development' && [
'127.0.0.1',
'0.0.0.0',
'::1',
'::'
].includes(serverConfig.host);
if (isLocalhost) {
return `http://localhost:${serverConfig.port}${url}`;
}
if (isIP(serverConfig.host) === 6) {
return `http://[${serverConfig.host}]:${serverConfig.port}${url}`;
}
return `http://${serverConfig.host}:${serverConfig.port}${url}`;
};
const getAbsoluteAdminUrl = getAbsoluteUrl('admin');
const getAbsoluteServerUrl = getAbsoluteUrl('server');
export { getAbsoluteAdminUrl, getAbsoluteServerUrl, getConfigUrls };
//# sourceMappingURL=urls.mjs.map

File diff suppressed because one or more lines are too long

8
server/node_modules/@strapi/core/dist/container.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import type { Core } from '@strapi/types';
export declare class Container implements Core.Container {
private registerMap;
private serviceMap;
add(name: string, resolver: unknown): this;
get(name: string, args?: unknown): any;
}
//# sourceMappingURL=container.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"container.d.ts","sourceRoot":"","sources":["../src/container.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAE1C,qBAAa,SAAU,YAAW,IAAI,CAAC,SAAS;IAC9C,OAAO,CAAC,WAAW,CAA8B;IAEjD,OAAO,CAAC,UAAU,CAAa;IAE/B,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO;IASnC,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO;CAoBjC"}

34
server/node_modules/@strapi/core/dist/container.js generated vendored Normal file
View File

@@ -0,0 +1,34 @@
'use strict';
class Container {
add(name, resolver) {
if (this.registerMap.has(name)) {
throw new Error(`Cannot register already registered service ${name}`);
}
this.registerMap.set(name, resolver);
return this;
}
get(name, args) {
// TODO: handle singleton vs instantiation everytime
if (this.serviceMap.has(name)) {
return this.serviceMap.get(name);
}
if (this.registerMap.has(name)) {
const resolver = this.registerMap.get(name);
if (typeof resolver === 'function') {
this.serviceMap.set(name, resolver(this, args));
} else {
this.serviceMap.set(name, resolver);
}
return this.serviceMap.get(name);
}
throw new Error(`Could not resolve service ${name}`);
}
constructor(){
this.registerMap = new Map();
this.serviceMap = new Map();
}
}
exports.Container = Container;
//# sourceMappingURL=container.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"container.js","sources":["../src/container.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport class Container implements Core.Container {\n private registerMap = new Map<string, unknown>();\n\n private serviceMap = new Map();\n\n add(name: string, resolver: unknown) {\n if (this.registerMap.has(name)) {\n throw new Error(`Cannot register already registered service ${name}`);\n }\n\n this.registerMap.set(name, resolver);\n return this;\n }\n\n get(name: string, args?: unknown) {\n // TODO: handle singleton vs instantiation everytime\n if (this.serviceMap.has(name)) {\n return this.serviceMap.get(name);\n }\n\n if (this.registerMap.has(name)) {\n const resolver = this.registerMap.get(name);\n\n if (typeof resolver === 'function') {\n this.serviceMap.set(name, resolver(this, args));\n } else {\n this.serviceMap.set(name, resolver);\n }\n\n return this.serviceMap.get(name);\n }\n\n throw new Error(`Could not resolve service ${name}`);\n }\n}\n"],"names":["Container","add","name","resolver","registerMap","has","Error","set","get","args","serviceMap","Map"],"mappings":";;AAEO,MAAMA,SAAAA,CAAAA;IAKXC,GAAIC,CAAAA,IAAY,EAAEC,QAAiB,EAAE;AACnC,QAAA,IAAI,IAAI,CAACC,WAAW,CAACC,GAAG,CAACH,IAAO,CAAA,EAAA;AAC9B,YAAA,MAAM,IAAII,KAAM,CAAA,CAAC,2CAA2C,EAAEJ,KAAK,CAAC,CAAA;AACtE;AAEA,QAAA,IAAI,CAACE,WAAW,CAACG,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAAA;AAC3B,QAAA,OAAO,IAAI;AACb;IAEAK,GAAIN,CAAAA,IAAY,EAAEO,IAAc,EAAE;;AAEhC,QAAA,IAAI,IAAI,CAACC,UAAU,CAACL,GAAG,CAACH,IAAO,CAAA,EAAA;AAC7B,YAAA,OAAO,IAAI,CAACQ,UAAU,CAACF,GAAG,CAACN,IAAAA,CAAAA;AAC7B;AAEA,QAAA,IAAI,IAAI,CAACE,WAAW,CAACC,GAAG,CAACH,IAAO,CAAA,EAAA;AAC9B,YAAA,MAAMC,WAAW,IAAI,CAACC,WAAW,CAACI,GAAG,CAACN,IAAAA,CAAAA;YAEtC,IAAI,OAAOC,aAAa,UAAY,EAAA;gBAClC,IAAI,CAACO,UAAU,CAACH,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAS,IAAI,EAAEM,IAAAA,CAAAA,CAAAA;aACpC,MAAA;AACL,gBAAA,IAAI,CAACC,UAAU,CAACH,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAAA;AAC5B;AAEA,YAAA,OAAO,IAAI,CAACO,UAAU,CAACF,GAAG,CAACN,IAAAA,CAAAA;AAC7B;AAEA,QAAA,MAAM,IAAII,KAAM,CAAA,CAAC,0BAA0B,EAAEJ,KAAK,CAAC,CAAA;AACrD;;AAhCQE,QAAAA,IAAAA,CAAAA,WAAAA,GAAc,IAAIO,GAAAA,EAAAA;AAElBD,QAAAA,IAAAA,CAAAA,UAAAA,GAAa,IAAIC,GAAAA,EAAAA;;AA+B3B;;;;"}

32
server/node_modules/@strapi/core/dist/container.mjs generated vendored Normal file
View File

@@ -0,0 +1,32 @@
class Container {
add(name, resolver) {
if (this.registerMap.has(name)) {
throw new Error(`Cannot register already registered service ${name}`);
}
this.registerMap.set(name, resolver);
return this;
}
get(name, args) {
// TODO: handle singleton vs instantiation everytime
if (this.serviceMap.has(name)) {
return this.serviceMap.get(name);
}
if (this.registerMap.has(name)) {
const resolver = this.registerMap.get(name);
if (typeof resolver === 'function') {
this.serviceMap.set(name, resolver(this, args));
} else {
this.serviceMap.set(name, resolver);
}
return this.serviceMap.get(name);
}
throw new Error(`Could not resolve service ${name}`);
}
constructor(){
this.registerMap = new Map();
this.serviceMap = new Map();
}
}
export { Container };
//# sourceMappingURL=container.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"container.mjs","sources":["../src/container.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\n\nexport class Container implements Core.Container {\n private registerMap = new Map<string, unknown>();\n\n private serviceMap = new Map();\n\n add(name: string, resolver: unknown) {\n if (this.registerMap.has(name)) {\n throw new Error(`Cannot register already registered service ${name}`);\n }\n\n this.registerMap.set(name, resolver);\n return this;\n }\n\n get(name: string, args?: unknown) {\n // TODO: handle singleton vs instantiation everytime\n if (this.serviceMap.has(name)) {\n return this.serviceMap.get(name);\n }\n\n if (this.registerMap.has(name)) {\n const resolver = this.registerMap.get(name);\n\n if (typeof resolver === 'function') {\n this.serviceMap.set(name, resolver(this, args));\n } else {\n this.serviceMap.set(name, resolver);\n }\n\n return this.serviceMap.get(name);\n }\n\n throw new Error(`Could not resolve service ${name}`);\n }\n}\n"],"names":["Container","add","name","resolver","registerMap","has","Error","set","get","args","serviceMap","Map"],"mappings":"AAEO,MAAMA,SAAAA,CAAAA;IAKXC,GAAIC,CAAAA,IAAY,EAAEC,QAAiB,EAAE;AACnC,QAAA,IAAI,IAAI,CAACC,WAAW,CAACC,GAAG,CAACH,IAAO,CAAA,EAAA;AAC9B,YAAA,MAAM,IAAII,KAAM,CAAA,CAAC,2CAA2C,EAAEJ,KAAK,CAAC,CAAA;AACtE;AAEA,QAAA,IAAI,CAACE,WAAW,CAACG,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAAA;AAC3B,QAAA,OAAO,IAAI;AACb;IAEAK,GAAIN,CAAAA,IAAY,EAAEO,IAAc,EAAE;;AAEhC,QAAA,IAAI,IAAI,CAACC,UAAU,CAACL,GAAG,CAACH,IAAO,CAAA,EAAA;AAC7B,YAAA,OAAO,IAAI,CAACQ,UAAU,CAACF,GAAG,CAACN,IAAAA,CAAAA;AAC7B;AAEA,QAAA,IAAI,IAAI,CAACE,WAAW,CAACC,GAAG,CAACH,IAAO,CAAA,EAAA;AAC9B,YAAA,MAAMC,WAAW,IAAI,CAACC,WAAW,CAACI,GAAG,CAACN,IAAAA,CAAAA;YAEtC,IAAI,OAAOC,aAAa,UAAY,EAAA;gBAClC,IAAI,CAACO,UAAU,CAACH,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAS,IAAI,EAAEM,IAAAA,CAAAA,CAAAA;aACpC,MAAA;AACL,gBAAA,IAAI,CAACC,UAAU,CAACH,GAAG,CAACL,IAAMC,EAAAA,QAAAA,CAAAA;AAC5B;AAEA,YAAA,OAAO,IAAI,CAACO,UAAU,CAACF,GAAG,CAACN,IAAAA,CAAAA;AAC7B;AAEA,QAAA,MAAM,IAAII,KAAM,CAAA,CAAC,0BAA0B,EAAEJ,KAAK,CAAC,CAAA;AACrD;;AAhCQE,QAAAA,IAAAA,CAAAA,WAAAA,GAAc,IAAIO,GAAAA,EAAAA;AAElBD,QAAAA,IAAAA,CAAAA,UAAAA,GAAa,IAAIC,GAAAA,EAAAA;;AA+B3B;;;;"}

View File

@@ -0,0 +1,11 @@
import type { Core, Struct, Utils } from '@strapi/types';
interface Options {
contentType: Struct.CollectionTypeSchema;
}
/**
*
* Returns a collection type controller to handle default core-api actions
*/
declare const createCollectionTypeController: ({ contentType, }: Options) => Utils.PartialWithThis<Core.CoreAPI.Controller.CollectionType>;
export { createCollectionTypeController };
//# sourceMappingURL=collection-type.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"collection-type.d.ts","sourceRoot":"","sources":["../../../src/core-api/controller/collection-type.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAO,MAAM,eAAe,CAAC;AAG9D,UAAU,OAAO;IACf,WAAW,EAAE,MAAM,CAAC,oBAAoB,CAAC;CAC1C;AAED;;;GAGG;AACH,QAAA,MAAM,8BAA8B,qBAEjC,OAAO,KAAG,MAAM,eAAe,CAAC,KAAK,OAAO,CAAC,UAAU,CAAC,cAAc,CAoGxE,CAAC;AAEF,OAAO,EAAE,8BAA8B,EAAE,CAAC"}

View File

@@ -0,0 +1,85 @@
'use strict';
var fp = require('lodash/fp');
var strapiUtils = require('@strapi/utils');
/**
*
* Returns a collection type controller to handle default core-api actions
*/ const createCollectionTypeController = ({ contentType })=>{
const uid = contentType.uid;
// TODO: transform into a class
return {
/**
* Retrieve records.
*/ async find (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { results, pagination } = await strapi.service(uid).find(sanitizedQuery);
const sanitizedResults = await this.sanitizeOutput(results, ctx);
return this.transformResponse(sanitizedResults, {
pagination
});
},
/**
* Retrieve a record
*/ async findOne (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const entity = await strapi.service(uid).findOne(id, sanitizedQuery);
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* Create a record.
*/ async create (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { body = {} } = ctx.request;
if (!fp.isObject(body.data)) {
throw new strapiUtils.errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).create({
...sanitizedQuery,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
ctx.status = 201;
return this.transformResponse(sanitizedEntity);
},
/**
* Update a record.
*/ async update (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { body = {} } = ctx.request;
if (!fp.isObject(body.data)) {
throw new strapiUtils.errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).update(id, {
...sanitizedQuery,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* Destroy a record.
*/ async delete (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
await strapi.service(uid).delete(id, sanitizedQuery);
ctx.status = 204;
}
};
};
exports.createCollectionTypeController = createCollectionTypeController;
//# sourceMappingURL=collection-type.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,83 @@
import { isObject } from 'lodash/fp';
import { errors } from '@strapi/utils';
/**
*
* Returns a collection type controller to handle default core-api actions
*/ const createCollectionTypeController = ({ contentType })=>{
const uid = contentType.uid;
// TODO: transform into a class
return {
/**
* Retrieve records.
*/ async find (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { results, pagination } = await strapi.service(uid).find(sanitizedQuery);
const sanitizedResults = await this.sanitizeOutput(results, ctx);
return this.transformResponse(sanitizedResults, {
pagination
});
},
/**
* Retrieve a record
*/ async findOne (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const entity = await strapi.service(uid).findOne(id, sanitizedQuery);
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* Create a record.
*/ async create (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { body = {} } = ctx.request;
if (!isObject(body.data)) {
throw new errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).create({
...sanitizedQuery,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
ctx.status = 201;
return this.transformResponse(sanitizedEntity);
},
/**
* Update a record.
*/ async update (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const { body = {} } = ctx.request;
if (!isObject(body.data)) {
throw new errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).update(id, {
...sanitizedQuery,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* Destroy a record.
*/ async delete (ctx) {
const { id } = ctx.params;
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
await strapi.service(uid).delete(id, sanitizedQuery);
ctx.status = 204;
}
};
};
export { createCollectionTypeController };
//# sourceMappingURL=collection-type.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
import type { Core, Struct } from '@strapi/types';
declare function createController<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {
contentType: T;
}): T extends Struct.SingleTypeSchema ? Core.CoreAPI.Controller.SingleType : Core.CoreAPI.Controller.CollectionType;
export { createController };
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core-api/controller/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAalD,iBAAS,gBAAgB,CAAC,CAAC,SAAS,MAAM,CAAC,gBAAgB,GAAG,MAAM,CAAC,oBAAoB,EAAE,IAAI,EAAE;IAC/F,WAAW,EAAE,CAAC,CAAC;CAChB,GAAG,CAAC,SAAS,MAAM,CAAC,gBAAgB,GACjC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,GAClC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,cAAc,CAAC;AA2D3C,OAAO,EAAE,gBAAgB,EAAE,CAAC"}

View File

@@ -0,0 +1,67 @@
'use strict';
var fp = require('lodash/fp');
var strapiUtils = require('@strapi/utils');
var transform = require('./transform.js');
var singleType = require('./single-type.js');
var collectionType = require('./collection-type.js');
var requestContext = require('../../services/request-context.js');
const isSingleType = (contentType)=>strapiUtils.contentTypes.isSingleType(contentType);
const getAuthFromKoaContext = (ctx)=>fp.prop('state.auth', ctx) ?? {};
function createController({ contentType }) {
// TODO: replace with Base class + SingleType and CollectionType classes
const proto = {
transformResponse (data, meta) {
const ctx = requestContext.get();
return transform.transformResponse(data, meta, {
contentType,
useJsonAPIFormat: ctx?.headers?.['strapi-response-format'] === 'v4'
});
},
async sanitizeOutput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.output(data, contentType, {
auth
});
},
async sanitizeInput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.input(data, contentType, {
auth
});
},
async sanitizeQuery (ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.query(ctx.query, contentType, {
auth
});
},
async validateQuery (ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.validate.query(ctx.query, contentType, {
auth
});
},
async validateInput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.validate.input(data, contentType, {
auth
});
}
};
let ctrl;
if (isSingleType(contentType)) {
ctrl = singleType.createSingleTypeController({
contentType
});
} else {
ctrl = collectionType.createCollectionTypeController({
contentType
});
}
return Object.assign(Object.create(proto), ctrl);
}
exports.createController = createController;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../../../src/core-api/controller/index.ts"],"sourcesContent":["import { prop } from 'lodash/fp';\nimport type Koa from 'koa';\nimport { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Core, Struct } from '@strapi/types';\n\nimport { transformResponse } from './transform';\nimport { createSingleTypeController } from './single-type';\nimport { createCollectionTypeController } from './collection-type';\nimport requestCtx from '../../services/request-context';\n\nconst isSingleType = (\n contentType: Struct.ContentTypeSchema\n): contentType is Struct.SingleTypeSchema => contentTypeUtils.isSingleType(contentType);\n\nconst getAuthFromKoaContext = (ctx: Koa.Context) => prop('state.auth', ctx) ?? {};\n\nfunction createController<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {\n contentType: T;\n}): T extends Struct.SingleTypeSchema\n ? Core.CoreAPI.Controller.SingleType\n : Core.CoreAPI.Controller.CollectionType;\nfunction createController({\n contentType,\n}: {\n contentType: Struct.SingleTypeSchema | Struct.CollectionTypeSchema;\n}) {\n // TODO: replace with Base class + SingleType and CollectionType classes\n\n const proto: Core.CoreAPI.Controller.Base = {\n transformResponse(data, meta) {\n const ctx = requestCtx.get();\n return transformResponse(data, meta, {\n contentType,\n useJsonAPIFormat: ctx?.headers?.['strapi-response-format'] === 'v4',\n });\n },\n\n async sanitizeOutput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.output(data, contentType, { auth });\n },\n\n async sanitizeInput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.input(data, contentType, { auth });\n },\n\n async sanitizeQuery(ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.query(ctx.query, contentType, { auth });\n },\n\n async validateQuery(ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.validate.query(ctx.query, contentType, { auth });\n },\n\n async validateInput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.validate.input(data, contentType, { auth });\n },\n };\n\n let ctrl;\n\n if (isSingleType(contentType)) {\n ctrl = createSingleTypeController({ contentType });\n } else {\n ctrl = createCollectionTypeController({ contentType });\n }\n\n return Object.assign(Object.create(proto), ctrl);\n}\n\nexport { createController };\n"],"names":["isSingleType","contentType","contentTypeUtils","getAuthFromKoaContext","ctx","prop","createController","proto","transformResponse","data","meta","requestCtx","get","useJsonAPIFormat","headers","sanitizeOutput","auth","strapi","contentAPI","sanitize","output","sanitizeInput","input","sanitizeQuery","query","validateQuery","validate","validateInput","ctrl","createSingleTypeController","createCollectionTypeController","Object","assign","create"],"mappings":";;;;;;;;;AAUA,MAAMA,YAAe,GAAA,CACnBC,WAC2CC,GAAAA,wBAAAA,CAAiBF,YAAY,CAACC,WAAAA,CAAAA;AAE3E,MAAME,wBAAwB,CAACC,GAAAA,GAAqBC,OAAK,CAAA,YAAA,EAAcD,QAAQ,EAAC;AAOhF,SAASE,gBAAAA,CAAiB,EACxBL,WAAW,EAGZ,EAAA;;AAGC,IAAA,MAAMM,KAAsC,GAAA;QAC1CC,iBAAkBC,CAAAA,CAAAA,IAAI,EAAEC,IAAI,EAAA;YAC1B,MAAMN,GAAAA,GAAMO,eAAWC,GAAG,EAAA;YAC1B,OAAOJ,2BAAAA,CAAkBC,MAAMC,IAAM,EAAA;AACnCT,gBAAAA,WAAAA;AACAY,gBAAAA,gBAAAA,EAAkBT,GAAKU,EAAAA,OAAAA,GAAU,wBAAA,CAAyB,KAAK;AACjE,aAAA,CAAA;AACF,SAAA;QAEA,MAAMC,cAAAA,CAAAA,CAAeN,IAAI,EAAEL,GAAG,EAAA;AAC5B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACC,MAAM,CAACX,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACrE,SAAA;QAEA,MAAMK,aAAAA,CAAAA,CAAcZ,IAAI,EAAEL,GAAG,EAAA;AAC3B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACG,KAAK,CAACb,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACpE,SAAA;AAEA,QAAA,MAAMO,eAAcnB,GAAG,EAAA;AACrB,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACK,KAAK,CAACpB,GAAAA,CAAIoB,KAAK,EAAEvB,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACzE,SAAA;AAEA,QAAA,MAAMS,eAAcrB,GAAG,EAAA;AACrB,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACQ,QAAQ,CAACF,KAAK,CAACpB,GAAAA,CAAIoB,KAAK,EAAEvB,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACzE,SAAA;QAEA,MAAMW,aAAAA,CAAAA,CAAclB,IAAI,EAAEL,GAAG,EAAA;AAC3B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACQ,QAAQ,CAACJ,KAAK,CAACb,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACpE;AACF,KAAA;IAEA,IAAIY,IAAAA;AAEJ,IAAA,IAAI5B,aAAaC,WAAc,CAAA,EAAA;AAC7B2B,QAAAA,IAAAA,GAAOC,qCAA2B,CAAA;AAAE5B,YAAAA;AAAY,SAAA,CAAA;KAC3C,MAAA;AACL2B,QAAAA,IAAAA,GAAOE,6CAA+B,CAAA;AAAE7B,YAAAA;AAAY,SAAA,CAAA;AACtD;AAEA,IAAA,OAAO8B,OAAOC,MAAM,CAACD,MAAOE,CAAAA,MAAM,CAAC1B,KAAQqB,CAAAA,EAAAA,IAAAA,CAAAA;AAC7C;;;;"}

View File

@@ -0,0 +1,65 @@
import { prop } from 'lodash/fp';
import { contentTypes } from '@strapi/utils';
import { transformResponse } from './transform.mjs';
import { createSingleTypeController } from './single-type.mjs';
import { createCollectionTypeController } from './collection-type.mjs';
import requestCtx from '../../services/request-context.mjs';
const isSingleType = (contentType)=>contentTypes.isSingleType(contentType);
const getAuthFromKoaContext = (ctx)=>prop('state.auth', ctx) ?? {};
function createController({ contentType }) {
// TODO: replace with Base class + SingleType and CollectionType classes
const proto = {
transformResponse (data, meta) {
const ctx = requestCtx.get();
return transformResponse(data, meta, {
contentType,
useJsonAPIFormat: ctx?.headers?.['strapi-response-format'] === 'v4'
});
},
async sanitizeOutput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.output(data, contentType, {
auth
});
},
async sanitizeInput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.input(data, contentType, {
auth
});
},
async sanitizeQuery (ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.sanitize.query(ctx.query, contentType, {
auth
});
},
async validateQuery (ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.validate.query(ctx.query, contentType, {
auth
});
},
async validateInput (data, ctx) {
const auth = getAuthFromKoaContext(ctx);
return strapi.contentAPI.validate.input(data, contentType, {
auth
});
}
};
let ctrl;
if (isSingleType(contentType)) {
ctrl = createSingleTypeController({
contentType
});
} else {
ctrl = createCollectionTypeController({
contentType
});
}
return Object.assign(Object.create(proto), ctrl);
}
export { createController };
//# sourceMappingURL=index.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sources":["../../../src/core-api/controller/index.ts"],"sourcesContent":["import { prop } from 'lodash/fp';\nimport type Koa from 'koa';\nimport { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Core, Struct } from '@strapi/types';\n\nimport { transformResponse } from './transform';\nimport { createSingleTypeController } from './single-type';\nimport { createCollectionTypeController } from './collection-type';\nimport requestCtx from '../../services/request-context';\n\nconst isSingleType = (\n contentType: Struct.ContentTypeSchema\n): contentType is Struct.SingleTypeSchema => contentTypeUtils.isSingleType(contentType);\n\nconst getAuthFromKoaContext = (ctx: Koa.Context) => prop('state.auth', ctx) ?? {};\n\nfunction createController<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {\n contentType: T;\n}): T extends Struct.SingleTypeSchema\n ? Core.CoreAPI.Controller.SingleType\n : Core.CoreAPI.Controller.CollectionType;\nfunction createController({\n contentType,\n}: {\n contentType: Struct.SingleTypeSchema | Struct.CollectionTypeSchema;\n}) {\n // TODO: replace with Base class + SingleType and CollectionType classes\n\n const proto: Core.CoreAPI.Controller.Base = {\n transformResponse(data, meta) {\n const ctx = requestCtx.get();\n return transformResponse(data, meta, {\n contentType,\n useJsonAPIFormat: ctx?.headers?.['strapi-response-format'] === 'v4',\n });\n },\n\n async sanitizeOutput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.output(data, contentType, { auth });\n },\n\n async sanitizeInput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.input(data, contentType, { auth });\n },\n\n async sanitizeQuery(ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.sanitize.query(ctx.query, contentType, { auth });\n },\n\n async validateQuery(ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.validate.query(ctx.query, contentType, { auth });\n },\n\n async validateInput(data, ctx) {\n const auth = getAuthFromKoaContext(ctx);\n\n return strapi.contentAPI.validate.input(data, contentType, { auth });\n },\n };\n\n let ctrl;\n\n if (isSingleType(contentType)) {\n ctrl = createSingleTypeController({ contentType });\n } else {\n ctrl = createCollectionTypeController({ contentType });\n }\n\n return Object.assign(Object.create(proto), ctrl);\n}\n\nexport { createController };\n"],"names":["isSingleType","contentType","contentTypeUtils","getAuthFromKoaContext","ctx","prop","createController","proto","transformResponse","data","meta","requestCtx","get","useJsonAPIFormat","headers","sanitizeOutput","auth","strapi","contentAPI","sanitize","output","sanitizeInput","input","sanitizeQuery","query","validateQuery","validate","validateInput","ctrl","createSingleTypeController","createCollectionTypeController","Object","assign","create"],"mappings":";;;;;;;AAUA,MAAMA,YAAe,GAAA,CACnBC,WAC2CC,GAAAA,YAAAA,CAAiBF,YAAY,CAACC,WAAAA,CAAAA;AAE3E,MAAME,wBAAwB,CAACC,GAAAA,GAAqBC,IAAK,CAAA,YAAA,EAAcD,QAAQ,EAAC;AAOhF,SAASE,gBAAAA,CAAiB,EACxBL,WAAW,EAGZ,EAAA;;AAGC,IAAA,MAAMM,KAAsC,GAAA;QAC1CC,iBAAkBC,CAAAA,CAAAA,IAAI,EAAEC,IAAI,EAAA;YAC1B,MAAMN,GAAAA,GAAMO,WAAWC,GAAG,EAAA;YAC1B,OAAOJ,iBAAAA,CAAkBC,MAAMC,IAAM,EAAA;AACnCT,gBAAAA,WAAAA;AACAY,gBAAAA,gBAAAA,EAAkBT,GAAKU,EAAAA,OAAAA,GAAU,wBAAA,CAAyB,KAAK;AACjE,aAAA,CAAA;AACF,SAAA;QAEA,MAAMC,cAAAA,CAAAA,CAAeN,IAAI,EAAEL,GAAG,EAAA;AAC5B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACC,MAAM,CAACX,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACrE,SAAA;QAEA,MAAMK,aAAAA,CAAAA,CAAcZ,IAAI,EAAEL,GAAG,EAAA;AAC3B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACG,KAAK,CAACb,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACpE,SAAA;AAEA,QAAA,MAAMO,eAAcnB,GAAG,EAAA;AACrB,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACC,QAAQ,CAACK,KAAK,CAACpB,GAAAA,CAAIoB,KAAK,EAAEvB,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACzE,SAAA;AAEA,QAAA,MAAMS,eAAcrB,GAAG,EAAA;AACrB,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACQ,QAAQ,CAACF,KAAK,CAACpB,GAAAA,CAAIoB,KAAK,EAAEvB,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACzE,SAAA;QAEA,MAAMW,aAAAA,CAAAA,CAAclB,IAAI,EAAEL,GAAG,EAAA;AAC3B,YAAA,MAAMY,OAAOb,qBAAsBC,CAAAA,GAAAA,CAAAA;YAEnC,OAAOa,MAAAA,CAAOC,UAAU,CAACQ,QAAQ,CAACJ,KAAK,CAACb,MAAMR,WAAa,EAAA;AAAEe,gBAAAA;AAAK,aAAA,CAAA;AACpE;AACF,KAAA;IAEA,IAAIY,IAAAA;AAEJ,IAAA,IAAI5B,aAAaC,WAAc,CAAA,EAAA;AAC7B2B,QAAAA,IAAAA,GAAOC,0BAA2B,CAAA;AAAE5B,YAAAA;AAAY,SAAA,CAAA;KAC3C,MAAA;AACL2B,QAAAA,IAAAA,GAAOE,8BAA+B,CAAA;AAAE7B,YAAAA;AAAY,SAAA,CAAA;AACtD;AAEA,IAAA,OAAO8B,OAAOC,MAAM,CAACD,MAAOE,CAAAA,MAAM,CAAC1B,KAAQqB,CAAAA,EAAAA,IAAAA,CAAAA;AAC7C;;;;"}

View File

@@ -0,0 +1,10 @@
import type { Struct, Core, Utils } from '@strapi/types';
interface Options {
contentType: Struct.SingleTypeSchema;
}
/**
* Returns a single type controller to handle default core-api actions
*/
declare const createSingleTypeController: ({ contentType, }: Options) => Utils.PartialWithThis<Core.CoreAPI.Controller.SingleType>;
export { createSingleTypeController };
//# sourceMappingURL=single-type.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"single-type.d.ts","sourceRoot":"","sources":["../../../src/core-api/controller/single-type.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAO,MAAM,eAAe,CAAC;AAE9D,UAAU,OAAO;IACf,WAAW,EAAE,MAAM,CAAC,gBAAgB,CAAC;CACtC;AAED;;GAEG;AACH,QAAA,MAAM,0BAA0B,qBAE7B,OAAO,KAAG,MAAM,eAAe,CAAC,KAAK,OAAO,CAAC,UAAU,CAAC,UAAU,CAoDpE,CAAC;AAEF,OAAO,EAAE,0BAA0B,EAAE,CAAC"}

View File

@@ -0,0 +1,47 @@
'use strict';
var fp = require('lodash/fp');
var strapiUtils = require('@strapi/utils');
/**
* Returns a single type controller to handle default core-api actions
*/ const createSingleTypeController = ({ contentType })=>{
const uid = contentType.uid;
// TODO: transform into a class
return {
/**
* Retrieve single type content
*
*/ async find (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const entity = await strapi.service(uid).find(sanitizedQuery);
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* create or update single type content.
*/ async update (ctx) {
const { query, body = {} } = ctx.request;
if (!fp.isObject(body.data)) {
throw new strapiUtils.errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).createOrUpdate({
...query,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
async delete (ctx) {
const { query } = ctx;
await strapi.service(uid).delete(query);
ctx.status = 204;
}
};
};
exports.createSingleTypeController = createSingleTypeController;
//# sourceMappingURL=single-type.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"single-type.js","sources":["../../../src/core-api/controller/single-type.ts"],"sourcesContent":["import { isObject } from 'lodash/fp';\nimport { errors } from '@strapi/utils';\nimport type { Struct, Core, Utils, UID } from '@strapi/types';\n\ninterface Options {\n contentType: Struct.SingleTypeSchema;\n}\n\n/**\n * Returns a single type controller to handle default core-api actions\n */\nconst createSingleTypeController = ({\n contentType,\n}: Options): Utils.PartialWithThis<Core.CoreAPI.Controller.SingleType> => {\n const uid = contentType.uid as UID.Service;\n\n // TODO: transform into a class\n return {\n /**\n * Retrieve single type content\n *\n */\n async find(ctx) {\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const entity = await strapi.service(uid).find(sanitizedQuery);\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * create or update single type content.\n */\n async update(ctx) {\n const { query, body = {} as any } = ctx.request;\n\n if (!isObject(body.data)) {\n throw new errors.ValidationError('Missing \"data\" payload in the request body');\n }\n\n await this.validateInput(body.data, ctx);\n\n const sanitizedInputData = await this.sanitizeInput(body.data, ctx);\n\n const entity = await strapi.service(uid).createOrUpdate({\n ...query,\n data: sanitizedInputData,\n });\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n async delete(ctx) {\n const { query } = ctx;\n\n await strapi.service(uid).delete(query);\n\n ctx.status = 204;\n },\n };\n};\n\nexport { createSingleTypeController };\n"],"names":["createSingleTypeController","contentType","uid","find","ctx","validateQuery","sanitizedQuery","sanitizeQuery","entity","strapi","service","sanitizedEntity","sanitizeOutput","transformResponse","update","query","body","request","isObject","data","errors","ValidationError","validateInput","sanitizedInputData","sanitizeInput","createOrUpdate","delete","status"],"mappings":";;;;;AAQA;;AAEC,IACKA,MAAAA,0BAAAA,GAA6B,CAAC,EAClCC,WAAW,EACH,GAAA;IACR,MAAMC,GAAAA,GAAMD,YAAYC,GAAG;;IAG3B,OAAO;AACL;;;QAIA,MAAMC,MAAKC,GAAG,EAAA;YACZ,MAAM,IAAI,CAACC,aAAa,CAACD,GAAAA,CAAAA;AACzB,YAAA,MAAME,cAAiB,GAAA,MAAM,IAAI,CAACC,aAAa,CAACH,GAAAA,CAAAA;AAEhD,YAAA,MAAMI,SAAS,MAAMC,MAAAA,CAAOC,OAAO,CAACR,GAAAA,CAAAA,CAAKC,IAAI,CAACG,cAAAA,CAAAA;AAE9C,YAAA,MAAMK,kBAAkB,MAAM,IAAI,CAACC,cAAc,CAACJ,MAAQJ,EAAAA,GAAAA,CAAAA;YAE1D,OAAO,IAAI,CAACS,iBAAiB,CAACF,eAAAA,CAAAA;AAChC,SAAA;AAEA;;QAGA,MAAMG,QAAOV,GAAG,EAAA;YACd,MAAM,EAAEW,KAAK,EAAEC,IAAAA,GAAO,EAAS,EAAE,GAAGZ,GAAAA,CAAIa,OAAO;AAE/C,YAAA,IAAI,CAACC,WAAAA,CAASF,IAAKG,CAAAA,IAAI,CAAG,EAAA;gBACxB,MAAM,IAAIC,kBAAOC,CAAAA,eAAe,CAAC,4CAAA,CAAA;AACnC;AAEA,YAAA,MAAM,IAAI,CAACC,aAAa,CAACN,IAAAA,CAAKG,IAAI,EAAEf,GAAAA,CAAAA;YAEpC,MAAMmB,kBAAAA,GAAqB,MAAM,IAAI,CAACC,aAAa,CAACR,IAAAA,CAAKG,IAAI,EAAEf,GAAAA,CAAAA;AAE/D,YAAA,MAAMI,SAAS,MAAMC,MAAAA,CAAOC,OAAO,CAACR,GAAAA,CAAAA,CAAKuB,cAAc,CAAC;AACtD,gBAAA,GAAGV,KAAK;gBACRI,IAAMI,EAAAA;AACR,aAAA,CAAA;AAEA,YAAA,MAAMZ,kBAAkB,MAAM,IAAI,CAACC,cAAc,CAACJ,MAAQJ,EAAAA,GAAAA,CAAAA;YAE1D,OAAO,IAAI,CAACS,iBAAiB,CAACF,eAAAA,CAAAA;AAChC,SAAA;AAEA,QAAA,MAAMe,QAAOtB,GAAG,EAAA;YACd,MAAM,EAAEW,KAAK,EAAE,GAAGX,GAAAA;AAElB,YAAA,MAAMK,MAAOC,CAAAA,OAAO,CAACR,GAAAA,CAAAA,CAAKwB,MAAM,CAACX,KAAAA,CAAAA;AAEjCX,YAAAA,GAAAA,CAAIuB,MAAM,GAAG,GAAA;AACf;AACF,KAAA;AACF;;;;"}

View File

@@ -0,0 +1,45 @@
import { isObject } from 'lodash/fp';
import { errors } from '@strapi/utils';
/**
* Returns a single type controller to handle default core-api actions
*/ const createSingleTypeController = ({ contentType })=>{
const uid = contentType.uid;
// TODO: transform into a class
return {
/**
* Retrieve single type content
*
*/ async find (ctx) {
await this.validateQuery(ctx);
const sanitizedQuery = await this.sanitizeQuery(ctx);
const entity = await strapi.service(uid).find(sanitizedQuery);
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
/**
* create or update single type content.
*/ async update (ctx) {
const { query, body = {} } = ctx.request;
if (!isObject(body.data)) {
throw new errors.ValidationError('Missing "data" payload in the request body');
}
await this.validateInput(body.data, ctx);
const sanitizedInputData = await this.sanitizeInput(body.data, ctx);
const entity = await strapi.service(uid).createOrUpdate({
...query,
data: sanitizedInputData
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
async delete (ctx) {
const { query } = ctx;
await strapi.service(uid).delete(query);
ctx.status = 204;
}
};
};
export { createSingleTypeController };
//# sourceMappingURL=single-type.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"single-type.mjs","sources":["../../../src/core-api/controller/single-type.ts"],"sourcesContent":["import { isObject } from 'lodash/fp';\nimport { errors } from '@strapi/utils';\nimport type { Struct, Core, Utils, UID } from '@strapi/types';\n\ninterface Options {\n contentType: Struct.SingleTypeSchema;\n}\n\n/**\n * Returns a single type controller to handle default core-api actions\n */\nconst createSingleTypeController = ({\n contentType,\n}: Options): Utils.PartialWithThis<Core.CoreAPI.Controller.SingleType> => {\n const uid = contentType.uid as UID.Service;\n\n // TODO: transform into a class\n return {\n /**\n * Retrieve single type content\n *\n */\n async find(ctx) {\n await this.validateQuery(ctx);\n const sanitizedQuery = await this.sanitizeQuery(ctx);\n\n const entity = await strapi.service(uid).find(sanitizedQuery);\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n /**\n * create or update single type content.\n */\n async update(ctx) {\n const { query, body = {} as any } = ctx.request;\n\n if (!isObject(body.data)) {\n throw new errors.ValidationError('Missing \"data\" payload in the request body');\n }\n\n await this.validateInput(body.data, ctx);\n\n const sanitizedInputData = await this.sanitizeInput(body.data, ctx);\n\n const entity = await strapi.service(uid).createOrUpdate({\n ...query,\n data: sanitizedInputData,\n });\n\n const sanitizedEntity = await this.sanitizeOutput(entity, ctx);\n\n return this.transformResponse(sanitizedEntity);\n },\n\n async delete(ctx) {\n const { query } = ctx;\n\n await strapi.service(uid).delete(query);\n\n ctx.status = 204;\n },\n };\n};\n\nexport { createSingleTypeController };\n"],"names":["createSingleTypeController","contentType","uid","find","ctx","validateQuery","sanitizedQuery","sanitizeQuery","entity","strapi","service","sanitizedEntity","sanitizeOutput","transformResponse","update","query","body","request","isObject","data","errors","ValidationError","validateInput","sanitizedInputData","sanitizeInput","createOrUpdate","delete","status"],"mappings":";;;AAQA;;AAEC,IACKA,MAAAA,0BAAAA,GAA6B,CAAC,EAClCC,WAAW,EACH,GAAA;IACR,MAAMC,GAAAA,GAAMD,YAAYC,GAAG;;IAG3B,OAAO;AACL;;;QAIA,MAAMC,MAAKC,GAAG,EAAA;YACZ,MAAM,IAAI,CAACC,aAAa,CAACD,GAAAA,CAAAA;AACzB,YAAA,MAAME,cAAiB,GAAA,MAAM,IAAI,CAACC,aAAa,CAACH,GAAAA,CAAAA;AAEhD,YAAA,MAAMI,SAAS,MAAMC,MAAAA,CAAOC,OAAO,CAACR,GAAAA,CAAAA,CAAKC,IAAI,CAACG,cAAAA,CAAAA;AAE9C,YAAA,MAAMK,kBAAkB,MAAM,IAAI,CAACC,cAAc,CAACJ,MAAQJ,EAAAA,GAAAA,CAAAA;YAE1D,OAAO,IAAI,CAACS,iBAAiB,CAACF,eAAAA,CAAAA;AAChC,SAAA;AAEA;;QAGA,MAAMG,QAAOV,GAAG,EAAA;YACd,MAAM,EAAEW,KAAK,EAAEC,IAAAA,GAAO,EAAS,EAAE,GAAGZ,GAAAA,CAAIa,OAAO;AAE/C,YAAA,IAAI,CAACC,QAAAA,CAASF,IAAKG,CAAAA,IAAI,CAAG,EAAA;gBACxB,MAAM,IAAIC,MAAOC,CAAAA,eAAe,CAAC,4CAAA,CAAA;AACnC;AAEA,YAAA,MAAM,IAAI,CAACC,aAAa,CAACN,IAAAA,CAAKG,IAAI,EAAEf,GAAAA,CAAAA;YAEpC,MAAMmB,kBAAAA,GAAqB,MAAM,IAAI,CAACC,aAAa,CAACR,IAAAA,CAAKG,IAAI,EAAEf,GAAAA,CAAAA;AAE/D,YAAA,MAAMI,SAAS,MAAMC,MAAAA,CAAOC,OAAO,CAACR,GAAAA,CAAAA,CAAKuB,cAAc,CAAC;AACtD,gBAAA,GAAGV,KAAK;gBACRI,IAAMI,EAAAA;AACR,aAAA,CAAA;AAEA,YAAA,MAAMZ,kBAAkB,MAAM,IAAI,CAACC,cAAc,CAACJ,MAAQJ,EAAAA,GAAAA,CAAAA;YAE1D,OAAO,IAAI,CAACS,iBAAiB,CAACF,eAAAA,CAAAA;AAChC,SAAA;AAEA,QAAA,MAAMe,QAAOtB,GAAG,EAAA;YACd,MAAM,EAAEW,KAAK,EAAE,GAAGX,GAAAA;AAElB,YAAA,MAAMK,MAAOC,CAAAA,OAAO,CAACR,GAAAA,CAAAA,CAAKwB,MAAM,CAACX,KAAAA,CAAAA;AAEjCX,YAAAA,GAAAA,CAAIuB,MAAM,GAAG,GAAA;AACf;AACF,KAAA;AACF;;;;"}

View File

@@ -0,0 +1,14 @@
import type { Struct } from '@strapi/types';
interface TransformOptions {
contentType?: Struct.ContentTypeSchema | Struct.ComponentSchema;
/**
* @deprecated this option is deprecated and will be removed in the next major version
*/
useJsonAPIFormat?: boolean;
}
declare const transformResponse: (resource: any, meta?: unknown, opts?: TransformOptions) => {
data: any;
meta: unknown;
} | null | undefined;
export { transformResponse };
//# sourceMappingURL=transform.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"transform.d.ts","sourceRoot":"","sources":["../../../src/core-api/controller/transform.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAO,MAAM,EAAQ,MAAM,eAAe,CAAC;AA2BvD,UAAU,gBAAgB;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC,iBAAiB,GAAG,MAAM,CAAC,eAAe,CAAC;IAChE;;OAEG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED,QAAA,MAAM,iBAAiB,aACX,GAAG,SACP,OAAO,SACP,gBAAgB;;;oBAgBvB,CAAC;AAkFF,OAAO,EAAE,iBAAiB,EAAE,CAAC"}

View File

@@ -0,0 +1,85 @@
'use strict';
var fp = require('lodash/fp');
function isEntry(property) {
return property === null || fp.isPlainObject(property) || Array.isArray(property);
}
function isDZEntries(property) {
return Array.isArray(property);
}
const transformResponse = (resource, meta = {}, opts = {
useJsonAPIFormat: false
})=>{
if (fp.isNil(resource)) {
return resource;
}
if (!fp.isPlainObject(resource) && !Array.isArray(resource)) {
throw new Error('Entry must be an object or an array of objects');
}
return {
data: opts.useJsonAPIFormat ? transformEntry(resource, opts?.contentType) : resource,
meta
};
};
function transformComponent(data, component) {
if (Array.isArray(data)) {
return data.map((datum)=>transformComponent(datum, component));
}
const res = transformEntry(data, component);
if (fp.isNil(res)) {
return res;
}
const { id, attributes } = res;
return {
id,
...attributes
};
}
function transformEntry(entry, type) {
if (fp.isNil(entry)) {
return entry;
}
if (Array.isArray(entry)) {
return entry.map((singleEntry)=>transformEntry(singleEntry, type));
}
if (!fp.isPlainObject(entry)) {
throw new Error('Entry must be an object');
}
const { id, documentId, ...properties } = entry;
const attributeValues = {};
for (const key of Object.keys(properties)){
const property = properties[key];
const attribute = type && type.attributes[key];
if (attribute && attribute.type === 'relation' && isEntry(property) && 'target' in attribute) {
const data = transformEntry(property, strapi.contentType(attribute.target));
attributeValues[key] = {
data
};
} else if (attribute && attribute.type === 'component' && isEntry(property)) {
attributeValues[key] = transformComponent(property, strapi.components[attribute.component]);
} else if (attribute && attribute.type === 'dynamiczone' && isDZEntries(property)) {
if (fp.isNil(property)) {
attributeValues[key] = property;
}
attributeValues[key] = property.map((subProperty)=>{
return transformComponent(subProperty, strapi.components[subProperty.__component]);
});
} else if (attribute && attribute.type === 'media' && isEntry(property)) {
const data = transformEntry(property, strapi.contentType('plugin::upload.file'));
attributeValues[key] = {
data
};
} else {
attributeValues[key] = property;
}
}
return {
id,
documentId,
attributes: attributeValues
};
}
exports.transformResponse = transformResponse;
//# sourceMappingURL=transform.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,83 @@
import { isNil, isPlainObject } from 'lodash/fp';
function isEntry(property) {
return property === null || isPlainObject(property) || Array.isArray(property);
}
function isDZEntries(property) {
return Array.isArray(property);
}
const transformResponse = (resource, meta = {}, opts = {
useJsonAPIFormat: false
})=>{
if (isNil(resource)) {
return resource;
}
if (!isPlainObject(resource) && !Array.isArray(resource)) {
throw new Error('Entry must be an object or an array of objects');
}
return {
data: opts.useJsonAPIFormat ? transformEntry(resource, opts?.contentType) : resource,
meta
};
};
function transformComponent(data, component) {
if (Array.isArray(data)) {
return data.map((datum)=>transformComponent(datum, component));
}
const res = transformEntry(data, component);
if (isNil(res)) {
return res;
}
const { id, attributes } = res;
return {
id,
...attributes
};
}
function transformEntry(entry, type) {
if (isNil(entry)) {
return entry;
}
if (Array.isArray(entry)) {
return entry.map((singleEntry)=>transformEntry(singleEntry, type));
}
if (!isPlainObject(entry)) {
throw new Error('Entry must be an object');
}
const { id, documentId, ...properties } = entry;
const attributeValues = {};
for (const key of Object.keys(properties)){
const property = properties[key];
const attribute = type && type.attributes[key];
if (attribute && attribute.type === 'relation' && isEntry(property) && 'target' in attribute) {
const data = transformEntry(property, strapi.contentType(attribute.target));
attributeValues[key] = {
data
};
} else if (attribute && attribute.type === 'component' && isEntry(property)) {
attributeValues[key] = transformComponent(property, strapi.components[attribute.component]);
} else if (attribute && attribute.type === 'dynamiczone' && isDZEntries(property)) {
if (isNil(property)) {
attributeValues[key] = property;
}
attributeValues[key] = property.map((subProperty)=>{
return transformComponent(subProperty, strapi.components[subProperty.__component]);
});
} else if (attribute && attribute.type === 'media' && isEntry(property)) {
const data = transformEntry(property, strapi.contentType('plugin::upload.file'));
attributeValues[key] = {
data
};
} else {
attributeValues[key] = property;
}
}
return {
id,
documentId,
attributes: attributeValues
};
}
export { transformResponse };
//# sourceMappingURL=transform.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,24 @@
import type { Schema } from '@strapi/types';
export declare const createRoutes: ({ contentType }: {
contentType: Schema.ContentType;
}) => {
find: {
method: string;
path: string;
handler: string;
config: {};
};
update: {
method: string;
path: string;
handler: string;
config: {};
};
delete: {
method: string;
path: string;
handler: string;
config: {};
};
};
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core-api/routes/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAE5C,eAAO,MAAM,YAAY,oBAAqB;IAAE,WAAW,EAAE,OAAO,WAAW,CAAA;CAAE;;;;;;;;;;;;;;;;;;;CAMhF,CAAC"}

View File

@@ -0,0 +1,69 @@
'use strict';
var strapiUtils = require('@strapi/utils');
const createRoutes = ({ contentType })=>{
if (strapiUtils.contentTypes.isSingleType(contentType)) {
return getSingleTypeRoutes(contentType);
}
return getCollectionTypeRoutes(contentType);
};
const getSingleTypeRoutes = ({ uid, info })=>{
return {
find: {
method: 'GET',
path: `/${info.singularName}`,
handler: `${uid}.find`,
config: {}
},
update: {
method: 'PUT',
path: `/${info.singularName}`,
handler: `${uid}.update`,
config: {}
},
delete: {
method: 'DELETE',
path: `/${info.singularName}`,
handler: `${uid}.delete`,
config: {}
}
};
};
const getCollectionTypeRoutes = ({ uid, info })=>{
return {
find: {
method: 'GET',
path: `/${info.pluralName}`,
handler: `${uid}.find`,
config: {}
},
findOne: {
method: 'GET',
path: `/${info.pluralName}/:id`,
handler: `${uid}.findOne`,
config: {}
},
create: {
method: 'POST',
path: `/${info.pluralName}`,
handler: `${uid}.create`,
config: {}
},
update: {
method: 'PUT',
path: `/${info.pluralName}/:id`,
handler: `${uid}.update`,
config: {}
},
delete: {
method: 'DELETE',
path: `/${info.pluralName}/:id`,
handler: `${uid}.delete`,
config: {}
}
};
};
exports.createRoutes = createRoutes;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../../../src/core-api/routes/index.ts"],"sourcesContent":["import { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Schema } from '@strapi/types';\n\nexport const createRoutes = ({ contentType }: { contentType: Schema.ContentType }) => {\n if (contentTypeUtils.isSingleType(contentType)) {\n return getSingleTypeRoutes(contentType);\n }\n\n return getCollectionTypeRoutes(contentType);\n};\n\nconst getSingleTypeRoutes = ({ uid, info }: Schema.ContentType) => {\n return {\n find: {\n method: 'GET',\n path: `/${info.singularName}`,\n handler: `${uid}.find`,\n config: {},\n },\n update: {\n method: 'PUT',\n path: `/${info.singularName}`,\n handler: `${uid}.update`,\n config: {},\n },\n delete: {\n method: 'DELETE',\n path: `/${info.singularName}`,\n handler: `${uid}.delete`,\n config: {},\n },\n };\n};\n\nconst getCollectionTypeRoutes = ({ uid, info }: Schema.ContentType) => {\n return {\n find: {\n method: 'GET',\n path: `/${info.pluralName}`,\n handler: `${uid}.find`,\n config: {},\n },\n findOne: {\n method: 'GET',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.findOne`,\n config: {},\n },\n create: {\n method: 'POST',\n path: `/${info.pluralName}`,\n handler: `${uid}.create`,\n config: {},\n },\n update: {\n method: 'PUT',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.update`,\n config: {},\n },\n delete: {\n method: 'DELETE',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.delete`,\n config: {},\n },\n };\n};\n"],"names":["createRoutes","contentType","contentTypeUtils","isSingleType","getSingleTypeRoutes","getCollectionTypeRoutes","uid","info","find","method","path","singularName","handler","config","update","delete","pluralName","findOne","create"],"mappings":";;;;AAGaA,MAAAA,YAAAA,GAAe,CAAC,EAAEC,WAAW,EAAuC,GAAA;IAC/E,IAAIC,wBAAAA,CAAiBC,YAAY,CAACF,WAAc,CAAA,EAAA;AAC9C,QAAA,OAAOG,mBAAoBH,CAAAA,WAAAA,CAAAA;AAC7B;AAEA,IAAA,OAAOI,uBAAwBJ,CAAAA,WAAAA,CAAAA;AACjC;AAEA,MAAMG,sBAAsB,CAAC,EAAEE,GAAG,EAAEC,IAAI,EAAsB,GAAA;IAC5D,OAAO;QACLC,IAAM,EAAA;YACJC,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,KAAK,CAAC;AACtBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAC,MAAQ,EAAA;YACNL,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAE,MAAQ,EAAA;YACNN,MAAQ,EAAA,QAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV;AACF,KAAA;AACF,CAAA;AAEA,MAAMR,0BAA0B,CAAC,EAAEC,GAAG,EAAEC,IAAI,EAAsB,GAAA;IAChE,OAAO;QACLC,IAAM,EAAA;YACJC,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKS,CAAAA,UAAU,CAAC,CAAC;AAC3BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,KAAK,CAAC;AACtBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAI,OAAS,EAAA;YACPR,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,QAAQ,CAAC;AACzBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAK,MAAQ,EAAA;YACNT,MAAQ,EAAA,MAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKS,CAAAA,UAAU,CAAC,CAAC;AAC3BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAC,MAAQ,EAAA;YACNL,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAE,MAAQ,EAAA;YACNN,MAAQ,EAAA,QAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV;AACF,KAAA;AACF,CAAA;;;;"}

View File

@@ -0,0 +1,67 @@
import { contentTypes } from '@strapi/utils';
const createRoutes = ({ contentType })=>{
if (contentTypes.isSingleType(contentType)) {
return getSingleTypeRoutes(contentType);
}
return getCollectionTypeRoutes(contentType);
};
const getSingleTypeRoutes = ({ uid, info })=>{
return {
find: {
method: 'GET',
path: `/${info.singularName}`,
handler: `${uid}.find`,
config: {}
},
update: {
method: 'PUT',
path: `/${info.singularName}`,
handler: `${uid}.update`,
config: {}
},
delete: {
method: 'DELETE',
path: `/${info.singularName}`,
handler: `${uid}.delete`,
config: {}
}
};
};
const getCollectionTypeRoutes = ({ uid, info })=>{
return {
find: {
method: 'GET',
path: `/${info.pluralName}`,
handler: `${uid}.find`,
config: {}
},
findOne: {
method: 'GET',
path: `/${info.pluralName}/:id`,
handler: `${uid}.findOne`,
config: {}
},
create: {
method: 'POST',
path: `/${info.pluralName}`,
handler: `${uid}.create`,
config: {}
},
update: {
method: 'PUT',
path: `/${info.pluralName}/:id`,
handler: `${uid}.update`,
config: {}
},
delete: {
method: 'DELETE',
path: `/${info.pluralName}/:id`,
handler: `${uid}.delete`,
config: {}
}
};
};
export { createRoutes };
//# sourceMappingURL=index.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sources":["../../../src/core-api/routes/index.ts"],"sourcesContent":["import { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Schema } from '@strapi/types';\n\nexport const createRoutes = ({ contentType }: { contentType: Schema.ContentType }) => {\n if (contentTypeUtils.isSingleType(contentType)) {\n return getSingleTypeRoutes(contentType);\n }\n\n return getCollectionTypeRoutes(contentType);\n};\n\nconst getSingleTypeRoutes = ({ uid, info }: Schema.ContentType) => {\n return {\n find: {\n method: 'GET',\n path: `/${info.singularName}`,\n handler: `${uid}.find`,\n config: {},\n },\n update: {\n method: 'PUT',\n path: `/${info.singularName}`,\n handler: `${uid}.update`,\n config: {},\n },\n delete: {\n method: 'DELETE',\n path: `/${info.singularName}`,\n handler: `${uid}.delete`,\n config: {},\n },\n };\n};\n\nconst getCollectionTypeRoutes = ({ uid, info }: Schema.ContentType) => {\n return {\n find: {\n method: 'GET',\n path: `/${info.pluralName}`,\n handler: `${uid}.find`,\n config: {},\n },\n findOne: {\n method: 'GET',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.findOne`,\n config: {},\n },\n create: {\n method: 'POST',\n path: `/${info.pluralName}`,\n handler: `${uid}.create`,\n config: {},\n },\n update: {\n method: 'PUT',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.update`,\n config: {},\n },\n delete: {\n method: 'DELETE',\n path: `/${info.pluralName}/:id`,\n handler: `${uid}.delete`,\n config: {},\n },\n };\n};\n"],"names":["createRoutes","contentType","contentTypeUtils","isSingleType","getSingleTypeRoutes","getCollectionTypeRoutes","uid","info","find","method","path","singularName","handler","config","update","delete","pluralName","findOne","create"],"mappings":";;AAGaA,MAAAA,YAAAA,GAAe,CAAC,EAAEC,WAAW,EAAuC,GAAA;IAC/E,IAAIC,YAAAA,CAAiBC,YAAY,CAACF,WAAc,CAAA,EAAA;AAC9C,QAAA,OAAOG,mBAAoBH,CAAAA,WAAAA,CAAAA;AAC7B;AAEA,IAAA,OAAOI,uBAAwBJ,CAAAA,WAAAA,CAAAA;AACjC;AAEA,MAAMG,sBAAsB,CAAC,EAAEE,GAAG,EAAEC,IAAI,EAAsB,GAAA;IAC5D,OAAO;QACLC,IAAM,EAAA;YACJC,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,KAAK,CAAC;AACtBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAC,MAAQ,EAAA;YACNL,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAE,MAAQ,EAAA;YACNN,MAAQ,EAAA,QAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKI,CAAAA,YAAY,CAAC,CAAC;AAC7BC,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV;AACF,KAAA;AACF,CAAA;AAEA,MAAMR,0BAA0B,CAAC,EAAEC,GAAG,EAAEC,IAAI,EAAsB,GAAA;IAChE,OAAO;QACLC,IAAM,EAAA;YACJC,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKS,CAAAA,UAAU,CAAC,CAAC;AAC3BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,KAAK,CAAC;AACtBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAI,OAAS,EAAA;YACPR,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,QAAQ,CAAC;AACzBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAK,MAAQ,EAAA;YACNT,MAAQ,EAAA,MAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,IAAKS,CAAAA,UAAU,CAAC,CAAC;AAC3BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAC,MAAQ,EAAA;YACNL,MAAQ,EAAA,KAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV,SAAA;QACAE,MAAQ,EAAA;YACNN,MAAQ,EAAA,QAAA;AACRC,YAAAA,IAAAA,EAAM,CAAC,CAAC,EAAEH,KAAKS,UAAU,CAAC,IAAI,CAAC;AAC/BJ,YAAAA,OAAAA,EAAS,CAAC,EAAEN,GAAI,CAAA,OAAO,CAAC;AACxBO,YAAAA,MAAAA,EAAQ;AACV;AACF,KAAA;AACF,CAAA;;;;"}

View File

@@ -0,0 +1,27 @@
import type { Core, Struct, Modules } from '@strapi/types';
import { CoreService } from './core-service';
export declare class CollectionTypeService extends CoreService implements Core.CoreAPI.Service.CollectionType {
private contentType;
constructor(contentType: Struct.CollectionTypeSchema);
find(params?: {}): Promise<{
results: Modules.Documents.AnyDocument[];
pagination: import("@strapi/utils/dist/pagination").PagePatinationInformation | import("@strapi/utils/dist/pagination").OffsetPaginationInformation;
}>;
findOne(documentId: Modules.Documents.ID, params?: {}): import("@strapi/types/dist/modules/documents/result/document-engine").FindOne<import("@strapi/types/dist/uid").ContentType, any>;
create(params?: {
data: {};
}): Promise<Modules.Documents.AnyDocument>;
update(documentId: Modules.Documents.ID, params?: {
data: {};
}): import("@strapi/types/dist/modules/documents/result/document-engine").Update<import("@strapi/types/dist/uid").ContentType, any>;
delete(documentId: Modules.Documents.ID, params?: {}): Promise<{
deletedEntries: number;
}>;
}
/**
*
* Returns a collection type service to handle default core-api actions
*/
declare const createCollectionTypeService: (contentType: Struct.CollectionTypeSchema) => Core.CoreAPI.Service.CollectionType;
export { createCollectionTypeService };
//# sourceMappingURL=collection-type.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"collection-type.d.ts","sourceRoot":"","sources":["../../../src/core-api/service/collection-type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAS3D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,qBAAa,qBACX,SAAQ,WACR,YAAW,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc;IAE9C,OAAO,CAAC,WAAW,CAA8B;gBAErC,WAAW,EAAE,MAAM,CAAC,oBAAoB;IAM9C,IAAI,CAAC,MAAM,KAAK;;;;IAgCtB,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,SAAS,CAAC,EAAE,EAAE,MAAM,KAAK;IAS/C,MAAM,CAAC,MAAM;;KAAe;IAMlC,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,SAAS,CAAC,EAAE,EAAE,MAAM;;KAAe;IASxD,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,SAAS,CAAC,EAAE,EAAE,MAAM,KAAK;;;CAU3D;AAED;;;GAGG;AAEH,QAAA,MAAM,2BAA2B,gBAClB,OAAO,oBAAoB,KACvC,KAAK,OAAO,CAAC,OAAO,CAAC,cAEvB,CAAC;AAEF,OAAO,EAAE,2BAA2B,EAAE,CAAC"}

View File

@@ -0,0 +1,80 @@
'use strict';
var pagination = require('./pagination.js');
var coreService = require('./core-service.js');
class CollectionTypeService extends coreService.CoreService {
async find(params = {}) {
const { uid } = this.contentType;
const fetchParams = this.getFetchParams(params);
const paginationInfo = pagination.getPaginationInfo(fetchParams);
const isPaged = pagination.isPagedPagination(fetchParams.pagination);
const results = await strapi.documents(uid).findMany({
...fetchParams,
...paginationInfo
});
if (pagination.shouldCount(fetchParams)) {
const count = await strapi.documents(uid).count({
...fetchParams,
...paginationInfo
});
if (typeof count !== 'number') {
throw new Error('Count should be a number');
}
return {
results,
pagination: pagination.transformPaginationResponse(paginationInfo, count, isPaged)
};
}
return {
results,
pagination: pagination.transformPaginationResponse(paginationInfo, undefined, isPaged)
};
}
findOne(documentId, params = {}) {
const { uid } = this.contentType;
return strapi.documents(uid).findOne({
...this.getFetchParams(params),
documentId
});
}
async create(params = {
data: {}
}) {
const { uid } = this.contentType;
return strapi.documents(uid).create(this.getFetchParams(params));
}
update(documentId, params = {
data: {}
}) {
const { uid } = this.contentType;
return strapi.documents(uid).update({
...this.getFetchParams(params),
documentId
});
}
async delete(documentId, params = {}) {
const { uid } = this.contentType;
const { entries } = await strapi.documents(uid).delete({
...this.getFetchParams(params),
documentId
});
return {
deletedEntries: entries.length
};
}
constructor(contentType){
super();
this.contentType = contentType;
}
}
/**
*
* Returns a collection type service to handle default core-api actions
*/ const createCollectionTypeService = (contentType)=>{
return new CollectionTypeService(contentType);
};
exports.CollectionTypeService = CollectionTypeService;
exports.createCollectionTypeService = createCollectionTypeService;
//# sourceMappingURL=collection-type.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,77 @@
import { getPaginationInfo, isPagedPagination, shouldCount, transformPaginationResponse } from './pagination.mjs';
import { CoreService } from './core-service.mjs';
class CollectionTypeService extends CoreService {
async find(params = {}) {
const { uid } = this.contentType;
const fetchParams = this.getFetchParams(params);
const paginationInfo = getPaginationInfo(fetchParams);
const isPaged = isPagedPagination(fetchParams.pagination);
const results = await strapi.documents(uid).findMany({
...fetchParams,
...paginationInfo
});
if (shouldCount(fetchParams)) {
const count = await strapi.documents(uid).count({
...fetchParams,
...paginationInfo
});
if (typeof count !== 'number') {
throw new Error('Count should be a number');
}
return {
results,
pagination: transformPaginationResponse(paginationInfo, count, isPaged)
};
}
return {
results,
pagination: transformPaginationResponse(paginationInfo, undefined, isPaged)
};
}
findOne(documentId, params = {}) {
const { uid } = this.contentType;
return strapi.documents(uid).findOne({
...this.getFetchParams(params),
documentId
});
}
async create(params = {
data: {}
}) {
const { uid } = this.contentType;
return strapi.documents(uid).create(this.getFetchParams(params));
}
update(documentId, params = {
data: {}
}) {
const { uid } = this.contentType;
return strapi.documents(uid).update({
...this.getFetchParams(params),
documentId
});
}
async delete(documentId, params = {}) {
const { uid } = this.contentType;
const { entries } = await strapi.documents(uid).delete({
...this.getFetchParams(params),
documentId
});
return {
deletedEntries: entries.length
};
}
constructor(contentType){
super();
this.contentType = contentType;
}
}
/**
*
* Returns a collection type service to handle default core-api actions
*/ const createCollectionTypeService = (contentType)=>{
return new CollectionTypeService(contentType);
};
export { CollectionTypeService, createCollectionTypeService };
//# sourceMappingURL=collection-type.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
export declare abstract class CoreService {
getFetchParams(params?: {}): any;
}
//# sourceMappingURL=core-service.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"core-service.d.ts","sourceRoot":"","sources":["../../../src/core-api/service/core-service.ts"],"names":[],"mappings":"AAAA,8BAAsB,WAAW;IAC/B,cAAc,CAAC,MAAM,KAAK,GAAG,GAAG;CAMjC"}

View File

@@ -0,0 +1,13 @@
'use strict';
class CoreService {
getFetchParams(params = {}) {
return {
status: 'published',
...params
};
}
}
exports.CoreService = CoreService;
//# sourceMappingURL=core-service.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"core-service.js","sources":["../../../src/core-api/service/core-service.ts"],"sourcesContent":["export abstract class CoreService {\n getFetchParams(params = {}): any {\n return {\n status: 'published',\n ...params,\n };\n }\n}\n"],"names":["CoreService","getFetchParams","params","status"],"mappings":";;AAAO,MAAeA,WAAAA,CAAAA;IACpBC,cAAeC,CAAAA,MAAAA,GAAS,EAAE,EAAO;QAC/B,OAAO;YACLC,MAAQ,EAAA,WAAA;AACR,YAAA,GAAGD;AACL,SAAA;AACF;AACF;;;;"}

View File

@@ -0,0 +1,11 @@
class CoreService {
getFetchParams(params = {}) {
return {
status: 'published',
...params
};
}
}
export { CoreService };
//# sourceMappingURL=core-service.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"core-service.mjs","sources":["../../../src/core-api/service/core-service.ts"],"sourcesContent":["export abstract class CoreService {\n getFetchParams(params = {}): any {\n return {\n status: 'published',\n ...params,\n };\n }\n}\n"],"names":["CoreService","getFetchParams","params","status"],"mappings":"AAAO,MAAeA,WAAAA,CAAAA;IACpBC,cAAeC,CAAAA,MAAAA,GAAS,EAAE,EAAO;QAC/B,OAAO;YACLC,MAAQ,EAAA,WAAA;AACR,YAAA,GAAGD;AACL,SAAA;AACF;AACF;;;;"}

View File

@@ -0,0 +1,9 @@
import type { Core, Struct } from '@strapi/types';
/**
* Returns a core api for the provided model
*/
declare function createService<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {
contentType: T;
}): T extends Struct.SingleTypeSchema ? Core.CoreAPI.Service.SingleType : Core.CoreAPI.Service.CollectionType;
export { createService };
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core-api/service/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AASlD;;GAEG;AACH,iBAAS,aAAa,CAAC,CAAC,SAAS,MAAM,CAAC,gBAAgB,GAAG,MAAM,CAAC,oBAAoB,EAAE,IAAI,EAAE;IAC5F,WAAW,EAAE,CAAC,CAAC;CAChB,GAAG,CAAC,SAAS,MAAM,CAAC,gBAAgB,GACjC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,GAC/B,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC;AAaxC,OAAO,EAAE,aAAa,EAAE,CAAC"}

View File

@@ -0,0 +1,16 @@
'use strict';
var strapiUtils = require('@strapi/utils');
var singleType = require('./single-type.js');
var collectionType = require('./collection-type.js');
const isSingleType = (contentType)=>strapiUtils.contentTypes.isSingleType(contentType);
function createService({ contentType }) {
if (isSingleType(contentType)) {
return singleType.createSingleTypeService(contentType);
}
return collectionType.createCollectionTypeService(contentType);
}
exports.createService = createService;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../../../src/core-api/service/index.ts"],"sourcesContent":["import { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Core, Struct } from '@strapi/types';\n\nimport { createSingleTypeService } from './single-type';\nimport { createCollectionTypeService } from './collection-type';\n\nconst isSingleType = (\n contentType: Struct.ContentTypeSchema\n): contentType is Struct.SingleTypeSchema => contentTypeUtils.isSingleType(contentType);\n\n/**\n * Returns a core api for the provided model\n */\nfunction createService<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {\n contentType: T;\n}): T extends Struct.SingleTypeSchema\n ? Core.CoreAPI.Service.SingleType\n : Core.CoreAPI.Service.CollectionType;\nfunction createService({\n contentType,\n}: {\n contentType: Struct.CollectionTypeSchema | Struct.SingleTypeSchema;\n}): Core.CoreAPI.Service.SingleType | Core.CoreAPI.Service.CollectionType {\n if (isSingleType(contentType)) {\n return createSingleTypeService(contentType);\n }\n\n return createCollectionTypeService(contentType);\n}\n\nexport { createService };\n"],"names":["isSingleType","contentType","contentTypeUtils","createService","createSingleTypeService","createCollectionTypeService"],"mappings":";;;;;;AAMA,MAAMA,YAAe,GAAA,CACnBC,WAC2CC,GAAAA,wBAAAA,CAAiBF,YAAY,CAACC,WAAAA,CAAAA;AAU3E,SAASE,aAAAA,CAAc,EACrBF,WAAW,EAGZ,EAAA;AACC,IAAA,IAAID,aAAaC,WAAc,CAAA,EAAA;AAC7B,QAAA,OAAOG,kCAAwBH,CAAAA,WAAAA,CAAAA;AACjC;AAEA,IAAA,OAAOI,0CAA4BJ,CAAAA,WAAAA,CAAAA;AACrC;;;;"}

View File

@@ -0,0 +1,14 @@
import { contentTypes } from '@strapi/utils';
import { createSingleTypeService } from './single-type.mjs';
import { createCollectionTypeService } from './collection-type.mjs';
const isSingleType = (contentType)=>contentTypes.isSingleType(contentType);
function createService({ contentType }) {
if (isSingleType(contentType)) {
return createSingleTypeService(contentType);
}
return createCollectionTypeService(contentType);
}
export { createService };
//# sourceMappingURL=index.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sources":["../../../src/core-api/service/index.ts"],"sourcesContent":["import { contentTypes as contentTypeUtils } from '@strapi/utils';\nimport type { Core, Struct } from '@strapi/types';\n\nimport { createSingleTypeService } from './single-type';\nimport { createCollectionTypeService } from './collection-type';\n\nconst isSingleType = (\n contentType: Struct.ContentTypeSchema\n): contentType is Struct.SingleTypeSchema => contentTypeUtils.isSingleType(contentType);\n\n/**\n * Returns a core api for the provided model\n */\nfunction createService<T extends Struct.SingleTypeSchema | Struct.CollectionTypeSchema>(opts: {\n contentType: T;\n}): T extends Struct.SingleTypeSchema\n ? Core.CoreAPI.Service.SingleType\n : Core.CoreAPI.Service.CollectionType;\nfunction createService({\n contentType,\n}: {\n contentType: Struct.CollectionTypeSchema | Struct.SingleTypeSchema;\n}): Core.CoreAPI.Service.SingleType | Core.CoreAPI.Service.CollectionType {\n if (isSingleType(contentType)) {\n return createSingleTypeService(contentType);\n }\n\n return createCollectionTypeService(contentType);\n}\n\nexport { createService };\n"],"names":["isSingleType","contentType","contentTypeUtils","createService","createSingleTypeService","createCollectionTypeService"],"mappings":";;;;AAMA,MAAMA,YAAe,GAAA,CACnBC,WAC2CC,GAAAA,YAAAA,CAAiBF,YAAY,CAACC,WAAAA,CAAAA;AAU3E,SAASE,aAAAA,CAAc,EACrBF,WAAW,EAGZ,EAAA;AACC,IAAA,IAAID,aAAaC,WAAc,CAAA,EAAA;AAC7B,QAAA,OAAOG,uBAAwBH,CAAAA,WAAAA,CAAAA;AACjC;AAEA,IAAA,OAAOI,2BAA4BJ,CAAAA,WAAAA,CAAAA;AACrC;;;;"}

View File

@@ -0,0 +1,30 @@
import { pagination } from '@strapi/utils';
interface BasePaginationParams {
withCount?: boolean | 't' | '1' | 'true' | 'f' | '0' | 'false' | 0 | 1;
}
type PagedPagination = BasePaginationParams & {
page?: number;
pageSize?: number;
};
type OffsetPagination = BasePaginationParams & {
start?: number;
limit?: number;
};
export type PaginationParams = PagedPagination | OffsetPagination;
type PaginationInfo = {
page: number;
pageSize: number;
} | {
start: number;
limit: number;
};
declare const isPagedPagination: (pagination?: PaginationParams) => pagination is PagedPagination;
declare const shouldCount: (params: {
pagination?: PaginationParams;
}) => boolean;
declare const getPaginationInfo: (params: {
pagination?: PaginationParams;
}) => PaginationInfo;
declare const transformPaginationResponse: (paginationInfo: PaginationInfo, total: number | undefined, isPaged: boolean) => pagination.PagePatinationInformation | pagination.OffsetPaginationInformation;
export { isPagedPagination, shouldCount, getPaginationInfo, transformPaginationResponse };
//# sourceMappingURL=pagination.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../../src/core-api/service/pagination.ts"],"names":[],"mappings":"AAEA,OAAO,EAAU,UAAU,EAAE,MAAM,eAAe,CAAC;AAEnD,UAAU,oBAAoB;IAC5B,SAAS,CAAC,EAAE,OAAO,GAAG,GAAG,GAAG,GAAG,GAAG,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC;CACxE;AAED,KAAK,eAAe,GAAG,oBAAoB,GAAG;IAC5C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,KAAK,gBAAgB,GAAG,oBAAoB,GAAG;IAC7C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG,eAAe,GAAG,gBAAgB,CAAC;AAElE,KAAK,cAAc,GACf;IACE,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;CAClB,GACD;IACE,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAaN,QAAA,MAAM,iBAAiB,gBAAiB,gBAAgB,kCACmC,CAAC;AAE5F,QAAA,MAAM,WAAW,WAAY;IAAE,UAAU,CAAC,EAAE,gBAAgB,CAAA;CAAE,YA0B7D,CAAC;AAEF,QAAA,MAAM,iBAAiB,WAAY;IAAE,UAAU,CAAC,EAAE,gBAAgB,CAAA;CAAE,KAAG,cAStE,CAAC;AAEF,QAAA,MAAM,2BAA2B,mBACf,cAAc,SACvB,MAAM,GAAG,SAAS,WAChB,OAAO,kFAcjB,CAAC;AAEF,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,iBAAiB,EAAE,2BAA2B,EAAE,CAAC"}

View File

@@ -0,0 +1,78 @@
'use strict';
var fp = require('lodash/fp');
var strapiUtils = require('@strapi/utils');
/**
* Default limit values from config
*/ const getLimitConfigDefaults = ()=>({
defaultLimit: fp.toNumber(strapi.config.get('api.rest.defaultLimit', 25)),
maxLimit: fp.toNumber(strapi.config.get('api.rest.maxLimit')) || null
});
const isOffsetPagination = (pagination)=>fp.has('start', pagination) || fp.has('limit', pagination);
const isPagedPagination = (pagination)=>fp.has('page', pagination) || fp.has('pageSize', pagination) || !isOffsetPagination(pagination);
const shouldCount = (params)=>{
if (fp.has('pagination.withCount', params)) {
const withCount = params.pagination?.withCount;
if (typeof withCount === 'boolean') {
return withCount;
}
if (typeof withCount === 'undefined') {
return false;
}
if ([
'true',
't',
'1',
1
].includes(withCount)) {
return true;
}
if ([
'false',
'f',
'0',
0
].includes(withCount)) {
return false;
}
throw new strapiUtils.errors.ValidationError('Invalid withCount parameter. Expected "t","1","true","false","0","f"');
}
return Boolean(strapi.config.get('api.rest.withCount', true));
};
const getPaginationInfo = (params)=>{
const { defaultLimit, maxLimit } = getLimitConfigDefaults();
const { start, limit } = strapiUtils.pagination.withDefaultPagination(params.pagination || {}, {
defaults: {
offset: {
limit: defaultLimit
},
page: {
pageSize: defaultLimit
}
},
maxLimit: maxLimit || -1
});
return {
start,
limit
};
};
const transformPaginationResponse = (paginationInfo, total, isPaged)=>{
const transform = isPaged ? strapiUtils.pagination.transformPagedPaginationInfo : strapiUtils.pagination.transformOffsetPaginationInfo;
const paginationResponse = transform(paginationInfo, total);
if (fp.isNil(total)) {
// Ignore total and pageCount if `total` value is not available.
return fp.omit([
'total',
'pageCount'
], paginationResponse);
}
return paginationResponse;
};
exports.getPaginationInfo = getPaginationInfo;
exports.isPagedPagination = isPagedPagination;
exports.shouldCount = shouldCount;
exports.transformPaginationResponse = transformPaginationResponse;
//# sourceMappingURL=pagination.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,73 @@
import { has, isNil, omit, toNumber } from 'lodash/fp';
import { errors, pagination } from '@strapi/utils';
/**
* Default limit values from config
*/ const getLimitConfigDefaults = ()=>({
defaultLimit: toNumber(strapi.config.get('api.rest.defaultLimit', 25)),
maxLimit: toNumber(strapi.config.get('api.rest.maxLimit')) || null
});
const isOffsetPagination = (pagination)=>has('start', pagination) || has('limit', pagination);
const isPagedPagination = (pagination)=>has('page', pagination) || has('pageSize', pagination) || !isOffsetPagination(pagination);
const shouldCount = (params)=>{
if (has('pagination.withCount', params)) {
const withCount = params.pagination?.withCount;
if (typeof withCount === 'boolean') {
return withCount;
}
if (typeof withCount === 'undefined') {
return false;
}
if ([
'true',
't',
'1',
1
].includes(withCount)) {
return true;
}
if ([
'false',
'f',
'0',
0
].includes(withCount)) {
return false;
}
throw new errors.ValidationError('Invalid withCount parameter. Expected "t","1","true","false","0","f"');
}
return Boolean(strapi.config.get('api.rest.withCount', true));
};
const getPaginationInfo = (params)=>{
const { defaultLimit, maxLimit } = getLimitConfigDefaults();
const { start, limit } = pagination.withDefaultPagination(params.pagination || {}, {
defaults: {
offset: {
limit: defaultLimit
},
page: {
pageSize: defaultLimit
}
},
maxLimit: maxLimit || -1
});
return {
start,
limit
};
};
const transformPaginationResponse = (paginationInfo, total, isPaged)=>{
const transform = isPaged ? pagination.transformPagedPaginationInfo : pagination.transformOffsetPaginationInfo;
const paginationResponse = transform(paginationInfo, total);
if (isNil(total)) {
// Ignore total and pageCount if `total` value is not available.
return omit([
'total',
'pageCount'
], paginationResponse);
}
return paginationResponse;
};
export { getPaginationInfo, isPagedPagination, shouldCount, transformPaginationResponse };
//# sourceMappingURL=pagination.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
import type { Struct, Core } from '@strapi/types';
import { CoreService } from './core-service';
export declare class SingleTypeService extends CoreService implements Core.CoreAPI.Service.SingleType {
private contentType;
constructor(contentType: Struct.SingleTypeSchema);
getDocumentId(): Promise<string>;
find(params?: {}): Promise<import("@strapi/types/dist/modules/documents").AnyDocument | null>;
createOrUpdate(params?: {}): Promise<import("@strapi/types/dist/modules/documents").AnyDocument | null>;
delete(params?: {}): Promise<{
deletedEntries: number;
}>;
}
declare const createSingleTypeService: (contentType: Struct.SingleTypeSchema) => Core.CoreAPI.Service.SingleType;
export { createSingleTypeService };
//# sourceMappingURL=single-type.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"single-type.d.ts","sourceRoot":"","sources":["../../../src/core-api/service/single-type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,qBAAa,iBAAkB,SAAQ,WAAY,YAAW,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU;IAC3F,OAAO,CAAC,WAAW,CAA0B;gBAEjC,WAAW,EAAE,MAAM,CAAC,gBAAgB;IAM1C,aAAa;IASb,IAAI,CAAC,MAAM,KAAK;IAMhB,cAAc,CAAC,MAAM,KAAK;IAe1B,MAAM,CAAC,MAAM,KAAK;;;CAazB;AAED,QAAA,MAAM,uBAAuB,gBACd,OAAO,gBAAgB,KACnC,KAAK,OAAO,CAAC,OAAO,CAAC,UAEvB,CAAC;AAEF,OAAO,EAAE,uBAAuB,EAAE,CAAC"}

Some files were not shown because too many files have changed in this diff Show More