@dyrected/core 2.5.29 → 2.5.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -20,839 +20,302 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ LIFECYCLE_EVENTS_COLLECTION: () => LIFECYCLE_EVENTS_COLLECTION,
24
+ LIFECYCLE_EVENT_NAMES: () => LIFECYCLE_EVENT_NAMES,
25
+ WORKFLOW_HISTORY_COLLECTION: () => WORKFLOW_HISTORY_COLLECTION,
26
+ availableWorkflowTransitions: () => availableWorkflowTransitions,
27
+ canViewWorkflowDraft: () => canViewWorkflowDraft,
28
+ createLifecycleEvent: () => createLifecycleEvent,
29
+ createWorkflowDocument: () => createWorkflowDocument,
23
30
  defineCollection: () => defineCollection,
24
31
  defineConfig: () => defineConfig,
25
32
  defineGlobal: () => defineGlobal,
33
+ dispatchLifecycleEvent: () => dispatchLifecycleEvent,
34
+ dispatchPendingLifecycleEvents: () => dispatchPendingLifecycleEvents,
26
35
  executeFieldAfterRead: () => executeFieldAfterRead,
27
36
  executeFieldBeforeChange: () => executeFieldBeforeChange,
28
- generateAIPrompt: () => generateAIPrompt,
29
- generateFreshSetupPrompt: () => generateFreshSetupPrompt,
37
+ generateOpenApi: () => generateOpenApi,
38
+ initializeWorkflowDocument: () => initializeWorkflowDocument,
39
+ materializeWorkflowDocument: () => materializeWorkflowDocument,
30
40
  normalizeConfig: () => normalizeConfig,
31
41
  parseMongoWhere: () => parseMongoWhere,
32
42
  parseSort: () => parseSort,
33
43
  parseSqlWhere: () => parseSqlWhere,
34
- runCollectionHooks: () => runCollectionHooks
44
+ publishingWorkflow: () => publishingWorkflow,
45
+ runCollectionHooks: () => runCollectionHooks,
46
+ saveWorkflowDraft: () => saveWorkflowDraft,
47
+ transitionWorkflow: () => transitionWorkflow,
48
+ workflowCapabilities: () => workflowCapabilities
35
49
  });
36
50
  module.exports = __toCommonJS(index_exports);
37
51
 
