@dyrected/core 0.0.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,50 @@
1
+ Business Source License 1.1
2
+
3
+ Parameters
4
+
5
+ Licensor: Ajola Technologies Ltd
6
+ Licensed Work: Dyrected
7
+ Additional Use Grant: Commercial use is permitted as long as it is not used to provide a hosted or managed service that competes with Dyrected.
8
+ Change Date: 2030-05-11
9
+ Change License: Apache License 2.0
10
+
11
+ ---
12
+
13
+ Business Source License 1.1
14
+
15
+ License text copyright © 2024 MariaDB plc, All Rights Reserved.
16
+ “Business Source License” is a trademark of MariaDB plc.
17
+
18
+ ### Terms
19
+
20
+ The Licensor hereby grants you the right to copy, modify, create derivative works, redistribute, and make non-production use of the Licensed Work. The Licensor may make an Additional Use Grant, above, permitting limited production use.
21
+
22
+ Effective on the Change Date, or the fourth anniversary of the first publicly available distribution of a specific version of the Licensed Work under this License, whichever comes first, the Licensor hereby grants you rights under the terms of the Change License, and the rights granted in the paragraph above terminate.
23
+
24
+ If your use of the Licensed Work does not comply with the requirements currently in effect as described in this License, you must purchase a commercial license from the Licensor, its affiliated entities, or authorized resellers, or you must refrain from using the Licensed Work.
25
+
26
+ All copies of the original and modified Licensed Work, and derivative works of the Licensed Work, are subject to this License. This License applies separately for each version of the Licensed Work and the Change Date may vary for each version of the Licensed Work released by Licensor.
27
+
28
+ You must conspicuously display this License on each original or modified copy of the Licensed Work. If you receive the Licensed Work in original or modified form from a third party, the terms and conditions set forth in this License apply to your use of that work.
29
+
30
+ Any use of the Licensed Work in violation of this License will automatically terminate your rights under this License for the current and all other versions of the Licensed Work.
31
+
32
+ This License does not grant you any right in any trademark or logo of Licensor or its affiliates (provided that you may use a trademark or logo of Licensor as expressly required by this License).
33
+
34
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND TITLE.
35
+
36
+ MariaDB hereby grants you permission to use this License’s text to license your works, and to refer to it using the trademark “Business Source License”, as long as you comply with the Covenants of Licensor below.
37
+
38
+ ### Covenants of Licensor
39
+
40
+ In consideration of the right to use this License’s text and the “Business Source License” name and trademark, Licensor covenants to MariaDB, and to all other recipients of the licensed work to be provided by Licensor:
41
+
42
+ 1. To specify as the Change License the GPL Version 2.0 or any later version, or a license that is compatible with GPL Version 2.0 or a later version, where “compatible” means that software provided under the Change License can be included in a program with software provided under GPL Version 2.0 or a later version. Licensor may specify additional Change Licenses without limitation.
43
+
44
+ 2. To either: (a) specify an additional grant of rights to use that does not impose any additional restriction on the right granted in this License, as the Additional Use Grant; or (b) insert the text “None”.
45
+
46
+ 3. Not to modify this License in any other way.
47
+
48
+ ---
49
+
50
+ The Business Source License (this document, or the “License”) is not an Open Source license. However, the Licensed Work will eventually be made available under an Open Source License, as stated in this License.
package/README.md CHANGED
@@ -1,3 +1,37 @@
1
1
  # @dyrected/core
2
2
 
