bởi Ellie

Strapi is a fully customizable, self-hosted headless CMS built on Node.js and TypeScript that auto-generates REST and GraphQL APIs from visual content models. Ideal for developers building content-driven applications across web, mobile, and IoT.
This block provides the Strapi Core Framework (packages/core/core), the runtime engine that boots a Strapi application, wires content types to auto-generated REST routes, dispatches requests through controllers and services, and manages the application lifecycle. It targets backend engineers embedding a headless CMS engine into a Node.js/TypeScript project or extending Strapi's internals.
src/Strapi.ts - Main Strapi class and StrapiOptions type; the application instancesrc/index.ts - Public entry point exporting createStrapi, compileStrapi, and factoriessrc/compile.ts - Pre-boot compilation step (compileStrapi)src/constants.ts - Shared constants used across the frameworksrc/container.ts - IoC container powering service/provider resolutionsrc/factories.ts - Factory helpers for controllers, services, policies, and middlewaressrc/configuration/ - Config loading, URL resolution, directory resolution, and env wiringsrc/core-api/controller/ - Auto-generated controller logic for single-type and collection-type contentsrc/core-api/routes/ - Route builders and Zod-based query/body validators per content typesrc/core-api/service/ - Default CRUD service implementations and pagination helperssrc/domain/content-type/ - Content-type schema validation and domain helperssrc/domain/module/ - Module registration validationsrc/ee/ - Enterprise Edition license and feature gatingsrc/loaders/ - Plugin, API, component, middleware, and sanitizer loaderssrc/middlewares/ - Built-in Koa middlewares: body parser, compression, CORS, error handlersrc/migrations/ - Database migration utilitiessrc/providers/ - Provider abstractions (auth, upload, etc.)src/registries/ - Runtime registries for controllers, services, middlewares, policiessrc/services/ - Core services including request contextsrc/utils/ - Utility helpers (signal handling, directory resolution, update notifier)Khởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This TypeScript cli / script completed archive review with strong static results. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Quy trình avcp-2026-08-04.1 · SHA-256 162c1d83612a4294…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
npm install koa koa-router koa-bodyparser koa-compress koa-cors \
lodash lodash/fp dotenv qs zod \
@strapi/types @strapi/utils \
@strapi/database @strapi/admin \
typescript
No native modules, no pod install, no Expo prebuild required. This is a pure Node.js package. Requires Node.js >= 18.
Copy source: Place the contents of source/ at src/strapi-core/ inside your project root.
TypeScript paths — extend your tsconfig.json:
{
"compilerOptions": {
"paths": {
"@strapi/core/*": ["./src/strapi-core/src/*"]
},
"moduleResolution": "Bundler",
"target": "ES2020",
"module": "ESNext",
"esModuleInterop": true,
"strict": true
}
}
Environment variables — create a .env at your project root:
NODE_ENV=development
HOST=0.0.0.0
PORT=1337
ENV_PATH=.env # Loaded automatically by dotenv in configuration/index.ts
App directories — Strapi expects appDir (source root) and distDir (compiled output). Pass them via StrapiOptions:
import { createStrapi } from './src/strapi-core/src';
const strapi = createStrapi({ appDir: process.cwd(), distDir: './dist' });
package.json in your appDir must exist and be valid JSON (it is require()d during config loading).
Build step — if you use compileStrapi before boot, run the compile step first; it produces the distDir expected by the loader chain.
createStrapiexport const createStrapi = (
options?: Partial<StrapiOptions>
): Core.Strapi
The primary entry point. Instantiates the Strapi class, resolves working directories, registers signal handlers for graceful shutdown, and optionally starts an update notifier. Call this once at application startup. The returned instance is also assigned to global.strapi for legacy compatibility.
compileStrapiexport default function compileStrapi(): Promise<void>
Exported from src/compile.ts via src/index.ts. Runs the TypeScript compilation phase that produces the distDir consumed by loaders. Run this before createStrapi in CI or production startup scripts when you need a fresh build rather than relying on pre-compiled output.
factoriesexport namespace factories {
function createCoreController(uid: string, cfg?: object): Core.CoreAPI.Controller.Base;
function createCoreService(uid: string, cfg?: object): Core.CoreAPI.Service.Base;
function createCoreRouter(uid: string, cfg?: object): Core.Router;
}
Namespace of factory helpers for extending auto-generated CRUD controllers, services, and routers. Pass a content-type uid and an optional configuration object with overrides. Use these inside custom API files to retain default behavior while adding or overriding individual actions.
createController (core-api)function createController(opts: {
contentType: Struct.SingleTypeSchema | Struct.CollectionTypeSchema;
}): Core.CoreAPI.Controller.SingleType | Core.CoreAPI.Controller.CollectionType
Internal factory that builds a fully wired controller (with transformResponse, sanitizeOutput, sanitizeInput, sanitizeQuery) from a content-type schema. Dispatches to single-type or collection-type implementation automatically based on contentTypeUtils.isSingleType.
createRoutes (core-api)export const createRoutes = (opts: {
strapi: Core.Strapi;
contentType: Schema.ContentType;
}): Record<string, Partial<Core.Route>>
Generates the complete route map (find, findOne, create, update, delete) for a content type, including Zod validators for query parameters and request bodies. Returns a plain object keyed by route name; pass it to the Strapi router registration layer.
Minimal production-ready startup that compiles TypeScript output, creates the Strapi instance, and starts the HTTP server.
import { createStrapi, compileStrapi } from './src/strapi-core/src';
async function main() {
// Compile TS → JS before booting (skip if using pre-built dist)
await compileStrapi();
const strapi = createStrapi({
appDir: process.cwd(),
distDir: './dist',
autoReload: false,
serveAdminPanel: false,
});
await strapi.load();
await strapi.start();
console.log(`Strapi running on port ${strapi.config.get('server.port')}`);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
Override only the find action while keeping all other CRUD defaults from the factory.
// src/api/article/controllers/article.ts
import { factories } from './src/strapi-core/src';
export default factories.createCoreController('api::article.article', ({ strapi }) => ({
async find(ctx) {
// Inject a hard-coded locale filter before delegating
ctx.query.filters = { ...(ctx.query.filters as object), locale: 'en' };
const { data, meta } = await super.find(ctx);
return { data, meta, extended: true };
},
}));
Inspect or log the auto-generated route map for a content type at bootstrap time.
import { createStrapi } from './src/strapi-core/src';
import { createRoutes } from './src/strapi-core/src/core-api/routes';
const strapi = createStrapi({ appDir: process.cwd(), distDir: './dist' });
await strapi.load();
const articleContentType = strapi.contentType('api::article.article');
const routes = createRoutes({ strapi, contentType: articleContentType });
for (const [name, route] of Object.entries(routes)) {
console.log(`${name}: ${route.method} ${route.path} → ${route.handler}`);
}
// find: GET /articles → api::article.article.find
// findOne: GET /articles/:id → api::article.article.findOne
// ...
src/index.ts - Public barrel: exports createStrapi, compileStrapi, factories; augments Koa's query type with qs-parsed return.src/Strapi.ts - Core application class; lifecycle (load, start, stop, destroy), config, registries, and global strapi assignment.src/compile.ts - Thin wrapper that runs the TypeScript build pipeline before boot.src/constants.ts - Package-level constants (version strings, reserved namespaces).src/container.ts - Lightweight IoC container; register / resolve pattern used by loaders.src/factories.ts - createCoreController, createCoreService, createCoreRouter exposed as the factories namespace.src/configuration/ - loadConfiguration merges defaults, dotenv, and user config files; getDirs resolves appDir/distDir; getConfigUrls computes admin/server URLs.src/core-api/controller/ - createController dispatches to createSingleTypeController or createCollectionTypeController; transformResponse handles JSON:API v4 and source-map encoding.src/core-api/routes/ - createRoutes generates route descriptors; CoreContentTypeRouteValidator wraps Zod schemas for each query param and body shape.src/core-api/service/ - createCoreService base + collection-type and single-type CRUD implementations; pagination helpers for offset and cursor paging.src/domain/content-type/ - Schema validation (validator.ts) and helper functions for content-type domains.src/domain/module/ - Module registration schema and validation guards.src/ee/ - EE license parsing and feature-flag gating; no-op when license absent.src/loaders/ - Sequenced loaders for plugins, APIs, components, middlewares, policies, sanitizers, validators, and the user's src/index.ts.src/middlewares/ - Koa middleware factories: body parser, brotli/gzip compression, CORS, and JSON error formatter.src/migrations/ - Run-once migration helpers for database schema changes across Strapi versions.src/providers/ - Pluggable provider interfaces (auth, upload, email); resolved at boot via container.src/registries/ - In-memory maps for controllers, services, middlewares, policies, content types.src/services/ - request-context AsyncLocalStorage service (access current Koa ctx anywhere in the call stack).src/utils/ - resolveWorkingDirectories, destroyOnSignal, createUpdateNotifier.global.strapi is undefined in tests — call createStrapi() before importing any module that reads strapi.*; or mock global.strapi in your Jest/Vitest setup file.Cannot find module 'package.json' — loadConfiguration does require(path.resolve(appDir, 'package.json')); ensure appDir points to a directory containing a valid package.json.distDir not found at runtime — run compileStrapi() (or tsc) before calling strapi.load(); loaders read from distDir, not appDir.zod/v4; pin "zod": "^3.23" (which ships the /v4 sub-path) and avoid mixing with user@example.com direct installs.import/export; if your project is CJS, set "module": "CommonJS" in tsconfig or use a bundler (Rollup config is included at rollup.config.mjs).dotenv loaded twice — configuration/index.ts calls dotenv.config() at module load time; avoid calling dotenv.config() again in your own entry point or values may not override correctly.I have dropped the Strapi Core Framework source into `src/strapi-core/` in my
Node.js/TypeScript project. The USAGE.md file in that directory contains the
full integration guide, real exports, and working code snippets.
Upstream package: strapi (packages/core/core)
Please help me integrate it step by step:
1. Read USAGE.md and src/strapi-core/src/index.ts to understand the public API.
2. Update my tsconfig.json to add the path alias `@strapi/core/*` → `./src/strapi-core/src/*`.
3. Create a `src/server.ts` that calls `createStrapi` with my project's `appDir`
and `distDir`, calls `strapi.load()`, then `strapi.start()`.
4. Show me how to extend the auto-generated controller for my `api::article.article`
content type using `factories.createCoreController` without losing the default CRUD.
5. Show me how to use `createRoutes` to log all generated routes for a content type
after `strapi.load()`.
6. Point out any missing peer dependencies I need to install based on the imports
in the source files.
Do not invent exports. Only use symbols visible in USAGE.md and the source files.
This block is derived from the Strapi open-source project. Strapi is released under the MIT License — see source/LICENSE for the full text. The upstream npm package is @strapi/strapi. Full documentation is available at docs.strapi.io.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
Automation, Utilities & Developer Tools
Miễn phí