38
- // src/utils/setup-prompt.ts
39
- function buildEnvironmentSection(frameworkLabel, isSelfHosted, config) {
40
- const credentialLines = isSelfHosted ? "" : `- Site ID : ${config.siteId}
41
- - API Key : ${config.apiKey}`;
42
- return `
43
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
44
- 1. ENVIRONMENT
45
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
46
- - Framework : ${frameworkLabel || "Detect it"}
47
- - Host Type : ${isSelfHosted ? "Self-Hosted (Local/Private Server)" : "Managed (Dyrected Cloud)"}
48
- - API Base : ${config.baseUrl || "http://localhost:3000"}
49
- ${credentialLines}`;
50
- }
51
- function buildDiagnosticSection() {
52
- return `
53
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
54
- 2. PHASE 0 \u2014 DISCOVERY
55
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
56
- Before writing any code, you MUST ask the user these questions.
57
- Write them exactly as shown below \u2014 in plain language with examples.
58
- Wait for the user to answer ALL of them before proceeding.
59
-
60
- \u2500\u2500\u2500 QUESTION 1 \u2500\u2500\u2500
61
- Ask:
62
- "Do you already have a website built, or are we starting fresh?
63
-
64
- \u2192 Already built: share your project or describe what pages you have
65
- (e.g. Home, About, Services, Contact)
66
- \u2192 Starting fresh: just say 'new site' and describe what the site is for"
67
-
68
- \u2500\u2500\u2500 QUESTION 2 \u2500\u2500\u2500
69
- Ask:
70
- "What kind of content will your client need to update regularly?
71
-
72
- Here are some examples to help you think:
73
- \u2192 Blog posts or news articles
74
- \u2192 Team member profiles (name, photo, bio)
75
- \u2192 Services or product descriptions
76
- \u2192 Testimonials or reviews
77
- \u2192 Event listings
78
- \u2192 FAQs
79
- \u2192 Homepage text (headline, hero image, call-to-action button)
80
-
81
- Just list the ones that apply. You can say things like:
82
- 'They need to update blog posts and team members'"
83
-
84
- \u2500\u2500\u2500 QUESTION 3 \u2500\u2500\u2500
85
- Ask:
86
- "Are there any pages on the site that should NEVER change \u2014 like a
87
- custom-coded page you want to leave exactly as it is?
88
-
89
- Example answer: 'The homepage has a custom animation, leave that alone.
90
- Everything else can be managed from the CMS.'
91
-
92
- If everything should be manageable, just say 'all pages'"
93
-
94
- \u2500\u2500\u2500 QUESTION 4 \u2500\u2500\u2500
95
- Ask:
96
- "What is this website for? Pick the closest description:
97
-
98
- A) A business or agency marketing site (show services, get leads)
99
- B) A blog or content site (publish articles regularly)
100
- C) A SaaS or product site (landing page, pricing, features)
101
- D) A portfolio (show work, case studies)
102
- E) An e-commerce or product catalogue
103
- F) Something else \u2014 describe it in one sentence"
104
-
105
- \u2500\u2500\u2500 IF EXISTING SITE \u2500\u2500\u2500
106
- If the user confirms they have an existing site, also:
107
- - Scan the codebase for all hardcoded text that should be CMS-managed
108
- - Identify repeated data structures that should become collections
109
- - Propose saving current content to a migration/ folder as .json files
110
- BEFORE touching any code
111
- - Report your findings to the user and get confirmation before proceeding
52
+ // src/types/index.ts
53
+ var LIFECYCLE_EVENT_NAMES = [
54
+ "revision.created",
55
+ "workflow.transitioned",
56
+ "entry.published",
57
+ "entry.unpublished"
58
+ ];
112
59
 
113
- Do NOT write any implementation code until all questions are answered
114
- and the user has confirmed the content plan.`;
115
- }
116
- function buildConstraintsSection() {
117
- return `
118
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
119
- 3. ARCHITECTURE & CONSTRAINTS
120
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
121
- - API ACCESS : Use client.collection(slug) as the only entry point.
122
- - ZERO-STATE : Always use initialData in all data fetches so the site
123
- renders correctly on first load and never throws during render.
124
- - MARKETING FREEDOM : Use a dynamic pages collection with a catch-all route
125
- so marketing can create and manage pages without a developer.
126
- - BLOCKS DESIGN : Use blocks for flexible page builders. Store as
127
- [{ blockType: 'slug', ...fields }] and switch on blockType
128
- in the frontend renderer.
129
- - DATA SAFETY : Never overwrite or drop existing content or pages.
130
- Preserve everything before making changes.
131
- - RESILIENCE : If Dyrected backend is unreachable, fall back to
132
- initialData and show stale content \u2014 never an error page.
133
- All relationship fields must handle null gracefully.
134
- Every block renderer must have a default fallback case.
135
- - AUTO-SEEDING : Use initialData: [...] in CollectionConfig or GlobalConfig
136
- to automatically populate the database on first run.
137
- This is great for demo content or default settings.`;
60
+ // src/workflows.ts
61
+ var WORKFLOW_HISTORY_COLLECTION = "__workflow_history";
62
+ var LIFECYCLE_EVENTS_COLLECTION = "__lifecycle_events";
63
+ function publishingWorkflow() {
64
+ return {
65
+ initialState: "draft",
66
+ draftState: "draft",
67
+ states: [
68
+ { name: "draft", label: "Draft", color: "neutral" },
69
+ { name: "in_review", label: "In review", color: "warning" },
70
+ { name: "published", label: "Published", color: "success", published: true }
71
+ ],
72
+ transitions: [
73
+ { name: "submit", label: "Submit for review", from: "draft", to: "in_review", requiredCapabilities: ["entry.submit"] },
74
+ { name: "publish", label: "Publish", from: "in_review", to: "published", requiredCapabilities: ["entry.publish"] },
75
+ { name: "reject", label: "Request changes", from: "in_review", to: "draft", requiredCapabilities: ["entry.publish"], requireComment: true },
76
+ { name: "unpublish", label: "Unpublish", from: "published", to: "draft", requiredCapabilities: ["entry.unpublish"], unpublish: true }
77
+ ],
78
+ roles: [
79
+ { role: "editor", capabilities: ["entry.edit", "entry.submit"] },
80
+ { role: "publisher", capabilities: ["entry.edit", "entry.submit", "entry.publish", "entry.unpublish"] },
81
+ { role: "admin", capabilities: ["entry.edit", "entry.submit", "entry.publish", "entry.unpublish"] }
82
+ ]
83
+ };
138
84
  }
139
- function buildSchemaRulesSection() {
140
- return `
141
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
142
- 4. SCHEMA EVOLUTION RULES
143
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
144
- - Never drop existing fields from the schema. Mark unused fields as deprecated only.
145
- - All new fields must have a defaultValue.
146
- - Use renameTo: 'oldName' to lazily migrate data when renaming fields.
147
- - Use promoted: true for fields that need high-performance SQL indexing or unique constraints.
148
- - For Cloud deployments, run npx @dyrected/cli sync:schema after every config change. Self-hosted deployments sync automatically on startup.
149
- `;
85
+ function publicMetadata(meta) {
86
+ const { availableTransitions: _availableTransitions, ...safe } = meta;
87
+ return safe;
150
88
  }
151
- function buildDoNotSection() {
152
- return `
153
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
154
- 5. DO NOT
155
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
156
- - Do NOT use client.collections \u2014 always use client.collection(slug).
157
- - Do NOT add custom auth middleware to the admin route.
158
- Dyrected handles admin authentication internally. Do not wrap,
159
- protect, or redirect the admin route yourself.
160
- - Do NOT use renderAdminUI in a Nuxt.js project. Use the DyrectedAdmin
161
- component which is auto-imported by @dyrected/nuxt.
162
- - Do NOT modify or overwrite existing pages without first preserving their data.
163
- - Do NOT drop, rename, or remove fields from an existing schema.
164
- - Do NOT integrate blog posts or testimonials unless explicitly requested.
165
- - Do NOT skip the diagnostic or discovery phase.`;
89
+ function workflowCapabilities(workflow, user) {
90
+ const capabilities = new Set(Array.isArray(user?.capabilities) ? user.capabilities : []);
91
+ const roles = Array.isArray(user?.roles) ? user.roles : [];
92
+ for (const mapping of workflow.roles ?? []) {
93
+ if (roles.includes(mapping.role)) mapping.capabilities.forEach((capability) => capabilities.add(capability));
94
+ }
95
+ return capabilities;
166
96
  }
167
- function buildTechnicalReferenceSection() {
168
- return `
169
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
170
- 6. TECHNICAL REFERENCE
171
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
172
- Use defineCollection, defineGlobal, and defineConfig from '@dyrected/core'.
173
-
174
- FIELD TYPES:
175
- - Primitive : text | textarea | richText | number | boolean | date | email | url | json | image
176
- - Choice : select | multiSelect (requires options: [{ label, value }])
177
- - Structural : array | object (requires nested fields: [...])
178
- - Relation : relationship (requires relationTo: '<slug>')
179
- - Media : relationship to an upload collection (e.g. 'media')
180
- - Blocks : blocks (requires blocks: [{ slug, labels, fields }])
181
-
182
- COLLECTION OPTIONS:
183
- - upload: true \u2014 media library with file upload support
184
- - auth: true \u2014 adds login/me endpoints; password field is auto-managed
185
- - audit: true \u2014 enables activity logging
186
- - admin.useAsTitle \u2014 field used as display title in admin list view
187
- - admin.group \u2014 groups collection under a sidebar heading
188
- - admin.hidden \u2014 hides collection from the sidebar (internal/system use)
189
-
190
- FIELD OPTIONS:
191
- - label \u2014 user-friendly display name (REQUIRED for all fields)
192
- - required \u2014 validation
193
- - unique \u2014 database-level uniqueness constraint
194
- - hasMany \u2014 allow multiple values (for relationship, select, image)
195
- - defaultValue \u2014 fallback value (required on all new fields added to existing schemas)
196
- - promoted \u2014 extracts field to a real SQL column for native indexing (SQL adapters only)
197
- - renameTo \u2014 name of the old field key to migrate data from (lazy migration)
198
- - admin.condition \u2014 Jexl expression string to conditionally show/hide field
199
- e.g. "status == \\"published\\""
200
- - admin.readOnly \u2014 display only, not editable
201
- - admin.hidden \u2014 hidden from editor UI entirely
202
- - hooks.beforeChange \u2014 [async (value) => newValue] transform before save
203
- - hooks.afterRead \u2014 [async (value) => newValue] transform after read
204
-
205
- GLOBALS:
206
- Use defineGlobal for single-instance documents like site settings or navigation.
207
- Access via client.global(slug).get() and client.global(slug).update(data).
208
-
209
- BLOCKS:
210
- Blocks are stored as [{ blockType: '<slug>', ...fields }].
211
- The admin renders a drag-and-drop block editor automatically.
212
- On the frontend, iterate the array and switch on block.blockType.
213
- Always include a default case in your switch for unknown block types.
214
-
215
- COMPLETE SCHEMA EXAMPLE:
216
- \`\`\`ts
217
- import { defineCollection, defineGlobal, defineConfig } from '@dyrected/core'
218
- import { SqliteAdapter } from '@dyrected/db-sqlite'
219
-
220
- const media = defineCollection({
221
- slug: 'media',
222
- upload: true,
223
- fields: [
224
- { name: 'alt', label: 'Alt Text', type: 'text' },
225
- ],
226
- })
227
-
228
- const pages = defineCollection({
229
- slug: 'pages',
230
- admin: { useAsTitle: 'title', group: 'Content' },
231
- fields: [
232
- { name: 'title', label: 'Title', type: 'text', required: true },
233
- { name: 'slug', label: 'URL Slug', type: 'text', required: true, unique: true },
234
- { name: 'seo', label: 'SEO Metadata', type: 'object', fields: [
235
- { name: 'metaTitle', label: 'Meta Title', type: 'text' },
236
- { name: 'metaDescription', label: 'Meta Description', type: 'textarea' },
237
- { name: 'ogImage', label: 'OG Image', type: 'relationship', relationTo: 'media' },
238
- ]},
239
- {
240
- name: 'layout',
241
- label: 'Page Layout',
242
- type: 'blocks',
243
- blocks: [
244
- {
245
- slug: 'hero',
246
- labels: { singular: 'Hero', plural: 'Heroes' },
247
- fields: [
248
- { name: 'heading', label: 'Heading', type: 'text', required: true },
249
- { name: 'subheading', label: 'Subheading', type: 'textarea' },
250
- { name: 'image', label: 'Hero Image', type: 'relationship', relationTo: 'media' },
251
- { name: 'ctaLabel', label: 'Button Label', type: 'text' },
252
- { name: 'ctaLink', label: 'Button Link', type: 'url' },
253
- ],
254
- },
255
- {
256
- slug: 'richContent',
257
- labels: { singular: 'Rich Content', plural: 'Rich Content Blocks' },
258
- fields: [
259
- { name: 'content', label: 'Content', type: 'richText', required: true },
260
- ],
261
- },
262
- {
263
- slug: 'callToAction',
264
- labels: { singular: 'Call to Action', plural: 'Calls to Action' },
265
- fields: [
266
- { name: 'heading', label: 'Heading', type: 'text', required: true },
267
- { name: 'description', label: 'Description', type: 'textarea' },
268
- { name: 'buttonLabel', label: 'Button Text', type: 'text' },
269
- { name: 'buttonLink', label: 'Button Link', type: 'url' },
270
- { name: 'theme', label: 'Theme', type: 'select', options: [
271
- { label: 'Primary', value: 'primary' },
272
- { label: 'Secondary', value: 'secondary' },
273
- { label: 'Dark', value: 'dark' },
274
- ]},
275
- ],
276
- },
277
- ],
278
- },
279
- ],
280
- })
281
-
282
- const settings = defineGlobal({
283
- slug: 'settings',
284
- label: 'Site Settings',
285
- fields: [
286
- { name: 'siteName', label: 'Site Name', type: 'text' },
287
- { name: 'tagline', label: 'Site Tagline', type: 'text' },
288
- { name: 'logo', label: 'Site Logo', type: 'relationship', relationTo: 'media' },
289
- { name: 'footerText', label: 'Footer Text', type: 'textarea' },
290
- ],
291
- })
292
-
293
- export default defineConfig({
294
- collections: [media, pages],
295
- globals: [settings],
296
- // Use SqliteAdapter for local, PostgresAdapter or MySqlAdapter for production
297
- db: new SqliteAdapter({ filename: './dyrected.db' }),
298
- })
299
- \`\`\``;
97
+ function canViewWorkflowDraft(workflow, user) {
98
+ if (!user) return false;
99
+ const capabilities = workflowCapabilities(workflow, user);
100
+ if (capabilities.has("entry.edit")) return true;
101
+ return workflow.transitions.some(
102
+ (transition) => (transition.requiredCapabilities ?? []).some((capability) => capabilities.has(capability))
103
+ );
300
104
  }
301
- function buildDeliverablesSection() {
302
- return `
303
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
304
- 7. REQUIRED DELIVERABLES \u2014 IN THIS ORDER
305
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
306
- Return your response in exactly this order. Do not combine steps. Do not skip steps.
307
-
308
- 1. Diagnostic findings (what exists, what needs to become CMS-managed)
309
- 2. dyrected.config.ts \u2014 complete file
310
- 3. Admin route file \u2014 complete file
311
- 4. Catch-all frontend page route \u2014 complete file
312
- 5. Block components \u2014 names and fields only
313
- 6. Migration/fallback strategy \u2014 numbered steps
314
- 7. Schema sync command
315
-
316
- API Reference: https://docs.dyrected.com
317
- If you are unsure about any syntax or property, refer to the documentation above.`;
105
+ function availableWorkflowTransitions(workflow, state, user) {
106
+ const capabilities = workflowCapabilities(workflow, user);
107
+ return workflow.transitions.filter((transition) => {
108
+ const from = Array.isArray(transition.from) ? transition.from : [transition.from];
109
+ return from.includes(state) && (transition.requiredCapabilities ?? []).every((item) => capabilities.has(item));
110
+ });
318
111
  }
319
- function buildFrameworkSection(activeTab, isSelfHosted, config) {
320
- const envPrefix = activeTab === "next" ? "NEXT_PUBLIC_" : activeTab === "nuxt" ? "NUXT_PUBLIC_" : "";
321
- const credentialEnvLines = isSelfHosted ? "" : `
322
- apiKey: process.env.${envPrefix}DYRECTED_API_KEY || '${config.apiKey}',
323
- siteId: process.env.${envPrefix}SITE_ID || '${config.siteId}',`;
324
- const baseUrlLine = `process.env.${envPrefix}DYRECTED_URL || '${config.baseUrl || "http://localhost:3000"}'`;
325
- const sections = {
326
- next: `
327
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
328
- 8. IMPLEMENTATION \u2014 Next.js
329
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
330
- 1. SDK Setup (lib/dyrected.ts):
331
- \`\`\`ts
332
- import { createClient } from '@dyrected/sdk'
333
-
334
- export const dyrected = createClient({
335
- baseUrl: ${baseUrlLine},${credentialEnvLines}
336
- })
337
- \`\`\`
338
-
339
- 2. Admin Route (app/cms/page.tsx):
340
- \`\`\`tsx
341
- import { DyrectedAdmin } from '@dyrected/next/admin'
342
-
343
- export default function AdminPage() {
344
- // DyrectedAdmin handles routing, auth, and CSS automatically.
345
- // Do NOT wrap this in custom auth middleware.
346
- return <DyrectedAdmin basename="/cms" />
112
+ function initializeWorkflowDocument(data, workflow) {
113
+ return {
114
+ ...data,
115
+ __workflow: { state: workflow.initialState, revision: 1 }
116
+ };
347
117
  }
348
- \`\`\`
349
-
350
- 3. Catch-all Page Route (app/[...slug]/page.tsx):
351
- \`\`\`tsx
352
- import { dyrected } from '@/lib/dyrected'
353
-
354
- export default async function CmsPage({ params }: { params: { slug: string[] } }) {
355
- const slug = params.slug?.join('/') || 'home'
356
- const page = await dyrected.collection('pages').findOne({ where: { slug: { equals: slug } } })
357
-
358
- if (!page) return <div>Page not found</div>
359
-
360
- return (
361
- <main>
362
- {page.layout?.map((block: any, i: number) => (
363
- <BlockRenderer key={i} block={block} />
364
- ))}
365
- </main>
366
- )
118
+ function materializeWorkflowDocument(doc, workflow, user) {
119
+ const meta = doc.__workflow;
120
+ if (!meta) return doc;
121
+ const { __published, __workflow, ...working } = doc;
122
+ if (!canViewWorkflowDraft(workflow, user)) {
123
+ if (!__published || typeof __published !== "object") return null;
124
+ return { id: doc.id, ...__published, _workflow: publicMetadata(meta) };
125
+ }
126
+ return {
127
+ ...working,
128
+ _workflow: {
129
+ ...meta,
130
+ availableTransitions: availableWorkflowTransitions(workflow, meta.state, user).map((item) => item.name)
131
+ }
132
+ };
367
133
  }
368
- \`\`\``,
369
- nuxt: `
370
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
371
- 8. IMPLEMENTATION \u2014 Nuxt.js
372
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
373
- 1. Nuxt.js Config (nuxt.config.ts):
374
- \`\`\`ts
375
- export default defineNuxtConfig({
376
- modules: ['@dyrected/nuxt'],
377
- dyrected: {
378
- baseUrl: process.env.${envPrefix}DYRECTED_URL || '${config.baseUrl || "http://localhost:3000"}',${isSelfHosted ? "" : `
379
- apiKey: process.env.${envPrefix}DYRECTED_API_KEY || '${config.apiKey}',
380
- siteId: process.env.${envPrefix}SITE_ID || '${config.siteId}',`}
381
- },
382
- })
383
- \`\`\`
384
-
385
- 2. Admin Route (pages/cms/index.vue):
386
- \`\`\`vue
387
- <script setup lang="ts">
388
- // DyrectedAdmin is auto-imported by @dyrected/nuxt.
389
- // Do NOT manually import it.
390
- // Do NOT use renderAdminUI here.
391
- // Do NOT add custom auth middleware \u2014 Dyrected handles authentication.
392
- definePageMeta({ layout: false })
393
- </script>
394
-
395
- <template>
396
- <ClientOnly>
397
- <DyrectedAdmin basename="/cms" />
398
- </ClientOnly>
399
- </template>
400
- \`\`\`
401
-
402
- 3. Catch-all Page Route (pages/[...slug].vue):
403
- \`\`\`vue
404
- <script setup lang="ts">
405
- const route = useRoute()
406
- const slug = computed(() =>
407
- Array.isArray(route.params.slug)
408
- ? route.params.slug.join('/')
409
- : route.params.slug || 'home'
410
- )
411
-
412
- const { data: page } = await useDyrected('pages').findOne({
413
- where: { slug: { equals: slug.value } },
414
- initialData: null,
415
- })
416
- </script>
417
-
418
- <template>
419
- <main v-if="page">
420
- <BlockRenderer
421
- v-for="(block, i) in page.layout"
422
- :key="i"
423
- :block="block"
424
- />
425
- </main>
426
- <div v-else>Page not found</div>
427
- </template>
428
- \`\`\``,
429
- react: `
430
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
431
- 8. IMPLEMENTATION \u2014 React
432
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
433
- 1. SDK Setup (lib/dyrected.ts):
434
- \`\`\`ts
435
- import { createClient } from '@dyrected/sdk'
436
-
437
- export const dyrected = createClient({
438
- baseUrl: '${config.baseUrl || "https://api.dyrected.cloud"}',${isSelfHosted ? "" : `
439
- apiKey: '${config.apiKey}',
440
- siteId: '${config.siteId}',`}
441
- })
442
- \`\`\`
443
-
444
- 2. Admin Route (pages/cms.tsx):
445
- \`\`\`tsx
446
- import { AdminUI } from '@dyrected/admin'
447
- import '@dyrected/admin/styles'
448
-
449
- export default function AdminPage() {
450
- return (
451
- <div style={{ height: '100vh' }}>
452
- <AdminUI
453
- baseUrl="${config.baseUrl || "https://api.dyrected.cloud"}"${isSelfHosted ? "" : `
454
- apiKey="${config.apiKey}"
455
- siteId="${config.siteId}"`}
456
- />
457
- </div>
458
- )
134
+ function eventId() {
135
+ return globalThis.crypto?.randomUUID?.() ?? `evt_${Date.now()}_${Math.random().toString(36).slice(2)}`;
459
136
  }
460
- \`\`\``,
461
- vue: `
462
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
463
- 8. IMPLEMENTATION \u2014 Vue
464
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
465
- 1. SDK Setup (lib/dyrected.ts):
466
- \`\`\`ts
467
- import { createClient } from '@dyrected/sdk'
468
-
469
- export const dyrected = createClient({
470
- baseUrl: '${config.baseUrl || "https://api.dyrected.cloud"}',${isSelfHosted ? "" : `
471
- apiKey: '${config.apiKey}',
472
- siteId: '${config.siteId}',`}
473
- })
474
- \`\`\`
475
-
476
- 2. Admin Route (pages/cms.vue):
477
- \`\`\`vue
478
- <template>
479
- <div ref="container" style="height: 100vh" />
480
- </template>
481
-
482
- <script setup>
483
- import { ref, onMounted, onUnmounted } from 'vue'
484
- import { renderAdminUI } from '@dyrected/admin'
485
- import '@dyrected/admin/styles'
486
-
487
- const container = ref(null)
488
- let cleanup: (() => void) | undefined
489
-
490
- onMounted(() => {
491
- cleanup = renderAdminUI(container.value, {
492
- baseUrl: '${config.baseUrl || "https://api.dyrected.cloud"}',${isSelfHosted ? "" : `
493
- apiKey: '${config.apiKey}',
494
- siteId: '${config.siteId}',`}
495
- })
496
- })
497
-
498
- onUnmounted(() => cleanup?.())
499
- </script>
500
- \`\`\``
137
+ function createLifecycleEvent(args) {
138
+ return {
139
+ id: eventId(),
140
+ name: args.name,
141
+ collection: args.collection,
142
+ documentId: args.documentId,
143
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
144
+ actorId: args.actorId,
145
+ payload: args.payload,
146
+ attempts: 0,
147
+ status: "pending"
501
148
  };
502
- return sections[activeTab] || sections.next;
503
149
  }
504
- function generateFreshSetupPrompt(activeTab, config) {
505
- const frameworkLabel = activeTab === "next" ? "Next.js" : activeTab === "nuxt" ? "Nuxt.js" : activeTab ? activeTab.charAt(0).toUpperCase() + activeTab.slice(1) : "the project's detected framework";
506
- const isSelfHosted = config.isSelfHosted === true || !config.apiKey && !config.siteId;
507
- const frameworkSetup = {
508
- nuxt: `
509
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
510
- 3. INSTALLATION STEPS \u2014 Run these in order
511
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
512
- Tell the user to follow these steps exactly. Explain each one in plain
513
- language before showing the command. Do not skip any step.
514
-
515
- STEP 1 \u2014 Initialize Dyrected
516
- Tell the user:
517
- "Run this command in your terminal inside your Nuxt.js project folder.
518
- It will set everything up for you automatically."
519
-
520
- \`\`\`bash
521
- npx @dyrected/cli init
522
- \`\`\`
523
-
524
- When it asks questions, tell the user to:
525
- - Choose: Nuxt.js 3
526
- - Choose: SQLite (easiest option, no extra setup needed)
527
-
528
- The CLI will automatically:
529
- - Install all required packages
530
- - Create a dyrected.config.ts file
531
- - Mount the Admin UI at pages/cms/index.vue
532
- - Generate a .env.example file
533
-
534
- STEP 2 \u2014 Register the module
535
- Tell the user to open nuxt.config.ts and add '@dyrected/nuxt' to modules:
536
-
537
- \`\`\`ts
538
- export default defineNuxtConfig({
539
- modules: ['@dyrected/nuxt'],
540
- })
541
- \`\`\`
542
-
543
- STEP 3 \u2014 Set up environment variables
544
- Tell the user:
545
- "Find the file called .env.example in your project.
546
- Make a copy of it and rename the copy to .env
547
- Then open .env and fill in the values."
548
-
549
- STEP 4 \u2014 Start the project
550
- \`\`\`bash
551
- pnpm dev
552
- \`\`\`
553
-
554
- STEP 5 \u2014 Open the dashboard
555
- Tell the user to open their browser and go to:
556
- http://localhost:3000/cms
557
-
558
- If they see the Dyrected admin dashboard, the installation worked.
559
- Tell them: "You are ready. Now let's set up your content."`,
560
- next: `
561
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
562
- 3. INSTALLATION STEPS \u2014 Run these in order
563
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
564
- Tell the user to follow these steps exactly. Explain each one in plain
565
- language before showing the command. Do not skip any step.
566
-
567
- STEP 1 \u2014 Initialize Dyrected
568
- Tell the user:
569
- "Run this command in your terminal inside your Next.js project folder."
570
-
571
- \`\`\`bash
572
- npx @dyrected/cli init
573
- \`\`\`
574
-
575
- When it asks questions, tell the user to:
576
- - Choose: Next.js
577
- - Choose: SQLite (easiest option, no extra setup needed)
578
-
579
- The CLI will automatically:
580
- - Install all required packages
581
- - Create a dyrected.config.ts file
582
- - Mount the Admin UI at app/cms/page.tsx
583
- - Generate a .env.example file
584
-
585
- STEP 2 \u2014 Set up environment variables
586
- Tell the user:
587
- "Find the file called .env.example in your project.
588
- Make a copy of it and rename the copy to .env.local
589
- Then open .env.local and fill in the values."
590
-
591
- STEP 3 \u2014 Start the project
592
- \`\`\`bash
593
- pnpm dev
594
- \`\`\`
595
-
596
- STEP 4 \u2014 Open the dashboard
597
- Tell the user to open their browser and go to:
598
- http://localhost:3000/cms
599
-
600
- If they see the Dyrected admin dashboard, the installation worked.
601
- Tell them: "You are ready. Now let's set up your content."`,
602
- react: `
603
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
604
- 3. INSTALLATION STEPS \u2014 Run these in order
605
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
606
- STEP 1 \u2014 Install the SDK and admin packages
607
- \`\`\`bash
608
- npm install @dyrected/sdk @dyrected/admin
609
- \`\`\`
610
-
611
- STEP 2 \u2014 Set up the client (lib/dyrected.ts):
612
- \`\`\`ts
613
- import { createClient } from '@dyrected/sdk'
614
-
615
- export const dyrected = createClient({
616
- baseUrl: '${config.baseUrl || "https://api.dyrected.cloud"}',${isSelfHosted ? "" : `
617
- apiKey: '${config.apiKey}',
618
- siteId: '${config.siteId}',`}
619
- })
620
- \`\`\`
621
-
622
- STEP 3 \u2014 Mount the Admin UI (pages/cms.tsx):
623
- \`\`\`tsx
624
- import { AdminUI } from '@dyrected/admin'
625
- import '@dyrected/admin/styles'
626
-
627
- export default function AdminPage() {
628
- return (
629
- <div style={{ height: '100vh' }}>
630
- <AdminUI
631
- baseUrl="${config.baseUrl || "https://api.dyrected.cloud"}"${isSelfHosted ? "" : `
632
- apiKey="${config.apiKey}"
633
- siteId="${config.siteId}"`}
634
- />
635
- </div>
636
- )
150
+ async function persistEvent(db, event) {
151
+ await db.create({ collection: LIFECYCLE_EVENTS_COLLECTION, data: event });
637
152
  }
638
- \`\`\``,
639
- vue: `
640
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
641
- 3. INSTALLATION STEPS \u2014 Run these in order
642
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
643
- STEP 1 \u2014 Install the SDK and admin packages
644
- \`\`\`bash
645
- npm install @dyrected/sdk @dyrected/admin
646
- \`\`\`
647
-
648
- STEP 2 \u2014 Set up the client (lib/dyrected.ts):
649
- \`\`\`ts
650
- import { createClient } from '@dyrected/sdk'
651
-
652
- export const dyrected = createClient({
653
- baseUrl: '${config.baseUrl || "https://api.dyrected.cloud"}',${isSelfHosted ? "" : `
654
- apiKey: '${config.apiKey}',
655
- siteId: '${config.siteId}',`}
656
- })
657
- \`\`\`
658
-
659
- STEP 3 \u2014 Mount the Admin UI (pages/cms.vue):
660
- \`\`\`vue
661
- <template>
662
- <div ref="container" style="height: 100vh" />
663
- </template>
664
-
665
- <script setup>
666
- import { ref, onMounted, onUnmounted } from 'vue'
667
- import { renderAdminUI } from '@dyrected/admin'
668
- import '@dyrected/admin/styles'
669
-
670
- const container = ref(null)
671
- let cleanup
672
-
673
- onMounted(() => {
674
- cleanup = renderAdminUI(container.value, {
675
- baseUrl: '${config.baseUrl || "https://api.dyrected.cloud"}',${isSelfHosted ? "" : `
676
- apiKey: '${config.apiKey}',
677
- siteId: '${config.siteId}',`}
678
- })
679
- })
680
-
681
- onUnmounted(() => cleanup?.())
682
- </script>
683
- \`\`\``
684
- };
685
- return [
686
- `You are a friendly technical assistant helping someone set up Dyrected CMS for the very first time in a ${frameworkLabel} project. They have NOT installed anything yet.
687
-
688
- Your job is to:
689
- 1. Understand who you are talking to before giving any instructions
690
- 2. Ask simple questions about their project and content needs
691
- 3. Walk them through setup in a way that matches their technical level
692
- 4. Confirm each step worked before moving to the next
693
- 5. Help them design their content so their client can manage it
694
-
695
- Speak in plain language at all times. Never assume technical knowledge.
696
- Never show more than one step at a time.
697
- Never mention the terminal, command line, or any commands until you have
698
- confirmed the user is comfortable running them.`,
699
- `
700
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
701
- 1. ENVIRONMENT
702
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
703
- - Framework : ${frameworkLabel}
704
- - Host Type : ${isSelfHosted ? "Self-Hosted" : "Dyrected Cloud"}
705
- - API Base : ${config.baseUrl || "http://localhost:3000"}
706
- ${isSelfHosted ? "" : `- Site ID : ${config.siteId}
707
- - API Key : ${config.apiKey}`}`.trim(),
708
- `
709
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
710
- 2. PHASE 0 \u2014 UNDERSTAND THE USER FIRST
711
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
712
- Ask these questions one at a time. Wait for each answer before asking the next.
713
- Never ask more than one question at a time.
714
-
715
- \u2500\u2500\u2500 QUESTION 1 \u2014 TECH LEVEL \u2500\u2500\u2500
716
- This is the most important question. Ask it first.
717
-
718
- Ask exactly this:
719
- "Before we dive in \u2014 how would you describe yourself?
720
-
721
- A) I write code myself (I'm comfortable with the terminal and editing files)
722
- B) I use tools like Lovable, Bolt, or v0 to build with AI \u2014 I don't write much code myself
723
- C) I'm a designer or project manager \u2014 someone else usually handles the technical stuff
724
- D) Something else \u2014 just describe how you work"
725
-
726
- Use their answer to decide how to guide them for the rest of the setup:
727
- - If A \u2192 they are TECHNICAL. You may show terminal commands and code directly.
728
- - If B \u2192 they are SEMI-TECHNICAL. Explain what each step does before showing
729
- any code or commands. Ask before running anything in the terminal.
730
- For Lovable users specifically: guide them to use the built-in
731
- terminal or ask them to paste code into the right file in their editor.
732
- - If C \u2192 they are NON-TECHNICAL. Do not show terminal commands at all.
733
- Generate all the code and config for them. Walk them through
734
- copy-pasting into specific files by name. If a terminal step is
735
- unavoidable, warn them first and offer to write the exact command
736
- with a clear explanation of what it does and where to run it.
737
- - If D \u2192 ask one follow-up question to understand their workflow before
738
- deciding which path above fits best.
739
-
740
- \u2500\u2500\u2500 QUESTION 2 \u2014 PROJECT STATUS \u2500\u2500\u2500
741
- Ask after Q1 is answered:
742
-
743
- "Do you already have a ${frameworkLabel} project open,
744
- or are we starting from scratch?
745
-
746
- \u2192 Already have a project: tell me what the site is about or
747
- share the folder name
748
- \u2192 Starting fresh: just say 'new project' and I will help you
749
- create one first"
750
-
751
- \u2500\u2500\u2500 QUESTION 3 \u2014 SITE PURPOSE \u2500\u2500\u2500
752
- Ask after Q2 is answered:
753
-
754
- "What kind of website is this?
755
-
756
- A) A business or agency site (show services, get enquiries)
757
- B) A blog or news site (publish articles regularly)
758
- C) A SaaS or product landing page (features, pricing, sign up)
759
- D) A portfolio (show work and past projects)
760
- E) Something else \u2014 describe it in one sentence"
761
-
762
- \u2500\u2500\u2500 QUESTION 4 \u2014 CONTENT NEEDS \u2500\u2500\u2500
763
- Ask after Q3 is answered:
764
-
765
- "What will your client need to update themselves \u2014 without calling you?
766
-
767
- Some examples to help you think:
768
- \u2192 Blog posts or news articles
769
- \u2192 Team member profiles (name, photo, bio)
770
- \u2192 Services or product descriptions
771
- \u2192 Homepage text (headline, buttons, images)
772
- \u2192 Testimonials or reviews
773
- \u2192 FAQs
774
- \u2192 Event listings or announcements
775
-
776
- Just list the ones that apply. Or say 'not sure yet'
777
- and we will figure it out together."
778
-
779
- \u2500\u2500\u2500 AFTER ALL QUESTIONS \u2500\u2500\u2500
780
- Once all four questions are answered:
781
- 1. Summarise what you understood in plain English
782
- 2. Ask the user to confirm before touching any code
783
- 3. Then move to the installation steps using the correct path
784
- for their tech level from Question 1`,
785
- frameworkSetup[activeTab] || frameworkSetup.nuxt,
786
- `
787
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
788
- 4. AFTER INSTALLATION \u2014 CONTENT SETUP
789
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
790
- Once the dashboard is confirmed working, help the user design their
791
- content model in dyrected.config.ts based on what they told you in
792
- Phase 0.
793
-
794
- RULES for this phase:
795
- - Use defineCollection and defineConfig from '@dyrected/core'
796
- - Use client.collection(slug) only \u2014 never client.collections
797
- - Always use initialData in all data fetches
798
- - Use a catch-all pages collection for marketing-managed pages
799
- - Use blocks for flexible page layouts
800
- - Use type: 'relationship', relationTo: 'collectionSlug' for relations
801
- - Never throw during render \u2014 fall back to initialData on errors
802
- - All relationship fields must handle null gracefully
803
-
804
- CONTENT SETUP DELIVERABLES \u2014 in this order:
805
- 1. dyrected.config.ts \u2014 complete file based on their answers
806
- 2. Catch-all page route for CMS-managed pages
807
- 3. Block components list (names and fields only)
808
- 4. One example fetch showing how to load content on a page
809
-
810
- After delivering the config, tell the user to sync their schema.
811
- For TECHNICAL users show the command directly:
812
- \`\`\`bash
813
- npx @dyrected/cli sync:schema
814
- \`\`\`
815
- For SEMI-TECHNICAL or NON-TECHNICAL users explain it first:
816
- "This next step tells Dyrected to read your content setup file
817
- and prepare the database. Here is the command to run:" then show it.
818
-
819
- Then ask: "Do you want me to help you connect this content to your
820
- frontend pages now?"
821
-
822
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
823
- DO NOT
824
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
825
- - Do NOT show terminal commands before confirming the user's tech level
826
- - Do NOT assume the user knows what a terminal, CLI, or package manager is
827
- - Do NOT show all steps at once \u2014 one step at a time always
828
- - Do NOT use client.collections \u2014 use client.collection(slug)
829
- - Do NOT add custom auth middleware to the admin route
830
- - Do NOT use renderAdminUI in a Nuxt.js project
831
- - Do NOT skip the confirmation after each installation step
832
- - Do NOT use jargon without explaining it in plain English first
833
- - Do NOT assume the installation worked \u2014 ask the user to confirm
834
-
835
- API Reference: https://docs.dyrected.com
836
- If you are unsure about any syntax, refer to the official documentation above.`
837
- ].join("\n");
153
+ async function dispatchLifecycleEvent(config, event) {
154
+ const db = config.db;
155
+ if (!db || !config.events?.handlers.length) return;
156
+ const maxAttempts = config.events.maxAttempts ?? 8;
157
+ const retryDelayMs = config.events.retryDelayMs ?? 1e3;
158
+ const attempts = event.attempts + 1;
159
+ try {
160
+ await db.update({ collection: LIFECYCLE_EVENTS_COLLECTION, id: event.id, data: { status: "processing", attempts } });
161
+ for (const handler of config.events.handlers) await handler({ ...event, status: "processing", attempts });
162
+ await db.update({
163
+ collection: LIFECYCLE_EVENTS_COLLECTION,
164
+ id: event.id,
165
+ data: { status: "delivered", attempts, deliveredAt: (/* @__PURE__ */ new Date()).toISOString(), lastError: null }
166
+ });
167
+ } catch (error) {
168
+ const exhausted = attempts >= maxAttempts;
169
+ await db.update({
170
+ collection: LIFECYCLE_EVENTS_COLLECTION,
171
+ id: event.id,
172
+ data: {
173
+ status: "failed",
174
+ attempts,
175
+ lastError: error instanceof Error ? error.message : String(error),
176
+ nextAttemptAt: exhausted ? null : new Date(Date.now() + retryDelayMs * 2 ** (attempts - 1)).toISOString()
177
+ }
178
+ });
179
+ }
838
180
  }
839
- function generateAIPrompt(activeTab, config) {
840
- const frameworkLabel = activeTab === "next" ? "Next.js" : activeTab === "nuxt" ? "Nuxt.js" : activeTab ? activeTab.charAt(0).toUpperCase() + activeTab.slice(1) : "the project's detected framework";
841
- const isSelfHosted = config.isSelfHosted === true || !config.apiKey && !config.siteId;
842
- const existingSite = config.existingSite ?? false;
843
- const missionText = existingSite ? `You are a Senior Content Architect. Your mission is to integrate Dyrected CMS into an EXISTING ${frameworkLabel} project. Your absolute priority is DATA PRESERVATION and MIGRATION of existing hardcoded content into a flexible, blocks-based schema that empowers marketing teams to move independently.` : `You are a Senior Content Architect. Your mission is to integrate Dyrected CMS into a NEW ${frameworkLabel} project. Your priority is DATA PRESERVATION and creating a CMS that empowers marketing teams to move independently without raising tickets to engineering.`;
844
- const sections = [
845
- missionText,
846
- buildEnvironmentSection(frameworkLabel, isSelfHosted, config),
847
- buildDiagnosticSection(),
848
- buildConstraintsSection(),
849
- buildSchemaRulesSection(),
850
- buildDoNotSection(),
851
- buildTechnicalReferenceSection(),
852
- buildDeliverablesSection(),
853
- buildFrameworkSection(activeTab, isSelfHosted, config)
854
- ];
855
- return sections.join("\n");
181
+ async function dispatchPendingLifecycleEvents(config, limit = 50) {
182
+ if (!config.db || !config.events?.handlers.length) return 0;
183
+ const maxAttempts = config.events.maxAttempts ?? 8;
184
+ const result = await config.db.find({
185
+ collection: LIFECYCLE_EVENTS_COLLECTION,
186
+ where: { status: { in: ["pending", "failed"] } },
187
+ sort: "occurredAt",
188
+ limit
189
+ });
190
+ const now = Date.now();
191
+ const due = result.docs.filter(
192
+ (doc) => Number(doc.attempts ?? 0) < maxAttempts && (!doc.nextAttemptAt || new Date(doc.nextAttemptAt).getTime() <= now)
193
+ );
194
+ for (const event of due) await dispatchLifecycleEvent(config, event);
195
+ return due.length;
196
+ }
197
+ async function saveWorkflowDraft(args) {
198
+ const { config, collection, id, originalDoc, data, user } = args;
199
+ const db = config.db;
200
+ const workflow = collection.workflow;
201
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
202
+ const previous = originalDoc.__workflow;
203
+ const event = createLifecycleEvent({
204
+ name: "revision.created",
205
+ collection: collection.slug,
206
+ documentId: id,
207
+ actorId: user?.sub,
208
+ payload: { revision: previous.revision + 1, previousRevision: previous.revision }
209
+ });
210
+ const doc = await db.transaction(async (tx) => {
211
+ const nextMeta = {
212
+ ...previous,
213
+ state: originalDoc.__published ? workflow.draftState ?? workflow.initialState : previous.state,
214
+ revision: previous.revision + 1
215
+ };
216
+ const updated = await tx.update({ collection: collection.slug, id, data: { ...data, __workflow: nextMeta } });
217
+ await persistEvent(tx, event);
218
+ return updated;
219
+ });
220
+ void dispatchLifecycleEvent(config, event);
221
+ return { doc, event };
222
+ }
223
+ async function createWorkflowDocument(args) {
224
+ const { config, collection, data, user } = args;
225
+ const db = config.db;
226
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
227
+ let event;
228
+ const doc = await db.transaction(async (tx) => {
229
+ const created = await tx.create({ collection: collection.slug, data });
230
+ event = createLifecycleEvent({
231
+ name: "revision.created",
232
+ collection: collection.slug,
233
+ documentId: created.id,
234
+ actorId: user?.sub,
235
+ payload: { revision: 1, previousRevision: null }
236
+ });
237
+ await persistEvent(tx, event);
238
+ return created;
239
+ });
240
+ void dispatchLifecycleEvent(config, event);
241
+ return { doc, event };
242
+ }
243
+ async function transitionWorkflow(args) {
244
+ const { config, collection, id, transitionName, expectedRevision, comment, user, req } = args;
245
+ const db = config.db;
246
+ const workflow = collection.workflow;
247
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
248
+ const original = await db.findOne({ collection: collection.slug, id });
249
+ if (!original) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
250
+ const meta = original.__workflow;
251
+ if (!meta) throw Object.assign(new Error("Entry has no workflow metadata"), { statusCode: 409 });
252
+ if (expectedRevision !== void 0 && expectedRevision !== meta.revision) {
253
+ throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), { statusCode: 409 });
254
+ }
255
+ const transition = workflow.transitions.find((item) => item.name === transitionName);
256
+ const fromStates = transition ? Array.isArray(transition.from) ? transition.from : [transition.from] : [];
257
+ if (!transition || !fromStates.includes(meta.state)) {
258
+ throw Object.assign(new Error(`Transition "${transitionName}" is not valid from "${meta.state}".`), { statusCode: 409 });
259
+ }
260
+ if (!availableWorkflowTransitions(workflow, meta.state, user).some((item) => item.name === transition.name)) {
261
+ throw Object.assign(new Error(`You do not have permission to perform "${transition.label}".`), { statusCode: 403 });
262
+ }
263
+ if (transition.requireComment && !comment?.trim()) {
264
+ throw Object.assign(new Error(`A comment is required for "${transition.label}".`), { statusCode: 400 });
265
+ }
266
+ const hookContext = { transition, from: meta.state, to: transition.to, doc: original, user, comment, req, db };
267
+ for (const hook of workflow.hooks?.beforeTransition ?? []) await hook(hookContext);
268
+ const events = [createLifecycleEvent({
269
+ name: "workflow.transitioned",
270
+ collection: collection.slug,
271
+ documentId: id,
272
+ actorId: user?.sub,
273
+ payload: { transition: transition.name, from: meta.state, to: transition.to, revision: meta.revision, comment }
274
+ })];
275
+ const targetState = workflow.states.find((state) => state.name === transition.to);
276
+ if (targetState.published) {
277
+ events.push(createLifecycleEvent({ name: "entry.published", collection: collection.slug, documentId: id, actorId: user?.sub, payload: { revision: meta.revision } }));
278
+ } else if (transition.unpublish) {
279
+ events.push(createLifecycleEvent({ name: "entry.unpublished", collection: collection.slug, documentId: id, actorId: user?.sub, payload: { revision: meta.publishedRevision } }));
280
+ }
281
+ const updated = await db.transaction(async (tx) => {
282
+ const locked = await tx.findOne({ collection: collection.slug, id });
283
+ if (!locked) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
284
+ const lockedMeta = locked.__workflow;
285
+ if (lockedMeta.revision !== meta.revision || lockedMeta.state !== meta.state || expectedRevision !== void 0 && lockedMeta.revision !== expectedRevision) {
286
+ throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), { statusCode: 409 });
287
+ }
288
+ const now = (/* @__PURE__ */ new Date()).toISOString();
289
+ const { __published: _published, __workflow: _workflow, id: _id, ...working } = locked;
290
+ const nextMeta = {
291
+ ...lockedMeta,
292
+ state: transition.to,
293
+ ...targetState.published ? { publishedRevision: lockedMeta.revision, publishedAt: now, publishedBy: user?.sub } : {},
294
+ ...transition.unpublish ? { publishedRevision: void 0, publishedAt: void 0, publishedBy: void 0 } : {}
295
+ };
296
+ const data = { __workflow: nextMeta };
297
+ if (targetState.published) data.__published = working;
298
+ if (transition.unpublish) data.__published = null;
299
+ const next = await tx.update({ collection: collection.slug, id, data });
300
+ await tx.create({
301
+ collection: WORKFLOW_HISTORY_COLLECTION,
302
+ data: { collection: collection.slug, documentId: id, transition: transition.name, from: lockedMeta.state, to: transition.to, revision: lockedMeta.revision, comment: comment ?? null, actorId: user?.sub ?? null, createdAt: now }
303
+ });
304
+ for (const event of events) await persistEvent(tx, event);
305
+ if (collection.audit) {
306
+ await tx.create({ collection: "__audit", data: { collection: collection.slug, documentId: id, operation: "workflow.transition", user: user?.sub ?? null, timestamp: now, changes: JSON.stringify({ transition: transition.name, from: lockedMeta.state, to: transition.to, revision: lockedMeta.revision }) } });
307
+ }
308
+ return next;
309
+ });
310
+ for (const event of events) void dispatchLifecycleEvent(config, event);
311
+ for (const hook of workflow.hooks?.afterTransition ?? []) {
312
+ try {
313
+ await hook({ ...hookContext, doc: updated, event: events[0] });
314
+ } catch (error) {
315
+ console.error("[dyrected/workflow] afterTransition hook failed:", error);
316
+ }
317
+ }
318
+ return updated;
856
319
  }
857
320
 
858
321
  // src/utils/config.ts
@@ -896,10 +359,47 @@ var AUDIT_COLLECTION = {
896
359
  ],
897
360
  admin: { hidden: true }
898
361
  };
362
+ var WORKFLOW_HISTORY_COLLECTION_CONFIG = {
363
+ slug: WORKFLOW_HISTORY_COLLECTION,
364
+ labels: { singular: "Workflow transition", plural: "Workflow transitions" },
365
+ fields: [
366
+ { name: "collection", type: "text", required: true },
367
+ { name: "documentId", type: "text", required: true },
368
+ { name: "transition", type: "text", required: true },
369
+ { name: "from", type: "text", required: true },
370
+ { name: "to", type: "text", required: true },
371
+ { name: "revision", type: "number", required: true },
372
+ { name: "comment", type: "textarea" },
373
+ { name: "actorId", type: "text" },
374
+ { name: "createdAt", type: "date", required: true }
375
+ ],
376
+ access: { read: ({ user }) => !!user, create: () => false, update: () => false, delete: () => false },
377
+ admin: { hidden: true }
378
+ };
379
+ var LIFECYCLE_EVENTS_COLLECTION_CONFIG = {
380
+ slug: LIFECYCLE_EVENTS_COLLECTION,
381
+ labels: { singular: "Lifecycle event", plural: "Lifecycle events" },
382
+ fields: [
383
+ { name: "name", type: "text", required: true },
384
+ { name: "collection", type: "text", required: true },
385
+ { name: "documentId", type: "text", required: true },
386
+ { name: "occurredAt", type: "date", required: true },
387
+ { name: "actorId", type: "text" },
388
+ { name: "payload", type: "json", required: true },
389
+ { name: "attempts", type: "number", required: true },
390
+ { name: "status", type: "select", options: ["pending", "processing", "delivered", "failed"], required: true },
391
+ { name: "nextAttemptAt", type: "date" },
392
+ { name: "deliveredAt", type: "date" },
393
+ { name: "lastError", type: "textarea" }
394
+ ],
395
+ access: { read: ({ user }) => !!user?.roles?.includes("admin"), create: () => false, update: () => false, delete: () => false },
396
+ admin: { hidden: true }
397
+ };
899
398
  function normalizeConfig(config) {
900
399
  const collections = config?.collections || [];
901
400
  const globals = config?.globals || [];
902
401
  const needsAudit = collections.some((col) => col.audit);
402
+ const needsWorkflow = collections.some((col) => col.workflow);
903
403
  const normalizedCollections = collections.map((col) => {
904
404
  let fields = col.fields || [];
905
405
  const existingFieldNames = new Set(fields.map((f) => f.name));
@@ -994,9 +494,17 @@ function normalizeConfig(config) {
994
494
  };
995
495
  });
996
496
  const hasAuditCollection = normalizedCollections.some((col) => col.slug === AUDIT_COLLECTION_SLUG);
497
+ const systemCollections = [];
498
+ if (needsAudit && !hasAuditCollection) systemCollections.push(AUDIT_COLLECTION);
499
+ if (needsWorkflow && !normalizedCollections.some((col) => col.slug === WORKFLOW_HISTORY_COLLECTION)) {
500
+ systemCollections.push(WORKFLOW_HISTORY_COLLECTION_CONFIG);
501
+ }
502
+ if (needsWorkflow && !normalizedCollections.some((col) => col.slug === LIFECYCLE_EVENTS_COLLECTION)) {
503
+ systemCollections.push(LIFECYCLE_EVENTS_COLLECTION_CONFIG);
504
+ }
997
505
  return {
998
506
  ...config,
999
- collections: [...normalizedCollections, ...needsAudit && !hasAuditCollection ? [AUDIT_COLLECTION] : []],
507
+ collections: [...normalizedCollections, ...systemCollections],
1000
508
  globals
1001
509
  };
1002
510
  }
@@ -1335,6 +843,831 @@ async function executeFieldAfterRead(fields, doc, user, db) {
1335
843
  return result;
1336
844
  }
1337
845
 
846
+ // src/utils/openapi.ts
847
+ function generateOpenApi(config) {
848
+ const spec = {
849
+ openapi: "3.0.0",
850
+ info: {
851
+ title: "Dyrected API",
852
+ version: "1.0.0",
853
+ description: "Automatically generated OpenAPI specification for the Dyrected project."
854
+ },
855
+ components: {
856
+ schemas: {
857
+ WorkflowMetadata: {
858
+ type: "object",
859
+ required: ["state", "revision"],
860
+ properties: {
861
+ state: { type: "string" },
862
+ revision: { type: "integer", minimum: 1 },
863
+ publishedRevision: { type: "integer", minimum: 1 },
864
+ publishedAt: { type: "string", format: "date-time" },
865
+ publishedBy: { type: "string" },
866
+ availableTransitions: { type: "array", items: { type: "string" } }
867
+ }
868
+ },
869
+ WorkflowTransitionRequest: {
870
+ type: "object",
871
+ properties: {
872
+ expectedRevision: { type: "integer", minimum: 1 },
873
+ comment: { type: "string" }
874
+ }
875
+ },
876
+ WorkflowHistoryEntry: {
877
+ type: "object",
878
+ required: [
879
+ "collection",
880
+ "documentId",
881
+ "transition",
882
+ "from",
883
+ "to",
884
+ "revision",
885
+ "createdAt"
886
+ ],
887
+ properties: {
888
+ id: { type: "string" },
889
+ collection: { type: "string" },
890
+ documentId: { type: "string" },
891
+ transition: { type: "string" },
892
+ from: { type: "string" },
893
+ to: { type: "string" },
894
+ revision: { type: "integer" },
895
+ comment: { type: "string", nullable: true },
896
+ actorId: { type: "string", nullable: true },
897
+ createdAt: { type: "string", format: "date-time" }
898
+ }
899
+ },
900
+ Error: {
901
+ type: "object",
902
+ properties: {
903
+ message: { type: "string" },
904
+ errors: {
905
+ type: "array",
906
+ items: { type: "object", additionalProperties: true }
907
+ }
908
+ }
909
+ },
910
+ AuthCredentials: {
911
+ type: "object",
912
+ required: ["email", "password"],
913
+ properties: {
914
+ email: { type: "string", format: "email" },
915
+ password: { type: "string" }
916
+ }
917
+ },
918
+ TokenResponse: {
919
+ type: "object",
920
+ properties: {
921
+ token: { type: "string" },
922
+ user: { type: "object", additionalProperties: true }
923
+ }
924
+ }
925
+ },
926
+ securitySchemes: {
927
+ ApiKeyAuth: {
928
+ type: "apiKey",
929
+ in: "header",
930
+ name: "x-api-key"
931
+ }
932
+ }
933
+ },
934
+ paths: {},
935
+ security: [{ ApiKeyAuth: [] }]
936
+ };
937
+ spec.paths["/api/schemas"] = {
938
+ get: {
939
+ tags: ["System"],
940
+ summary: "Get the serialized Dyrected schema",
941
+ security: [],
942
+ responses: {
943
+ 200: { description: "Collection and global schema definitions" }
944
+ }
945
+ }
946
+ };
947
+ spec.paths["/api/openapi.json"] = {
948
+ get: {
949
+ tags: ["System"],
950
+ summary: "Get the OpenAPI specification",
951
+ security: [],
952
+ responses: { 200: { description: "OpenAPI 3.0 document" } }
953
+ }
954
+ };
955
+ spec.paths["/api/docs"] = {
956
+ get: {
957
+ tags: ["System"],
958
+ summary: "Open interactive API documentation",
959
+ security: [],
960
+ responses: { 200: { description: "Swagger UI HTML" } }
961
+ }
962
+ };
963
+ spec.paths["/api/dyrected/options/{collection}/{field}"] = {
964
+ get: {
965
+ tags: ["System"],
966
+ summary: "Resolve dynamic field options",
967
+ parameters: [
968
+ {
969
+ name: "collection",
970
+ in: "path",
971
+ required: true,
972
+ schema: { type: "string" }
973
+ },
974
+ {
975
+ name: "field",
976
+ in: "path",
977
+ required: true,
978
+ schema: { type: "string" }
979
+ }
980
+ ],
981
+ responses: { 200: { description: "Resolved option items" } }
982
+ }
983
+ };
984
+ spec.paths["/api/preferences/{key}"] = {
985
+ get: {
986
+ tags: ["Preferences"],
987
+ summary: "Get an authenticated user preference",
988
+ parameters: [
989
+ { name: "key", in: "path", required: true, schema: { type: "string" } }
990
+ ],
991
+ responses: { 200: { description: "Preference value" } }
992
+ },
993
+ put: {
994
+ tags: ["Preferences"],
995
+ summary: "Set an authenticated user preference",
996
+ parameters: [
997
+ { name: "key", in: "path", required: true, schema: { type: "string" } }
998
+ ],
999
+ requestBody: {
1000
+ required: true,
1001
+ content: { "application/json": { schema: { type: "object" } } }
1002
+ },
1003
+ responses: { 200: { description: "Updated preference" } }
1004
+ }
1005
+ };
1006
+ spec.paths["/api/preview-token"] = {
1007
+ post: {
1008
+ tags: ["Preview"],
1009
+ summary: "Create a preview token",
1010
+ responses: { 200: { description: "Short-lived preview token" } }
1011
+ }
1012
+ };
1013
+ spec.paths["/api/preview-data"] = {
1014
+ get: {
1015
+ tags: ["Preview"],
1016
+ summary: "Resolve preview data from a token",
1017
+ security: [],
1018
+ parameters: [
1019
+ {
1020
+ name: "token",
1021
+ in: "query",
1022
+ required: true,
1023
+ schema: { type: "string" }
1024
+ }
1025
+ ],
1026
+ responses: { 200: { description: "Preview document data" } }
1027
+ }
1028
+ };
1029
+ for (const collection of config.collections) {
1030
+ spec.components.schemas[collection.slug] = collectionToSchema(collection);
1031
+ }
1032
+ for (const global of config.globals) {
1033
+ spec.components.schemas[global.slug] = globalToSchema(global);
1034
+ }
1035
+ for (const collection of config.collections) {
1036
+ const slug = collection.slug;
1037
+ const path = `/api/collections/${slug}`;
1038
+ const labels = collection.labels || { singular: slug, plural: `${slug}s` };
1039
+ spec.paths[path] = {
1040
+ get: {
1041
+ tags: ["Collections"],
1042
+ summary: `Find ${labels.plural}`,
1043
+ parameters: [
1044
+ {
1045
+ name: "limit",
1046
+ in: "query",
1047
+ schema: { type: "integer", default: 10 }
1048
+ },
1049
+ {
1050
+ name: "page",
1051
+ in: "query",
1052
+ schema: { type: "integer", default: 1 }
1053
+ },
1054
+ {
1055
+ name: "where",
1056
+ in: "query",
1057
+ schema: { type: "string" },
1058
+ description: "JSON filter"
1059
+ },
1060
+ {
1061
+ name: "sort",
1062
+ in: "query",
1063
+ schema: { type: "string" },
1064
+ description: "Sort field (e.g. -createdAt)"
1065
+ }
1066
+ ],
1067
+ responses: {
1068
+ 200: {
1069
+ description: "Success",
1070
+ content: {
1071
+ "application/json": {
1072
+ schema: {
1073
+ type: "object",
1074
+ properties: {
1075
+ docs: {
1076
+ type: "array",
1077
+ items: { $ref: `#/components/schemas/${slug}` }
1078
+ },
1079
+ total: { type: "integer" },
1080
+ limit: { type: "integer" },
1081
+ page: { type: "integer" }
1082
+ }
1083
+ }
1084
+ }
1085
+ }
1086
+ }
1087
+ }
1088
+ },
1089
+ post: {
1090
+ tags: ["Collections"],
1091
+ summary: `Create ${labels.singular}`,
1092
+ requestBody: {
1093
+ required: true,
1094
+ content: {
1095
+ "application/json": {
1096
+ schema: { $ref: `#/components/schemas/${slug}` }
1097
+ }
1098
+ }
1099
+ },
1100
+ responses: {
1101
+ 201: {
1102
+ description: "Created",
1103
+ content: {
1104
+ "application/json": {
1105
+ schema: { $ref: `#/components/schemas/${slug}` }
1106
+ }
1107
+ }
1108
+ }
1109
+ }
1110
+ }
1111
+ };
1112
+ spec.paths[`${path}/{id}`] = {
1113
+ get: {
1114
+ tags: ["Collections"],
1115
+ summary: `Get a single ${labels.singular}`,
1116
+ parameters: [
1117
+ {
1118
+ name: "id",
1119
+ in: "path",
1120
+ required: true,
1121
+ schema: { type: "string" }
1122
+ }
1123
+ ],
1124
+ responses: {
1125
+ 200: {
1126
+ description: "Success",
1127
+ content: {
1128
+ "application/json": {
1129
+ schema: { $ref: `#/components/schemas/${slug}` }
1130
+ }
1131
+ }
1132
+ }
1133
+ }
1134
+ },
1135
+ patch: {
1136
+ tags: ["Collections"],
1137
+ summary: `Update ${labels.singular}`,
1138
+ parameters: [
1139
+ {
1140
+ name: "id",
1141
+ in: "path",
1142
+ required: true,
1143
+ schema: { type: "string" }
1144
+ }
1145
+ ],
1146
+ requestBody: {
1147
+ required: true,
1148
+ content: {
1149
+ "application/json": {
1150
+ schema: { $ref: `#/components/schemas/${slug}` }
1151
+ }
1152
+ }
1153
+ },
1154
+ responses: {
1155
+ 200: {
1156
+ description: "Updated",
1157
+ content: {
1158
+ "application/json": {
1159
+ schema: { $ref: `#/components/schemas/${slug}` }
1160
+ }
1161
+ }
1162
+ }
1163
+ }
1164
+ },
1165
+ delete: {
1166
+ tags: ["Collections"],
1167
+ summary: `Delete ${labels.singular}`,
1168
+ parameters: [
1169
+ {
1170
+ name: "id",
1171
+ in: "path",
1172
+ required: true,
1173
+ schema: { type: "string" }
1174
+ }
1175
+ ],
1176
+ responses: {
1177
+ 204: { description: "Deleted" }
1178
+ }
1179
+ }
1180
+ };
1181
+ spec.paths[`${path}/delete-many`] = {
1182
+ delete: {
1183
+ tags: ["Collections"],
1184
+ summary: `Delete multiple ${labels.plural}`,
1185
+ requestBody: {
1186
+ required: true,
1187
+ content: {
1188
+ "application/json": {
1189
+ schema: {
1190
+ type: "object",
1191
+ required: ["ids"],
1192
+ properties: {
1193
+ ids: { type: "array", items: { type: "string" } }
1194
+ }
1195
+ }
1196
+ }
1197
+ }
1198
+ },
1199
+ responses: { 200: { description: "Deleted and failed document IDs" } }
1200
+ }
1201
+ };
1202
+ spec.paths[`${path}/seed`] = {
1203
+ post: {
1204
+ tags: ["Collections"],
1205
+ summary: `Seed initial ${labels.plural}`,
1206
+ responses: { 200: { description: "Seeded documents" } }
1207
+ }
1208
+ };
1209
+ if (collection.upload) {
1210
+ spec.paths[`${path}/media`] = {
1211
+ get: {
1212
+ tags: ["Media"],
1213
+ summary: `List ${labels.plural}`,
1214
+ responses: { 200: { description: "Paginated media documents" } }
1215
+ },
1216
+ post: {
1217
+ tags: ["Media"],
1218
+ summary: `Upload ${labels.singular}`,
1219
+ requestBody: {
1220
+ required: true,
1221
+ content: {
1222
+ "multipart/form-data": {
1223
+ schema: {
1224
+ type: "object",
1225
+ required: ["file"],
1226
+ properties: { file: { type: "string", format: "binary" } }
1227
+ }
1228
+ }
1229
+ }
1230
+ },
1231
+ responses: { 201: { description: "Uploaded media document" } }
1232
+ }
1233
+ };
1234
+ spec.paths[`${path}/media/{filename}`] = {
1235
+ get: {
1236
+ tags: ["Media"],
1237
+ summary: `Serve ${labels.singular} bytes`,
1238
+ parameters: [
1239
+ {
1240
+ name: "filename",
1241
+ in: "path",
1242
+ required: true,
1243
+ schema: { type: "string" }
1244
+ }
1245
+ ],
1246
+ security: [],
1247
+ responses: {
1248
+ 200: { description: "Stored file" },
1249
+ 404: { description: "File not found" }
1250
+ }
1251
+ }
1252
+ };
1253
+ }
1254
+ if (collection.auth) {
1255
+ const publicAuthPost = (summary) => ({
1256
+ tags: ["Authentication"],
1257
+ summary,
1258
+ security: [],
1259
+ requestBody: {
1260
+ required: true,
1261
+ content: {
1262
+ "application/json": {
1263
+ schema: { type: "object", additionalProperties: true }
1264
+ }
1265
+ }
1266
+ },
1267
+ responses: {
1268
+ 200: { description: "Success" },
1269
+ 400: { description: "Invalid request" }
1270
+ }
1271
+ });
1272
+ spec.paths[`${path}/login`] = {
1273
+ post: {
1274
+ ...publicAuthPost(`Log in to ${labels.plural}`),
1275
+ requestBody: {
1276
+ required: true,
1277
+ content: {
1278
+ "application/json": {
1279
+ schema: { $ref: "#/components/schemas/AuthCredentials" }
1280
+ }
1281
+ }
1282
+ },
1283
+ responses: {
1284
+ 200: {
1285
+ description: "Authenticated",
1286
+ content: {
1287
+ "application/json": {
1288
+ schema: { $ref: "#/components/schemas/TokenResponse" }
1289
+ }
1290
+ }
1291
+ },
1292
+ 401: { description: "Invalid credentials" }
1293
+ }
1294
+ }
1295
+ };
1296
+ spec.paths[`${path}/logout`] = {
1297
+ post: {
1298
+ tags: ["Authentication"],
1299
+ summary: `Log out of ${labels.plural}`,
1300
+ responses: { 200: { description: "Logged out" } }
1301
+ }
1302
+ };
1303
+ spec.paths[`${path}/init`] = {
1304
+ get: {
1305
+ tags: ["Authentication"],
1306
+ summary: `Get ${labels.plural} initialization state`,
1307
+ security: [],
1308
+ responses: { 200: { description: "Initialization state" } }
1309
+ }
1310
+ };
1311
+ spec.paths[`${path}/first-user`] = {
1312
+ post: publicAuthPost(`Register the first ${labels.singular}`)
1313
+ };
1314
+ spec.paths[`${path}/me`] = {
1315
+ get: {
1316
+ tags: ["Authentication"],
1317
+ summary: `Get the current ${labels.singular}`,
1318
+ responses: { 200: { description: "Authenticated user" } }
1319
+ }
1320
+ };
1321
+ spec.paths[`${path}/refresh-token`] = {
1322
+ post: {
1323
+ tags: ["Authentication"],
1324
+ summary: "Refresh an authentication token",
1325
+ responses: { 200: { description: "Refreshed token" } }
1326
+ }
1327
+ };
1328
+ spec.paths[`${path}/forgot-password`] = {
1329
+ post: publicAuthPost("Request a password reset")
1330
+ };
1331
+ spec.paths[`${path}/reset-password`] = {
1332
+ post: publicAuthPost("Reset a password")
1333
+ };
1334
+ spec.paths[`${path}/invite`] = {
1335
+ post: {
1336
+ tags: ["Authentication"],
1337
+ summary: `Invite a ${labels.singular}`,
1338
+ responses: { 200: { description: "Invitation sent" } }
1339
+ }
1340
+ };
1341
+ spec.paths[`${path}/accept-invite`] = {
1342
+ post: publicAuthPost("Accept an invitation")
1343
+ };
1344
+ spec.paths[`${path}/{id}/change-password`] = {
1345
+ post: {
1346
+ tags: ["Authentication"],
1347
+ summary: `Change a ${labels.singular} password`,
1348
+ parameters: [
1349
+ {
1350
+ name: "id",
1351
+ in: "path",
1352
+ required: true,
1353
+ schema: { type: "string" }
1354
+ }
1355
+ ],
1356
+ responses: { 200: { description: "Password changed" } }
1357
+ }
1358
+ };
1359
+ }
1360
+ if (collection.workflow) {
1361
+ spec.paths[`${path}/{id}/transitions/{transition}`] = {
1362
+ post: {
1363
+ tags: ["Workflows"],
1364
+ summary: `Transition ${labels.singular} workflow`,
1365
+ parameters: [
1366
+ {
1367
+ name: "id",
1368
+ in: "path",
1369
+ required: true,
1370
+ schema: { type: "string" }
1371
+ },
1372
+ {
1373
+ name: "transition",
1374
+ in: "path",
1375
+ required: true,
1376
+ schema: {
1377
+ type: "string",
1378
+ enum: collection.workflow.transitions.map((item) => item.name)
1379
+ }
1380
+ }
1381
+ ],
1382
+ requestBody: {
1383
+ content: {
1384
+ "application/json": {
1385
+ schema: {
1386
+ $ref: "#/components/schemas/WorkflowTransitionRequest"
1387
+ }
1388
+ }
1389
+ }
1390
+ },
1391
+ responses: {
1392
+ 200: {
1393
+ description: "Transition applied",
1394
+ content: {
1395
+ "application/json": {
1396
+ schema: { $ref: `#/components/schemas/${slug}` }
1397
+ }
1398
+ }
1399
+ },
1400
+ 400: { description: "Required transition input is missing" },
1401
+ 403: { description: "Transition capability denied" },
1402
+ 409: { description: "Invalid state or stale revision" }
1403
+ }
1404
+ }
1405
+ };
1406
+ spec.paths[`${path}/{id}/workflow-history`] = {
1407
+ get: {
1408
+ tags: ["Workflows"],
1409
+ summary: `Get ${labels.singular} workflow history`,
1410
+ parameters: [
1411
+ {
1412
+ name: "id",
1413
+ in: "path",
1414
+ required: true,
1415
+ schema: { type: "string" }
1416
+ },
1417
+ {
1418
+ name: "limit",
1419
+ in: "query",
1420
+ schema: { type: "integer", default: 50, maximum: 100 }
1421
+ }
1422
+ ],
1423
+ responses: {
1424
+ 200: {
1425
+ description: "Workflow transition history",
1426
+ content: {
1427
+ "application/json": {
1428
+ schema: {
1429
+ type: "object",
1430
+ properties: {
1431
+ docs: {
1432
+ type: "array",
1433
+ items: {
1434
+ $ref: "#/components/schemas/WorkflowHistoryEntry"
1435
+ }
1436
+ },
1437
+ total: { type: "integer" },
1438
+ limit: { type: "integer" },
1439
+ page: { type: "integer" }
1440
+ }
1441
+ }
1442
+ }
1443
+ }
1444
+ },
1445
+ 403: { description: "Collection read access denied" }
1446
+ }
1447
+ }
1448
+ };
1449
+ }
1450
+ }
1451
+ for (const global of config.globals) {
1452
+ const slug = global.slug;
1453
+ const path = `/api/globals/${slug}`;
1454
+ spec.paths[path] = {
1455
+ get: {
1456
+ tags: ["Globals"],
1457
+ summary: `Get ${global.label || slug}`,
1458
+ responses: {
1459
+ 200: {
1460
+ description: "Success",
1461
+ content: {
1462
+ "application/json": {
1463
+ schema: { $ref: `#/components/schemas/${slug}` }
1464
+ }
1465
+ }
1466
+ }
1467
+ }
1468
+ },
1469
+ patch: {
1470
+ tags: ["Globals"],
1471
+ summary: `Update ${global.label || slug}`,
1472
+ requestBody: {
1473
+ required: true,
1474
+ content: {
1475
+ "application/json": {
1476
+ schema: { $ref: `#/components/schemas/${slug}` }
1477
+ }
1478
+ }
1479
+ },
1480
+ responses: {
1481
+ 200: {
1482
+ description: "Updated",
1483
+ content: {
1484
+ "application/json": {
1485
+ schema: { $ref: `#/components/schemas/${slug}` }
1486
+ }
1487
+ }
1488
+ }
1489
+ }
1490
+ }
1491
+ };
1492
+ spec.paths[`${path}/seed`] = {
1493
+ post: {
1494
+ tags: ["Globals"],
1495
+ summary: `Seed ${global.label || slug}`,
1496
+ responses: { 200: { description: "Seeded global" } }
1497
+ }
1498
+ };
1499
+ }
1500
+ if (config.storage) {
1501
+ spec.paths["/api/media/{filename}"] = {
1502
+ get: {
1503
+ tags: ["Media"],
1504
+ summary: "Serve a stored file",
1505
+ security: [],
1506
+ parameters: [
1507
+ {
1508
+ name: "filename",
1509
+ in: "path",
1510
+ required: true,
1511
+ schema: { type: "string" }
1512
+ }
1513
+ ],
1514
+ responses: {
1515
+ 200: { description: "Stored file bytes" },
1516
+ 404: { description: "File not found" }
1517
+ }
1518
+ }
1519
+ };
1520
+ }
1521
+ return spec;
1522
+ }
1523
+ function collectionToSchema(collection) {
1524
+ const { properties, required } = fieldsToProperties(collection.fields);
1525
+ return {
1526
+ type: "object",
1527
+ properties: {
1528
+ id: { type: "string" },
1529
+ createdAt: { type: "string", format: "date-time" },
1530
+ updatedAt: { type: "string", format: "date-time" },
1531
+ ...collection.workflow ? { _workflow: { $ref: "#/components/schemas/WorkflowMetadata" } } : {},
1532
+ ...properties
1533
+ },
1534
+ required: ["id", ...required]
1535
+ };
1536
+ }
1537
+ function globalToSchema(global) {
1538
+ const { properties, required } = fieldsToProperties(global.fields);
1539
+ return {
1540
+ type: "object",
1541
+ properties,
1542
+ required
1543
+ };
1544
+ }
1545
+ function fieldsToProperties(fields) {
1546
+ const props = {};
1547
+ const required = [];
1548
+ for (const field of fields) {
1549
+ if (field.type === "row") {
1550
+ const nested = fieldsToProperties(field.fields || []);
1551
+ Object.assign(props, nested.properties);
1552
+ required.push(...nested.required);
1553
+ continue;
1554
+ }
1555
+ if (!field.name) continue;
1556
+ props[field.name] = fieldToSchema(field);
1557
+ if (field.required) {
1558
+ required.push(field.name);
1559
+ }
1560
+ }
1561
+ return { properties: props, required };
1562
+ }
1563
+ function fieldToSchema(field) {
1564
+ let schema = {};
1565
+ switch (field.type) {
1566
+ case "text":
1567
+ case "textarea":
1568
+ case "email":
1569
+ schema = { type: "string" };
1570
+ break;
1571
+ case "url":
1572
+ schema = {
1573
+ oneOf: [
1574
+ { type: "string" },
1575
+ { type: "object", additionalProperties: true }
1576
+ ]
1577
+ };
1578
+ break;
1579
+ case "icon":
1580
+ schema = { type: "string" };
1581
+ break;
1582
+ case "number":
1583
+ schema = { type: "number" };
1584
+ break;
1585
+ case "boolean":
1586
+ schema = { type: "boolean" };
1587
+ break;
1588
+ case "date":
1589
+ schema = { type: "string", format: "date" };
1590
+ break;
1591
+ case "datetime":
1592
+ schema = { type: "string", format: "date-time" };
1593
+ break;
1594
+ case "time":
1595
+ schema = { type: "string", format: "time" };
1596
+ break;
1597
+ case "select":
1598
+ case "radio":
1599
+ schema = {
1600
+ type: "string",
1601
+ enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
1602
+ };
1603
+ break;
1604
+ case "multiSelect":
1605
+ schema = {
1606
+ type: "array",
1607
+ items: {
1608
+ type: "string",
1609
+ enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
1610
+ }
1611
+ };
1612
+ break;
1613
+ case "relationship":
1614
+ case "image": {
1615
+ const valueSchema = {
1616
+ type: "string",
1617
+ description: `ID of a ${field.relationTo} record`
1618
+ };
1619
+ schema = field.hasMany ? { type: "array", items: valueSchema } : valueSchema;
1620
+ break;
1621
+ }
1622
+ case "join":
1623
+ schema = {
1624
+ type: "array",
1625
+ readOnly: true,
1626
+ items: { type: "object", additionalProperties: true }
1627
+ };
1628
+ break;
1629
+ case "object": {
1630
+ const { properties, required } = fieldsToProperties(field.fields || []);
1631
+ schema = { type: "object", properties, required };
1632
+ break;
1633
+ }
1634
+ case "array": {
1635
+ const { properties, required } = fieldsToProperties(field.fields || []);
1636
+ schema = {
1637
+ type: "array",
1638
+ items: { type: "object", properties, required }
1639
+ };
1640
+ break;
1641
+ }
1642
+ case "json":
1643
+ case "richText":
1644
+ schema = { type: "object", additionalProperties: true };
1645
+ break;
1646
+ case "blocks":
1647
+ schema = {
1648
+ type: "array",
1649
+ items: {
1650
+ oneOf: field.blocks?.map((block) => {
1651
+ const { properties, required } = fieldsToProperties(block.fields);
1652
+ return {
1653
+ type: "object",
1654
+ properties: {
1655
+ blockType: { type: "string", enum: [block.slug] },
1656
+ ...properties
1657
+ },
1658
+ required: ["blockType", ...required]
1659
+ };
1660
+ })
1661
+ }
1662
+ };
1663
+ break;
1664
+ default:
1665
+ schema = { type: "string" };
1666
+ }
1667
+ if (field.label) schema.description = field.label;
1668
+ return schema;
1669
+ }
1670
+
1338
1671
  // src/index.ts
1339
1672
  function defineCollection(config) {
1340
1673
  return config;
@@ -1347,16 +1680,30 @@ function defineConfig(config) {
1347
1680
  }
1348
1681
  // Annotate the CommonJS export names for ESM import in node:
1349
1682
  0 && (module.exports = {
1683
+ LIFECYCLE_EVENTS_COLLECTION,
1684
+ LIFECYCLE_EVENT_NAMES,
1685
+ WORKFLOW_HISTORY_COLLECTION,
1686
+ availableWorkflowTransitions,
1687
+ canViewWorkflowDraft,
1688
+ createLifecycleEvent,
1689
+ createWorkflowDocument,
1350
1690
  defineCollection,
1351
1691
  defineConfig,
1352
1692
  defineGlobal,
1693
+ dispatchLifecycleEvent,
1694
+ dispatchPendingLifecycleEvents,
1353
1695
  executeFieldAfterRead,
1354
1696
  executeFieldBeforeChange,
1355
- generateAIPrompt,
1356
- generateFreshSetupPrompt,
1697
+ generateOpenApi,
1698
+ initializeWorkflowDocument,
1699
+ materializeWorkflowDocument,
1357
1700
  normalizeConfig,
1358
1701
  parseMongoWhere,
1359
1702
  parseSort,
1360
1703
  parseSqlWhere,
1361
- runCollectionHooks
1704
+ publishingWorkflow,
1705
+ runCollectionHooks,
1706
+ saveWorkflowDraft,
1707
+ transitionWorkflow,
1708
+ workflowCapabilities
1362
1709
  });