3
- This is the core package/app for the Dyrected ecosystem.
3
+ The heart of the Dyrected ecosystem. `@dyrected/core` is a lightweight, Hono-based headless CMS engine designed for high performance and developer flexibility.
4
+
5
+ ## Features
6
+
7
+ - **Code-First Schema**: Define your content structure in TypeScript.
8
+ - **Framework Agnostic**: Pluggable adapters for database, storage, and auth.
9
+ - **REST & OpenAPI**: Automatically generates a fully-typed API and Swagger documentation.
10
+ - **Embedded or Standalone**: Use it directly inside your Next.js/Nuxt app or as a separate service.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pnpm add @dyrected/core
16
+ ```
17
+
18
+ ## Basic Usage
19
+
20
+ ```ts
21
+ import { defineConfig } from '@dyrected/core';
22
+
23
+ export default defineConfig({
24
+ collections: [
25
+ {
26
+ slug: 'posts',
27
+ fields: [
28
+ { name: 'title', type: 'text', required: true },
29
+ { name: 'content', type: 'richText' }
30
+ ]
31
+ }
32
+ ],
33
+ // Add database and storage adapters
34
+ });
35
+ ```
36
+
37
+ For full documentation, visit [docs.dyrected.com](https://docs.dyrected.com).
@@ -0,0 +1,33 @@
1
+ // src/auth/token.ts
2
+ import { SignJWT, jwtVerify, decodeJwt } from "jose";
3
+ import { TextEncoder } from "util";
4
+ function getSecret() {
5
+ const secret = process.env.DYRECTED_JWT_SECRET || process.env.JWT_SECRET;
6
+ if (!secret) {
7
+ throw new Error(
8
+ "[dyrected/core] DYRECTED_JWT_SECRET is not set. Add it to your environment variables to enable auth collections."
9
+ );
10
+ }
11
+ return new TextEncoder().encode(secret);
12
+ }
13
+ var DEFAULT_EXPIRY = "7d";
14
+ async function signCollectionToken(payload, expiresIn = DEFAULT_EXPIRY) {
15
+ return new SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(getSecret());
16
+ }
17
+ async function verifyCollectionToken(token) {
18
+ const { payload } = await jwtVerify(token, getSecret());
19
+ return payload;
20
+ }
21
+ function decodeCollectionToken(token) {
22
+ try {
23
+ return decodeJwt(token);
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ export {
30
+ signCollectionToken,
31
+ verifyCollectionToken,
32
+ decodeCollectionToken
33
+ };
@@ -0,0 +1,66 @@
1
+ // src/utils/config.ts
2
+ var AUDIT_COLLECTION_SLUG = "__audit";
3
+ var SYSTEM_FIELDS = [
4
+ {
5
+ name: "createdAt",
6
+ type: "date",
7
+ label: "Created At",
8
+ admin: { readOnly: true, hidden: true }
9
+ },
10
+ {
11
+ name: "updatedAt",
12
+ type: "date",
13
+ label: "Updated At",
14
+ admin: { readOnly: true, hidden: true }
15
+ },
16
+ {
17
+ name: "createdBy",
18
+ type: "text",
19
+ label: "Created By",
20
+ admin: { readOnly: true, hidden: true }
21
+ },
22
+ {
23
+ name: "updatedBy",
24
+ type: "text",
25
+ label: "Updated By",
26
+ admin: { readOnly: true, hidden: true }
27
+ }
28
+ ];
29
+ var AUDIT_COLLECTION = {
30
+ slug: AUDIT_COLLECTION_SLUG,
31
+ labels: { singular: "Audit Log", plural: "Audit Logs" },
32
+ fields: [
33
+ { name: "collection", type: "text", label: "Collection", required: true },
34
+ { name: "documentId", type: "text", label: "Document ID" },
35
+ { name: "operation", type: "select", label: "Operation", options: ["create", "update", "delete"], required: true },
36
+ { name: "user", type: "text", label: "User ID" },
37
+ { name: "timestamp", type: "date", label: "Timestamp", required: true },
38
+ { name: "changes", type: "json", label: "Changes" }
39
+ ],
40
+ admin: { hidden: true }
41
+ };
42
+ function normalizeConfig(config) {
43
+ const needsAudit = config.collections.some((col) => col.audit);
44
+ const normalizedCollections = config.collections.map((col) => {
45
+ const existingFieldNames = new Set(col.fields.map((f) => f.name));
46
+ const fieldsToInject = SYSTEM_FIELDS.filter((f) => !existingFieldNames.has(f.name));
47
+ return {
48
+ ...col,
49
+ fields: [...col.fields, ...fieldsToInject]
50
+ };
51
+ });
52
+ const hasAuditCollection = normalizedCollections.some(
53
+ (col) => col.slug === AUDIT_COLLECTION_SLUG
54
+ );
55
+ return {
56
+ ...config,
57
+ collections: [
58
+ ...normalizedCollections,
59
+ ...needsAudit && !hasAuditCollection ? [AUDIT_COLLECTION] : []
60
+ ]
61
+ };
62
+ }
63
+
64
+ export {
65
+ normalizeConfig
66
+ };
@@ -0,0 +1,336 @@
1
+ type FieldType = "text" | "textarea" | "richText" | "number" | "boolean" | "date" | "select" | "multiSelect" | "relationship" | "array" | "object" | "json" | "blocks" | "image" | "email" | "url";
2
+ interface Block {
3
+ slug: string;
4
+ labels?: {
5
+ singular: string;
6
+ plural: string;
7
+ };
8
+ fields: Field[];
9
+ }
10
+ interface Field {
11
+ name: string;
12
+ type: FieldType;
13
+ label?: string;
14
+ required?: boolean;
15
+ unique?: boolean;
16
+ defaultValue?: any;
17
+ options?: string[] | {
18
+ label: string;
19
+ value: string;
20
+ }[];
21
+ relationTo?: string;
22
+ hasMany?: boolean;
23
+ fields?: Field[];
24
+ blocks?: Block[];
25
+ access?: {
26
+ read?: AccessFunction;
27
+ update?: AccessFunction;
28
+ };
29
+ hooks?: {
30
+ beforeChange?: FieldHook[];
31
+ afterRead?: FieldHook[];
32
+ };
33
+ admin?: {
34
+ placeholder?: string;
35
+ description?: string;
36
+ hidden?: boolean;
37
+ readOnly?: boolean;
38
+ condition?: ((data: any, siblingData: any) => boolean) | string;
39
+ layout?: "radio" | "select" | string;
40
+ direction?: "horizontal" | "vertical";
41
+ };
42
+ }
43
+ type AccessFunction = (args: {
44
+ user: any;
45
+ doc?: any;
46
+ data?: any;
47
+ req: any;
48
+ }) => boolean | object | Promise<boolean | object>;
49
+ type HookFunction = (args: {
50
+ data?: any;
51
+ doc?: any;
52
+ user?: any;
53
+ req?: any;
54
+ /** The operation that triggered this hook. */
55
+ operation?: 'create' | 'update' | 'delete';
56
+ }) => any | Promise<any>;
57
+ type FieldHook = (args: {
58
+ value: any;
59
+ originalDoc?: any;
60
+ data?: any;
61
+ user?: any;
62
+ }) => any | Promise<any>;
63
+ interface CollectionConfig {
64
+ slug: string;
65
+ siteId?: string;
66
+ shared?: boolean;
67
+ labels?: {
68
+ singular: string;
69
+ plural: string;
70
+ };
71
+ auth?: boolean;
72
+ upload?: boolean | UploadConfig;
73
+ fields: Field[];
74
+ timestamps?: boolean;
75
+ /** Enable full activity logging to the __audit collection for this collection. */
76
+ audit?: boolean;
77
+ access?: {
78
+ read?: AccessFunction;
79
+ create?: AccessFunction;
80
+ update?: AccessFunction;
81
+ delete?: AccessFunction;
82
+ };
83
+ hooks?: {
84
+ beforeRead?: HookFunction[];
85
+ afterRead?: HookFunction[];
86
+ beforeChange?: HookFunction[];
87
+ afterChange?: HookFunction[];
88
+ beforeDelete?: HookFunction[];
89
+ afterDelete?: HookFunction[];
90
+ };
91
+ admin?: {
92
+ useAsTitle?: string;
93
+ defaultColumns?: string[];
94
+ group?: string;
95
+ hidden?: boolean;
96
+ /**
97
+ * URL to open in the Live Preview pane.
98
+ * Accepts a static string or a function that receives the document and returns a URL.
99
+ */
100
+ previewUrl?: string | ((doc: any, opts: {
101
+ locale?: string;
102
+ }) => string | null);
103
+ /** Which mode to use for live preview. Defaults to 'postMessage'. */
104
+ previewMode?: 'postMessage' | 'token';
105
+ };
106
+ }
107
+ interface UploadConfig {
108
+ allowedMimeTypes?: string[];
109
+ maxFileSize?: number;
110
+ /** Local disk path where files are stored. Only used by LocalStorage adapter. */
111
+ staticDir?: string;
112
+ /** Public URL prefix for locally stored files. Only used by LocalStorage adapter. */
113
+ staticURL?: string;
114
+ /** Which imageSizes entry to use as the thumbnail in the Admin media grid. */
115
+ adminThumbnail?: string;
116
+ imageSizes?: {
117
+ name: string;
118
+ width?: number;
119
+ height?: number;
120
+ crop?: string;
121
+ /** sharp fit strategy: 'cover' | 'contain' | 'fill' | 'inside' | 'outside' */
122
+ fit?: string;
123
+ /** Never upscale images smaller than the target size. Default: true. */
124
+ withoutEnlargement?: boolean;
125
+ /** Additional sharp format options. */
126
+ formatOptions?: Record<string, any>;
127
+ }[];
128
+ }
129
+ interface GlobalConfig {
130
+ slug: string;
131
+ siteId?: string;
132
+ shared?: boolean;
133
+ label?: string;
134
+ fields: Field[];
135
+ access?: {
136
+ read?: AccessFunction;
137
+ update?: AccessFunction;
138
+ };
139
+ hooks?: {
140
+ beforeRead?: HookFunction[];
141
+ afterRead?: HookFunction[];
142
+ beforeChange?: HookFunction[];
143
+ afterChange?: HookFunction[];
144
+ };
145
+ admin?: {
146
+ group?: string;
147
+ hidden?: boolean;
148
+ };
149
+ }
150
+ interface PaginatedResult<T = any> {
151
+ docs: T[];
152
+ total: number;
153
+ limit: number;
154
+ page: number;
155
+ /** Total number of pages given the current limit. */
156
+ totalPages: number;
157
+ hasNextPage: boolean;
158
+ hasPrevPage: boolean;
159
+ }
160
+ interface DatabaseAdapter {
161
+ find(args: {
162
+ collection: string;
163
+ where?: any;
164
+ limit?: number;
165
+ page?: number;
166
+ sort?: string;
167
+ }): Promise<PaginatedResult>;
168
+ findOne(args: {
169
+ collection: string;
170
+ id: string;
171
+ }): Promise<any>;
172
+ create(args: {
173
+ collection: string;
174
+ data: any;
175
+ }): Promise<any>;
176
+ update(args: {
177
+ collection: string;
178
+ id: string;
179
+ data: any;
180
+ }): Promise<any>;
181
+ delete(args: {
182
+ collection: string;
183
+ id: string;
184
+ }): Promise<any>;
185
+ getGlobal(args: {
186
+ slug: string;
187
+ }): Promise<any>;
188
+ updateGlobal(args: {
189
+ slug: string;
190
+ data: any;
191
+ }): Promise<any>;
192
+ /**
193
+ * Sync the database schema with the provided collections and globals.
194
+ * Useful for creating tables on startup.
195
+ */
196
+ sync?(collections: CollectionConfig[], globals: GlobalConfig[]): Promise<void>;
197
+ /**
198
+ * Low-level raw query execution.
199
+ * Optional as not all adapters may support raw SQL/commands.
200
+ */
201
+ execute?(query: string, params?: any[]): Promise<any>;
202
+ }
203
+ interface FileData {
204
+ filename: string;
205
+ filesize?: number;
206
+ mimeType: string;
207
+ url: string;
208
+ width?: number;
209
+ height?: number;
210
+ focalPoint?: {
211
+ x: number;
212
+ y: number;
213
+ };
214
+ blurhash?: string;
215
+ type?: "upload" | "external";
216
+ provider?: string;
217
+ provider_metadata?: any;
218
+ [key: string]: any;
219
+ }
220
+ interface StorageAdapter {
221
+ upload(args: {
222
+ filename: string;
223
+ buffer: Uint8Array;
224
+ mimeType: string;
225
+ prefix?: string;
226
+ }): Promise<FileData>;
227
+ delete(args: {
228
+ filename: string;
229
+ }): Promise<void>;
230
+ getURL(args: {
231
+ filename: string;
232
+ }): string;
233
+ /** Retrieve file content for serving via API */
234
+ resolve?(args: {
235
+ filename: string;
236
+ }): Promise<{
237
+ buffer: Uint8Array;
238
+ mimeType: string;
239
+ } | null>;
240
+ }
241
+ /** Branding and metadata configuration for the Admin UI. */
242
+ interface AdminConfig {
243
+ branding?: {
244
+ /** URL or imported image for the full logo shown in the sidebar. */
245
+ logo?: string;
246
+ /** URL or imported image for the compact logo mark used in collapsed sidebar. */
247
+ logoMark?: string;
248
+ /** Primary accent colour as a CSS value (e.g. '#6366f1' or 'hsl(240 50% 60%)') */
249
+ primaryColor?: string;
250
+ /** URL for the browser tab favicon. */
251
+ favicon?: string;
252
+ };
253
+ meta?: {
254
+ /** Appended to every Admin page title. Default: '- Dyrected' */
255
+ titleSuffix?: string;
256
+ };
257
+ }
258
+ interface ImageService {
259
+ process(args: {
260
+ buffer: Uint8Array;
261
+ mimeType: string;
262
+ config?: CollectionConfig['upload'];
263
+ focalPoint?: {
264
+ x: number;
265
+ y: number;
266
+ };
267
+ }): Promise<{
268
+ metadata: {
269
+ width?: number;
270
+ height?: number;
271
+ blurhash?: string;
272
+ };
273
+ sizes?: Record<string, {
274
+ buffer: Uint8Array;
275
+ width: number;
276
+ height: number;
277
+ filename: string;
278
+ }>;
279
+ }>;
280
+ }
281
+ interface DyrectedConfig {
282
+ collections: CollectionConfig[];
283
+ globals: GlobalConfig[];
284
+ db?: DatabaseAdapter;
285
+ storage?: StorageAdapter;
286
+ image?: ImageService;
287
+ /** Admin UI branding and meta configuration. */
288
+ admin?: AdminConfig;
289
+ email?: {
290
+ from: string;
291
+ send: (args: {
292
+ to: string;
293
+ subject: string;
294
+ html: string;
295
+ }) => Promise<void>;
296
+ templates?: {
297
+ welcome?: (args: {
298
+ email: string;
299
+ }) => {
300
+ subject?: string;
301
+ html: string;
302
+ };
303
+ invite?: (args: {
304
+ token: string;
305
+ invitedByEmail?: string;
306
+ }) => {
307
+ subject?: string;
308
+ html: string;
309
+ };
310
+ resetPassword?: (args: {
311
+ token: string;
312
+ }) => {
313
+ subject?: string;
314
+ html: string;
315
+ };
316
+ passwordChanged?: (args: {
317
+ email: string;
318
+ }) => {
319
+ subject?: string;
320
+ html: string;
321
+ };
322
+ };
323
+ };
324
+ redis?: {
325
+ url: string;
326
+ };
327
+ cors?: {
328
+ origins: string[];
329
+ };
330
+ onSchemaFetch?: (siteId: string) => Promise<{
331
+ collections?: CollectionConfig[];
332
+ globals?: GlobalConfig[];
333
+ }>;
334
+ }
335
+
336
+ export type { AccessFunction as A, Block as B, CollectionConfig as C, DyrectedConfig as D, Field as F, GlobalConfig as G, HookFunction as H, ImageService as I, PaginatedResult as P, StorageAdapter as S, UploadConfig as U, AdminConfig as a, DatabaseAdapter as b, FieldHook as c, FieldType as d, FileData as e };