@dyrected/core 2.7.0 → 2.7.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.
@@ -0,0 +1,3365 @@
1
+ // src/observability.ts
2
+ import {
3
+ TraceFlags,
4
+ context as otelContext,
5
+ trace
6
+ } from "@opentelemetry/api";
7
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
8
+ import { PrometheusExporter } from "@opentelemetry/exporter-prometheus";
9
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
10
+ import { resourceFromAttributes } from "@opentelemetry/resources";
11
+ import {
12
+ MeterProvider,
13
+ PeriodicExportingMetricReader
14
+ } from "@opentelemetry/sdk-metrics";
15
+ import {
16
+ BasicTracerProvider,
17
+ BatchSpanProcessor,
18
+ ConsoleSpanExporter
19
+ } from "@opentelemetry/sdk-trace-base";
20
+ import pino, {
21
+ destination as pinoDestination,
22
+ multistream,
23
+ stdTimeFunctions
24
+ } from "pino";
25
+ import pinoPretty from "pino-pretty";
26
+ import { Writable } from "stream";
27
+ var DEFAULT_REDACT_HEADERS = ["authorization", "cookie", "set-cookie", "x-api-key"];
28
+ var DEFAULT_REDACT_PATHS = [
29
+ "password",
30
+ "currentPassword",
31
+ "newPassword",
32
+ "confirmPassword",
33
+ "token",
34
+ "refreshToken",
35
+ "accessToken",
36
+ "secret",
37
+ "apiKey",
38
+ "inviteToken",
39
+ "resetToken"
40
+ ];
41
+ var DEFAULT_MAX_BODY_BYTES = 8192;
42
+ var DEFAULT_SUCCESS_SAMPLE_RATE = 0.1;
43
+ var DEFAULT_BODY_SAMPLE_RATE = 0.02;
44
+ var REDACTED_VALUE = "[REDACTED]";
45
+ var runtimeByConfig = /* @__PURE__ */ new WeakMap();
46
+ var fallbackLogger = pino({
47
+ name: "dyrected",
48
+ enabled: process.env.DISABLE_LOGGING !== "true",
49
+ timestamp: stdTimeFunctions.isoTime
50
+ });
51
+ function resolveObservabilityConfig(config) {
52
+ const requestLogging = config?.requestLogging;
53
+ const sampling = config?.sampling;
54
+ const tracing = config?.tracing;
55
+ const metrics = config?.metrics;
56
+ return {
57
+ requestLogging: {
58
+ enabled: requestLogging?.enabled ?? true,
59
+ logBodies: requestLogging?.logBodies ?? false,
60
+ maxBodyBytes: requestLogging?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES,
61
+ redactPaths: uniqueValues([
62
+ ...DEFAULT_REDACT_PATHS,
63
+ ...requestLogging?.redactPaths ?? []
64
+ ]),
65
+ includeHeaders: normalizeHeaderNames(requestLogging?.includeHeaders ?? []),
66
+ redactHeaders: uniqueValues(
67
+ normalizeHeaderNames([
68
+ ...DEFAULT_REDACT_HEADERS,
69
+ ...requestLogging?.redactHeaders ?? []
70
+ ])
71
+ )
72
+ },
73
+ sampling: {
74
+ successRate: clampRate(sampling?.successRate ?? DEFAULT_SUCCESS_SAMPLE_RATE),
75
+ traceSuccessRate: clampRate(
76
+ sampling?.traceSuccessRate ?? sampling?.successRate ?? DEFAULT_SUCCESS_SAMPLE_RATE
77
+ ),
78
+ bodySuccessRate: clampRate(
79
+ sampling?.bodySuccessRate ?? Math.min(DEFAULT_BODY_SAMPLE_RATE, sampling?.successRate ?? DEFAULT_SUCCESS_SAMPLE_RATE)
80
+ ),
81
+ alwaysKeep4xx: sampling?.alwaysKeep4xx ?? true,
82
+ alwaysKeep5xx: sampling?.alwaysKeep5xx ?? true
83
+ },
84
+ tracing: {
85
+ enabled: tracing?.enabled ?? false,
86
+ serviceName: tracing?.serviceName ?? "dyrected",
87
+ exporter: tracing?.exporter ?? "none",
88
+ headers: tracing?.headers ?? {},
89
+ endpoint: tracing?.endpoint
90
+ },
91
+ metrics: {
92
+ enabled: metrics?.enabled ?? false,
93
+ exporter: metrics?.exporter ?? "none",
94
+ endpoint: metrics?.endpoint,
95
+ path: metrics?.path ?? "/metrics"
96
+ },
97
+ transports: {
98
+ targets: config?.transports?.targets && config.transports.targets.length > 0 ? config.transports.targets : [{ type: "stdout" }]
99
+ }
100
+ };
101
+ }
102
+ function createObservabilityRuntime(config) {
103
+ const resolved = resolveObservabilityConfig(config.observability);
104
+ const logger = createRootLogger(config.logger, resolved);
105
+ const shutdownTasks = [];
106
+ const meterRuntime = resolved.metrics.enabled || resolved.metrics.exporter === "prometheus" ? createMeterProvider(resolved) : void 0;
107
+ const tracerProvider = resolved.tracing.enabled ? createTracerProvider(resolved) : void 0;
108
+ const tracer = tracerProvider?.getTracer("dyrected");
109
+ const meter = meterRuntime?.provider.getMeter("dyrected");
110
+ const metrics = meter ? {
111
+ requestCount: meter.createCounter("dyrected_http_requests_total", {
112
+ description: "Total HTTP requests served by Dyrected"
113
+ }),
114
+ authFailureCount: meter.createCounter("dyrected_auth_failures_total", {
115
+ description: "Authentication failures"
116
+ }),
117
+ uncaughtErrorCount: meter.createCounter("dyrected_uncaught_errors_total", {
118
+ description: "Uncaught application errors"
119
+ }),
120
+ auditWriteFailureCount: meter.createCounter("dyrected_audit_write_failures_total", {
121
+ description: "Audit log persistence failures"
122
+ }),
123
+ emailSendFailureCount: meter.createCounter("dyrected_email_send_failures_total", {
124
+ description: "Transactional email delivery failures"
125
+ }),
126
+ workflowHookFailureCount: meter.createCounter("dyrected_workflow_hook_failures_total", {
127
+ description: "Workflow hook failures isolated after successful writes"
128
+ }),
129
+ requestDuration: meter.createHistogram("dyrected_http_request_duration_ms", {
130
+ description: "HTTP request duration in milliseconds",
131
+ unit: "ms"
132
+ })
133
+ } : void 0;
134
+ if (meterRuntime) {
135
+ shutdownTasks.push(() => meterRuntime.provider.shutdown());
136
+ }
137
+ if (tracerProvider) {
138
+ shutdownTasks.push(() => tracerProvider.shutdown());
139
+ }
140
+ return {
141
+ logger,
142
+ config: resolved,
143
+ tracer,
144
+ metrics,
145
+ prometheusExporter: meterRuntime?.prometheusExporter,
146
+ shutdown: async () => {
147
+ for (const task of shutdownTasks) {
148
+ await task();
149
+ }
150
+ },
151
+ recordAuthFailure: (attributes) => metrics?.authFailureCount.add(1, attributes),
152
+ recordUncaughtError: (attributes) => metrics?.uncaughtErrorCount.add(1, attributes),
153
+ recordAuditWriteFailure: (attributes) => metrics?.auditWriteFailureCount.add(1, attributes),
154
+ recordEmailSendFailure: (attributes) => metrics?.emailSendFailureCount.add(1, attributes),
155
+ recordWorkflowHookFailure: (attributes) => metrics?.workflowHookFailureCount.add(1, attributes)
156
+ };
157
+ }
158
+ function bindObservabilityRuntime(config, runtime) {
159
+ runtimeByConfig.set(config, runtime);
160
+ }
161
+ function getObservabilityRuntime(config) {
162
+ if (!config || typeof config !== "object") return void 0;
163
+ return runtimeByConfig.get(config);
164
+ }
165
+ function createRootLogger(loggerConfig, observability) {
166
+ if (loggerConfig && !("options" in loggerConfig)) {
167
+ return loggerConfig;
168
+ }
169
+ const options = loggerConfig?.options ?? {};
170
+ const enabled = options.enabled ?? process.env.DISABLE_LOGGING !== "true";
171
+ const name = options.name ?? "dyrected";
172
+ if (loggerConfig?.destination) {
173
+ return pino(
174
+ {
175
+ ...options,
176
+ enabled,
177
+ name,
178
+ timestamp: options.timestamp ?? stdTimeFunctions.isoTime
179
+ },
180
+ loggerConfig.destination
181
+ );
182
+ }
183
+ const streams = buildTransportStreams(observability);
184
+ const destination = streams.length === 1 ? streams[0] : multistream(streams.map((stream) => ({ stream })));
185
+ return pino(
186
+ {
187
+ ...options,
188
+ enabled,
189
+ name,
190
+ timestamp: options.timestamp ?? stdTimeFunctions.isoTime
191
+ },
192
+ destination
193
+ );
194
+ }
195
+ function buildTransportStreams(observability) {
196
+ const targets = observability.transports.targets;
197
+ if (targets.length === 0) {
198
+ return [defaultLoggerDestination()];
199
+ }
200
+ return targets.map((target) => {
201
+ switch (target.type) {
202
+ case "stdout":
203
+ return defaultLoggerDestination();
204
+ case "stderr":
205
+ return pinoDestination(2);
206
+ case "file":
207
+ return pinoDestination(target.path);
208
+ case "otlp":
209
+ return new OtlpLogWritable(target.endpoint, target.headers);
210
+ }
211
+ });
212
+ }
213
+ function defaultLoggerDestination() {
214
+ if (process.env.NODE_ENV !== "production") {
215
+ return pinoPretty({
216
+ colorize: true,
217
+ ignore: "pid,hostname",
218
+ translateTime: "SYS:HH:MM:ss",
219
+ destination: 1,
220
+ sync: true
221
+ });
222
+ }
223
+ return pinoDestination(1);
224
+ }
225
+ var OtlpLogWritable = class extends Writable {
226
+ constructor(endpoint, headers = {}) {
227
+ super();
228
+ this.endpoint = endpoint;
229
+ this.headers = headers;
230
+ }
231
+ endpoint;
232
+ headers;
233
+ _write(chunk, _encoding, callback) {
234
+ const payload = chunk.toString();
235
+ void fetch(this.endpoint, {
236
+ method: "POST",
237
+ headers: {
238
+ "content-type": "application/json",
239
+ ...this.headers
240
+ },
241
+ body: JSON.stringify({ logs: payload.trim().split("\n").filter(Boolean) })
242
+ }).then(() => callback()).catch(
243
+ (error) => callback(error instanceof Error ? error : new Error(String(error)))
244
+ );
245
+ }
246
+ };
247
+ function createTracerProvider(observability) {
248
+ const exporter = createTraceExporter(observability);
249
+ const provider = new BasicTracerProvider({
250
+ resource: resourceFromAttributes({
251
+ "service.name": observability.tracing.serviceName
252
+ }),
253
+ spanProcessors: exporter ? [new BatchSpanProcessor(exporter)] : []
254
+ });
255
+ trace.setGlobalTracerProvider(provider);
256
+ return provider;
257
+ }
258
+ function createTraceExporter(observability) {
259
+ switch (observability.tracing.exporter) {
260
+ case "console":
261
+ return new ConsoleSpanExporter();
262
+ case "otlp":
263
+ return new OTLPTraceExporter({
264
+ url: observability.tracing.endpoint,
265
+ headers: observability.tracing.headers
266
+ });
267
+ default:
268
+ return void 0;
269
+ }
270
+ }
271
+ function createMeterProvider(observability) {
272
+ const readers = [];
273
+ let prometheusExporter;
274
+ switch (observability.metrics.exporter) {
275
+ case "otlp":
276
+ readers.push(
277
+ new PeriodicExportingMetricReader({
278
+ exporter: new OTLPMetricExporter({
279
+ url: observability.metrics.endpoint
280
+ })
281
+ })
282
+ );
283
+ break;
284
+ case "prometheus":
285
+ prometheusExporter = new PrometheusExporter({
286
+ endpoint: observability.metrics.path,
287
+ preventServerStart: true
288
+ });
289
+ readers.push(prometheusExporter);
290
+ break;
291
+ }
292
+ const provider = new MeterProvider({
293
+ resource: resourceFromAttributes({
294
+ "service.name": observability.tracing.serviceName
295
+ }),
296
+ readers
297
+ });
298
+ return { provider, prometheusExporter };
299
+ }
300
+ function getConfigLogger(config, component) {
301
+ const base = config?.logger && !("options" in config.logger) ? config.logger : fallbackLogger;
302
+ return base.child({ component });
303
+ }
304
+ function getRequestLogger(c, component) {
305
+ const base = c.get("logger") ?? fallbackLogger;
306
+ return component ? base.child({ component }) : base;
307
+ }
308
+ function buildRequestLogger(runtime, vars, requestId) {
309
+ const trace2 = vars.requestTrace;
310
+ return runtime.logger.child({
311
+ requestId,
312
+ siteId: vars.siteId,
313
+ workspaceId: vars.workspaceId,
314
+ traceId: trace2?.traceId,
315
+ spanId: trace2?.spanId
316
+ });
317
+ }
318
+ function shouldSampleRequest(requestId, statusCode, sampling, kind) {
319
+ if (statusCode >= 500 && sampling.alwaysKeep5xx) return true;
320
+ if (statusCode >= 400 && sampling.alwaysKeep4xx) return true;
321
+ const rate = kind === "trace" ? sampling.traceSuccessRate : kind === "body" ? sampling.bodySuccessRate : sampling.successRate;
322
+ return deterministicSample(requestId ?? "no-request-id", rate);
323
+ }
324
+ function redactHeaders(headers, observability) {
325
+ const includeHeaders = new Set(observability.requestLogging.includeHeaders);
326
+ const redactHeaders2 = new Set(observability.requestLogging.redactHeaders);
327
+ const output = {};
328
+ for (const [key, value] of Object.entries(headers)) {
329
+ const normalizedKey = key.toLowerCase();
330
+ if (includeHeaders.size > 0 && !includeHeaders.has(normalizedKey)) continue;
331
+ output[normalizedKey] = redactHeaders2.has(normalizedKey) ? REDACTED_VALUE : value;
332
+ }
333
+ return output;
334
+ }
335
+ async function captureRequestBody(request, observability) {
336
+ const contentType = request.headers.get("content-type") ?? void 0;
337
+ const contentLength = toNumber(request.headers.get("content-length"));
338
+ const jsonBody = contentType?.includes("application/json");
339
+ if (!jsonBody) {
340
+ return {
341
+ attempted: false,
342
+ contentType,
343
+ contentLength
344
+ };
345
+ }
346
+ try {
347
+ const text = await request.clone().text();
348
+ if (!text) {
349
+ return { attempted: true, contentType, contentLength };
350
+ }
351
+ const truncated = text.length > observability.requestLogging.maxBodyBytes;
352
+ const raw = truncated ? text.slice(0, observability.requestLogging.maxBodyBytes) : text;
353
+ try {
354
+ const parsed = JSON.parse(raw);
355
+ return {
356
+ attempted: true,
357
+ contentType,
358
+ contentLength: contentLength ?? text.length,
359
+ truncated,
360
+ body: redactBody(parsed, observability.requestLogging.redactPaths)
361
+ };
362
+ } catch {
363
+ return {
364
+ attempted: true,
365
+ contentType,
366
+ contentLength: contentLength ?? text.length,
367
+ truncated,
368
+ parseFailed: true
369
+ };
370
+ }
371
+ } catch {
372
+ return {
373
+ attempted: true,
374
+ contentType,
375
+ contentLength,
376
+ parseFailed: true
377
+ };
378
+ }
379
+ }
380
+ function redactBody(value, redactPaths) {
381
+ const cloned = deepClone(value);
382
+ for (const path of redactPaths) {
383
+ applyRedaction(cloned, path.split("."));
384
+ }
385
+ return cloned;
386
+ }
387
+ function applyRedaction(target, segments) {
388
+ if (!target || segments.length === 0) return;
389
+ const [segment, ...rest] = segments;
390
+ if (Array.isArray(target)) {
391
+ for (const item of target) {
392
+ if (segment === "*") {
393
+ applyRedaction(item, rest);
394
+ } else {
395
+ applyRedaction(item, segments);
396
+ }
397
+ }
398
+ return;
399
+ }
400
+ if (typeof target !== "object") return;
401
+ const record = target;
402
+ if (segment === "*") {
403
+ for (const value of Object.values(record)) {
404
+ applyRedaction(value, rest);
405
+ }
406
+ return;
407
+ }
408
+ if (!(segment in record)) return;
409
+ if (rest.length === 0) {
410
+ record[segment] = REDACTED_VALUE;
411
+ return;
412
+ }
413
+ applyRedaction(record[segment], rest);
414
+ }
415
+ function deepClone(value) {
416
+ if (typeof structuredClone === "function") {
417
+ return structuredClone(value);
418
+ }
419
+ return JSON.parse(JSON.stringify(value));
420
+ }
421
+ function createRequestSpan(runtime, name, attributes) {
422
+ if (!runtime.tracer) return void 0;
423
+ const span = runtime.tracer.startSpan(name, { attributes }, otelContext.active());
424
+ const spanContext = span.spanContext();
425
+ return {
426
+ span,
427
+ traceId: spanContext.traceId,
428
+ spanId: spanContext.spanId,
429
+ sampled: spanContext.traceFlags === TraceFlags.SAMPLED
430
+ };
431
+ }
432
+ function endRequestSpan(requestTrace, statusCode, error) {
433
+ if (!requestTrace) return;
434
+ requestTrace.span.setAttribute("http.status_code", statusCode);
435
+ if (error) {
436
+ requestTrace.span.recordException(error instanceof Error ? error : new Error(String(error)));
437
+ }
438
+ requestTrace.span.end();
439
+ }
440
+ function attachRequestMetrics(runtime, args) {
441
+ runtime.metrics?.requestCount.add(1, {
442
+ method: args.method,
443
+ route: args.route,
444
+ status_class: `${Math.floor(args.statusCode / 100)}xx`
445
+ });
446
+ runtime.metrics?.requestDuration.record(args.durationMs, {
447
+ method: args.method,
448
+ route: args.route,
449
+ status_class: `${Math.floor(args.statusCode / 100)}xx`
450
+ });
451
+ }
452
+ async function renderPrometheusMetrics(exporter) {
453
+ let statusCode = 200;
454
+ const headers = {};
455
+ let body = "";
456
+ await new Promise((resolve) => {
457
+ const response = {
458
+ statusCode,
459
+ setHeader(name, value) {
460
+ headers[name.toLowerCase()] = value;
461
+ },
462
+ end(chunk) {
463
+ if (chunk) body += chunk;
464
+ statusCode = this.statusCode;
465
+ resolve();
466
+ }
467
+ };
468
+ exporter.getMetricsRequestHandler({}, response);
469
+ });
470
+ return { body, headers, statusCode };
471
+ }
472
+ function normalizeHeaderNames(headers) {
473
+ return headers.map((value) => value.toLowerCase());
474
+ }
475
+ function uniqueValues(values) {
476
+ return [...new Set(values)];
477
+ }
478
+ function clampRate(value) {
479
+ if (Number.isNaN(value)) return 0;
480
+ return Math.max(0, Math.min(1, value));
481
+ }
482
+ function deterministicSample(seed, rate) {
483
+ if (rate >= 1) return true;
484
+ if (rate <= 0) return false;
485
+ let hash = 0;
486
+ for (let index = 0; index < seed.length; index += 1) {
487
+ hash = hash * 31 + seed.charCodeAt(index) >>> 0;
488
+ }
489
+ return hash / 4294967295 <= rate;
490
+ }
491
+ function toNumber(value) {
492
+ if (!value) return void 0;
493
+ const parsed = Number(value);
494
+ return Number.isFinite(parsed) ? parsed : void 0;
495
+ }
496
+
497
+ // src/workflows.ts
498
+ var WORKFLOW_HISTORY_COLLECTION = "__workflow_history";
499
+ var LIFECYCLE_EVENTS_COLLECTION = "__lifecycle_events";
500
+ var EDITOR_CAPABILITIES = ["entry.edit", "entry.submit"];
501
+ var PUBLISHER_CAPABILITIES = ["entry.edit", "entry.submit", "entry.publish", "entry.unpublish"];
502
+ function definePublishingWorkflow(options = {}) {
503
+ const editors = options.editors ?? ["editor"];
504
+ const publishers = options.publishers ?? ["publisher", "admin"];
505
+ return {
506
+ initialState: "draft",
507
+ draftState: "draft",
508
+ states: [
509
+ { name: "draft", label: "Draft", color: "neutral" },
510
+ { name: "in_review", label: "In review", color: "warning" },
511
+ { name: "published", label: "Published", color: "success", published: true }
512
+ ],
513
+ transitions: [
514
+ { name: "submit", label: "Submit for review", from: "draft", to: "in_review", requiredCapabilities: ["entry.submit"] },
515
+ { name: "publish", label: "Publish", from: "in_review", to: "published", requiredCapabilities: ["entry.publish"] },
516
+ { name: "reject", label: "Request changes", from: "in_review", to: "draft", requiredCapabilities: ["entry.publish"], requireComment: true },
517
+ { name: "unpublish", label: "Unpublish", from: "published", to: "draft", requiredCapabilities: ["entry.unpublish"], unpublish: true }
518
+ ],
519
+ roles: [
520
+ ...editors.map((role) => ({ role, capabilities: [...EDITOR_CAPABILITIES] })),
521
+ ...publishers.map((role) => ({ role, capabilities: [...PUBLISHER_CAPABILITIES] }))
522
+ ]
523
+ };
524
+ }
525
+ function publishingWorkflow() {
526
+ return definePublishingWorkflow();
527
+ }
528
+ function simplePublishingWorkflow() {
529
+ return {
530
+ initialState: "draft",
531
+ draftState: "draft",
532
+ states: [
533
+ { name: "draft", label: "Draft", color: "neutral" },
534
+ { name: "published", label: "Published", color: "success", published: true }
535
+ ],
536
+ transitions: [
537
+ { name: "publish", label: "Publish", from: "draft", to: "published" },
538
+ { name: "unpublish", label: "Unpublish", from: "published", to: "draft", unpublish: true }
539
+ ]
540
+ // Intentionally no `roles`: this lightweight workflow (synthesized from
541
+ // `drafts: true`) does no capability-based gating. Draft visibility for a
542
+ // no-roles workflow is handled in `canViewWorkflowDraft`.
543
+ };
544
+ }
545
+ function publicMetadata(meta) {
546
+ const { availableTransitions: _availableTransitions, ...safe } = meta;
547
+ return safe;
548
+ }
549
+ function workflowCapabilities(workflow, user) {
550
+ const capabilities = new Set(Array.isArray(user?.capabilities) ? user.capabilities : []);
551
+ const roles = Array.isArray(user?.roles) ? user.roles : [];
552
+ for (const mapping of workflow.roles ?? []) {
553
+ if (roles.includes(mapping.role)) mapping.capabilities.forEach((capability) => capabilities.add(capability));
554
+ }
555
+ return capabilities;
556
+ }
557
+ function canViewWorkflowDraft(workflow, user) {
558
+ if (!user) return false;
559
+ const capabilities = workflowCapabilities(workflow, user);
560
+ if (capabilities.has("entry.edit")) return true;
561
+ if (workflow.transitions.some(
562
+ (transition) => (transition.requiredCapabilities ?? []).some((capability) => capabilities.has(capability))
563
+ )) {
564
+ return true;
565
+ }
566
+ if (!workflow.roles || workflow.roles.length === 0) return true;
567
+ return false;
568
+ }
569
+ function availableWorkflowTransitions(workflow, state, user) {
570
+ const capabilities = workflowCapabilities(workflow, user);
571
+ return workflow.transitions.filter((transition) => {
572
+ const from = Array.isArray(transition.from) ? transition.from : [transition.from];
573
+ return from.includes(state) && (transition.requiredCapabilities ?? []).every((item) => capabilities.has(item));
574
+ });
575
+ }
576
+ function initializeWorkflowDocument(data, workflow) {
577
+ return {
578
+ ...data,
579
+ __workflow: { state: workflow.initialState, revision: 1 }
580
+ };
581
+ }
582
+ function publishedStateName(workflow) {
583
+ return workflow.states.find((state) => state.published)?.name ?? workflow.states[workflow.states.length - 1]?.name ?? workflow.initialState;
584
+ }
585
+ function materializeWorkflowDocument(doc, workflow, user) {
586
+ const meta = doc.__workflow;
587
+ const publishedState = publishedStateName(workflow);
588
+ if (!meta) {
589
+ const { __published: _legacyPublished, __workflow: _legacyWorkflow, ...working2 } = doc;
590
+ const state = publishedStateName(workflow);
591
+ return {
592
+ ...working2,
593
+ _workflow: {
594
+ state,
595
+ revision: 1,
596
+ availableTransitions: availableWorkflowTransitions(workflow, state, user).map((item) => item.name)
597
+ }
598
+ };
599
+ }
600
+ const { __published, __workflow, ...working } = doc;
601
+ if (!canViewWorkflowDraft(workflow, user)) {
602
+ if (!__published || typeof __published !== "object") {
603
+ if (meta.state === publishedState) {
604
+ return { ...working, _workflow: publicMetadata(meta) };
605
+ }
606
+ return null;
607
+ }
608
+ return { id: doc.id, ...__published, _workflow: publicMetadata(meta) };
609
+ }
610
+ return {
611
+ ...working,
612
+ _workflow: {
613
+ ...meta,
614
+ availableTransitions: availableWorkflowTransitions(workflow, meta.state, user).map((item) => item.name)
615
+ }
616
+ };
617
+ }
618
+ function eventId() {
619
+ return globalThis.crypto?.randomUUID?.() ?? `evt_${Date.now()}_${Math.random().toString(36).slice(2)}`;
620
+ }
621
+ function createLifecycleEvent(args) {
622
+ return {
623
+ id: eventId(),
624
+ name: args.name,
625
+ collection: args.collection,
626
+ documentId: args.documentId,
627
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
628
+ actorId: args.actorId,
629
+ payload: args.payload,
630
+ attempts: 0,
631
+ status: "pending"
632
+ };
633
+ }
634
+ async function persistEvent(db, event) {
635
+ await db.create({ collection: LIFECYCLE_EVENTS_COLLECTION, data: event });
636
+ }
637
+ async function dispatchLifecycleEvent(config, event) {
638
+ const db = config.db;
639
+ if (!db || !config.events?.handlers.length) return;
640
+ const maxAttempts = config.events.maxAttempts ?? 8;
641
+ const retryDelayMs = config.events.retryDelayMs ?? 1e3;
642
+ const attempts = event.attempts + 1;
643
+ try {
644
+ await db.update({ collection: LIFECYCLE_EVENTS_COLLECTION, id: event.id, data: { status: "processing", attempts } });
645
+ for (const handler of config.events.handlers) await handler({ ...event, status: "processing", attempts });
646
+ await db.update({
647
+ collection: LIFECYCLE_EVENTS_COLLECTION,
648
+ id: event.id,
649
+ data: { status: "delivered", attempts, deliveredAt: (/* @__PURE__ */ new Date()).toISOString(), lastError: null }
650
+ });
651
+ } catch (error) {
652
+ const exhausted = attempts >= maxAttempts;
653
+ await db.update({
654
+ collection: LIFECYCLE_EVENTS_COLLECTION,
655
+ id: event.id,
656
+ data: {
657
+ status: "failed",
658
+ attempts,
659
+ lastError: error instanceof Error ? error.message : String(error),
660
+ nextAttemptAt: exhausted ? null : new Date(Date.now() + retryDelayMs * 2 ** (attempts - 1)).toISOString()
661
+ }
662
+ });
663
+ }
664
+ }
665
+ async function dispatchPendingLifecycleEvents(config, limit = 50) {
666
+ if (!config.db || !config.events?.handlers.length) return 0;
667
+ const maxAttempts = config.events.maxAttempts ?? 8;
668
+ const result = await config.db.find({
669
+ collection: LIFECYCLE_EVENTS_COLLECTION,
670
+ where: { status: { in: ["pending", "failed"] } },
671
+ sort: "occurredAt",
672
+ limit
673
+ });
674
+ const now = Date.now();
675
+ const due = result.docs.filter(
676
+ (doc) => Number(doc.attempts ?? 0) < maxAttempts && (!doc.nextAttemptAt || new Date(doc.nextAttemptAt).getTime() <= now)
677
+ );
678
+ for (const event of due) await dispatchLifecycleEvent(config, event);
679
+ return due.length;
680
+ }
681
+ async function saveWorkflowDraft(args) {
682
+ const { config, collection, id, originalDoc, data, user } = args;
683
+ const db = config.db;
684
+ const workflow = collection.workflow;
685
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
686
+ const previous = originalDoc.__workflow;
687
+ const isLegacyPublishedDoc = !previous;
688
+ const baselineRevision = previous?.revision ?? 1;
689
+ const event = createLifecycleEvent({
690
+ name: "revision.created",
691
+ collection: collection.slug,
692
+ documentId: id,
693
+ actorId: user?.sub,
694
+ payload: {
695
+ revision: baselineRevision + 1,
696
+ previousRevision: isLegacyPublishedDoc ? baselineRevision : previous?.revision ?? null
697
+ }
698
+ });
699
+ const doc = await db.transaction(async (tx) => {
700
+ const nextMeta = {
701
+ ...previous ?? {},
702
+ state: isLegacyPublishedDoc ? workflow.draftState ?? workflow.initialState : originalDoc.__published ? workflow.draftState ?? workflow.initialState : previous.state,
703
+ revision: baselineRevision + 1,
704
+ ...isLegacyPublishedDoc ? { publishedRevision: baselineRevision } : {}
705
+ };
706
+ const updateData = {
707
+ ...data,
708
+ __workflow: nextMeta
709
+ };
710
+ if (isLegacyPublishedDoc) {
711
+ const { __workflow: _legacyWorkflow, __published: _legacyPublished, ...publishedSnapshot } = originalDoc;
712
+ updateData.__published = publishedSnapshot;
713
+ }
714
+ const updated = await tx.update({ collection: collection.slug, id, data: updateData });
715
+ await persistEvent(tx, event);
716
+ return updated;
717
+ });
718
+ void dispatchLifecycleEvent(config, event);
719
+ return { doc, event };
720
+ }
721
+ async function createWorkflowDocument(args) {
722
+ const { config, collection, data, user } = args;
723
+ const db = config.db;
724
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
725
+ let event;
726
+ const doc = await db.transaction(async (tx) => {
727
+ const created = await tx.create({ collection: collection.slug, data });
728
+ event = createLifecycleEvent({
729
+ name: "revision.created",
730
+ collection: collection.slug,
731
+ documentId: created.id,
732
+ actorId: user?.sub,
733
+ payload: { revision: 1, previousRevision: null }
734
+ });
735
+ await persistEvent(tx, event);
736
+ return created;
737
+ });
738
+ void dispatchLifecycleEvent(config, event);
739
+ return { doc, event };
740
+ }
741
+ async function transitionWorkflow(args) {
742
+ const { config, collection, id, transitionName, expectedRevision, comment, user, req } = args;
743
+ const db = config.db;
744
+ const workflow = collection.workflow;
745
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
746
+ const original = await db.findOne({ collection: collection.slug, id });
747
+ if (!original) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
748
+ const meta = original.__workflow;
749
+ if (!meta) throw Object.assign(new Error("Entry has no workflow metadata"), { statusCode: 409 });
750
+ if (expectedRevision !== void 0 && expectedRevision !== meta.revision) {
751
+ throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), { statusCode: 409 });
752
+ }
753
+ const transition = workflow.transitions.find((item) => item.name === transitionName);
754
+ const fromStates = transition ? Array.isArray(transition.from) ? transition.from : [transition.from] : [];
755
+ if (!transition || !fromStates.includes(meta.state)) {
756
+ throw Object.assign(new Error(`Transition "${transitionName}" is not valid from "${meta.state}".`), { statusCode: 409 });
757
+ }
758
+ if (!availableWorkflowTransitions(workflow, meta.state, user).some((item) => item.name === transition.name)) {
759
+ throw Object.assign(new Error(`You do not have permission to perform "${transition.label}".`), { statusCode: 403 });
760
+ }
761
+ if (transition.requireComment && !comment?.trim()) {
762
+ throw Object.assign(new Error(`A comment is required for "${transition.label}".`), { statusCode: 400 });
763
+ }
764
+ const hookContext = { transition, from: meta.state, to: transition.to, doc: original, user, comment, req, db };
765
+ for (const hook of workflow.hooks?.beforeTransition ?? []) await hook(hookContext);
766
+ const events = [createLifecycleEvent({
767
+ name: "workflow.transitioned",
768
+ collection: collection.slug,
769
+ documentId: id,
770
+ actorId: user?.sub,
771
+ payload: { transition: transition.name, from: meta.state, to: transition.to, revision: meta.revision, comment }
772
+ })];
773
+ const targetState = workflow.states.find((state) => state.name === transition.to);
774
+ if (targetState.published) {
775
+ events.push(createLifecycleEvent({ name: "entry.published", collection: collection.slug, documentId: id, actorId: user?.sub, payload: { revision: meta.revision } }));
776
+ } else if (transition.unpublish) {
777
+ events.push(createLifecycleEvent({ name: "entry.unpublished", collection: collection.slug, documentId: id, actorId: user?.sub, payload: { revision: meta.publishedRevision } }));
778
+ }
779
+ const updated = await db.transaction(async (tx) => {
780
+ const locked = await tx.findOne({ collection: collection.slug, id });
781
+ if (!locked) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
782
+ const lockedMeta = locked.__workflow;
783
+ if (lockedMeta.revision !== meta.revision || lockedMeta.state !== meta.state || expectedRevision !== void 0 && lockedMeta.revision !== expectedRevision) {
784
+ throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), { statusCode: 409 });
785
+ }
786
+ const now = (/* @__PURE__ */ new Date()).toISOString();
787
+ const { __published: _published, __workflow: _workflow, id: _id, ...working } = locked;
788
+ const nextMeta = {
789
+ ...lockedMeta,
790
+ state: transition.to,
791
+ ...targetState.published ? { publishedRevision: lockedMeta.revision, publishedAt: now, publishedBy: user?.sub } : {},
792
+ ...transition.unpublish ? { publishedRevision: void 0, publishedAt: void 0, publishedBy: void 0 } : {}
793
+ };
794
+ const data = { __workflow: nextMeta };
795
+ if (targetState.published) data.__published = working;
796
+ if (transition.unpublish) data.__published = null;
797
+ const next = await tx.update({ collection: collection.slug, id, data });
798
+ await tx.create({
799
+ collection: WORKFLOW_HISTORY_COLLECTION,
800
+ 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 }
801
+ });
802
+ for (const event of events) await persistEvent(tx, event);
803
+ if (collection.audit) {
804
+ 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 }) } });
805
+ }
806
+ return next;
807
+ });
808
+ for (const event of events) void dispatchLifecycleEvent(config, event);
809
+ for (const hook of workflow.hooks?.afterTransition ?? []) {
810
+ try {
811
+ await hook({ ...hookContext, doc: updated, event: events[0] });
812
+ } catch (error) {
813
+ getObservabilityRuntime(config)?.recordWorkflowHookFailure({
814
+ collection: collection.slug,
815
+ transition: transition.name
816
+ });
817
+ getConfigLogger(config, "workflow").error({
818
+ err: error,
819
+ msg: "afterTransition hook failed",
820
+ collection: collection.slug,
821
+ transition: transition.name,
822
+ documentId: id
823
+ });
824
+ }
825
+ }
826
+ return updated;
827
+ }
828
+
829
+ // src/utils/admin-auth.ts
830
+ function getAdminAuthCollection(config) {
831
+ const adminCollection = resolveAdminAuthCollection(config.collections, config.adminAuth?.collectionSlug);
832
+ return adminCollection ?? null;
833
+ }
834
+ function resolveAdminAuthCollection(collections, collectionSlug) {
835
+ const adminsCollection = collections.find((collection) => collection.slug === "__admins");
836
+ if (adminsCollection) return adminsCollection;
837
+ if (collectionSlug) {
838
+ const requestedCollection = collections.find((collection) => collection.slug === collectionSlug);
839
+ if (requestedCollection) return requestedCollection;
840
+ }
841
+ return collections.find((collection) => collection.auth);
842
+ }
843
+ function getPublicAdminAuthConfig(adminAuth, collections) {
844
+ const providers = (adminAuth?.providers ?? []).map((provider) => ({
845
+ id: provider.id,
846
+ type: provider.type,
847
+ displayName: provider.displayName || humanizeProviderName(provider.id, provider.type),
848
+ autoRedirect: provider.autoRedirect
849
+ }));
850
+ const resolvedCollectionSlug = collections ? resolveAdminAuthCollection(collections, adminAuth?.collectionSlug)?.slug : adminAuth?.collectionSlug;
851
+ return {
852
+ mode: adminAuth?.mode ?? "local",
853
+ collectionSlug: resolvedCollectionSlug,
854
+ provisioningMode: adminAuth?.provisioningMode,
855
+ providers
856
+ };
857
+ }
858
+ function humanizeProviderName(id, type) {
859
+ const cleaned = id.replace(/[-_]+/g, " ").trim();
860
+ if (!cleaned) return type.toUpperCase();
861
+ return cleaned.replace(/\b\w/g, (char) => char.toUpperCase());
862
+ }
863
+
864
+ // src/utils/declarative-hooks.ts
865
+ import jexl2 from "jexl";
866
+
867
+ // src/utils/jexl-helpers.ts
868
+ import jexl from "jexl";
869
+ function slugify(val) {
870
+ if (val === void 0 || val === null) return "";
871
+ return String(val).normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
872
+ }
873
+ function lower(val) {
874
+ if (val === void 0 || val === null) return "";
875
+ return String(val).toLowerCase();
876
+ }
877
+ function upper(val) {
878
+ if (val === void 0 || val === null) return "";
879
+ return String(val).toUpperCase();
880
+ }
881
+ function trim(val) {
882
+ if (val === void 0 || val === null) return "";
883
+ return String(val).trim();
884
+ }
885
+ function replace(val, search, replacement) {
886
+ if (val === void 0 || val === null) return "";
887
+ return String(val).replace(new RegExp(String(search || ""), "g"), String(replacement ?? ""));
888
+ }
889
+ function includes(arrOrStr, item) {
890
+ if (Array.isArray(arrOrStr)) {
891
+ return arrOrStr.includes(item);
892
+ }
893
+ if (typeof arrOrStr === "string") {
894
+ return arrOrStr.includes(String(item ?? ""));
895
+ }
896
+ return false;
897
+ }
898
+ function startsWith(str, prefix) {
899
+ if (str === void 0 || str === null) return false;
900
+ return String(str).startsWith(String(prefix ?? ""));
901
+ }
902
+ function endsWith(str, suffix) {
903
+ if (str === void 0 || str === null) return false;
904
+ return String(str).endsWith(String(suffix ?? ""));
905
+ }
906
+ function defaultValue(val, fallback) {
907
+ if (val === void 0 || val === null || val === "") return fallback;
908
+ return val;
909
+ }
910
+ function coalesce(...args) {
911
+ for (const arg of args) {
912
+ if (arg !== void 0 && arg !== null && arg !== "") return arg;
913
+ }
914
+ return null;
915
+ }
916
+ function length(val) {
917
+ if (Array.isArray(val) || typeof val === "string") return val.length;
918
+ if (val && typeof val === "object") return Object.keys(val).length;
919
+ return 0;
920
+ }
921
+ function registerJexlHelpers(jexlInstance = jexl) {
922
+ const helpers = {
923
+ slugify,
924
+ lower,
925
+ upper,
926
+ trim,
927
+ replace,
928
+ includes,
929
+ startsWith,
930
+ endsWith,
931
+ default: defaultValue,
932
+ coalesce,
933
+ length
934
+ };
935
+ for (const [name, fn] of Object.entries(helpers)) {
936
+ try {
937
+ jexlInstance.addFunction(name, fn);
938
+ } catch {
939
+ }
940
+ }
941
+ }
942
+ registerJexlHelpers(jexl);
943
+ var BUILTIN_JEXL_HELPERS = [
944
+ "slugify",
945
+ "lower",
946
+ "upper",
947
+ "trim",
948
+ "replace",
949
+ "includes",
950
+ "startsWith",
951
+ "endsWith",
952
+ "default",
953
+ "coalesce",
954
+ "length"
955
+ ];
956
+
957
+ // src/utils/declarative-hooks.ts
958
+ registerJexlHelpers(jexl2);
959
+ var SURFACE_ROOTS = {
960
+ "collection.beforeRead": ["req", "user", "query", ...BUILTIN_JEXL_HELPERS],
961
+ "collection.afterRead": ["req", "user", "doc", ...BUILTIN_JEXL_HELPERS],
962
+ "collection.beforeChange": ["req", "user", "data", "doc", "operation", ...BUILTIN_JEXL_HELPERS],
963
+ "global.beforeRead": ["req", "user", "query", ...BUILTIN_JEXL_HELPERS],
964
+ "global.afterRead": ["req", "user", "doc", ...BUILTIN_JEXL_HELPERS],
965
+ "global.beforeChange": ["req", "user", "data", "doc", "operation", ...BUILTIN_JEXL_HELPERS],
966
+ "field.beforeChange": ["value", "data", "originalDoc", "user", ...BUILTIN_JEXL_HELPERS],
967
+ "field.admin.onChange": ["value", "siblingData", "data", ...BUILTIN_JEXL_HELPERS]
968
+ };
969
+ var ACCESS_ROOTS = ["user", "req", "doc", "data", "id", "config", ...BUILTIN_JEXL_HELPERS];
970
+ var ADMIN_CONDITION_RESERVED_ROOTS = ["data", "siblingData", "user", "id", ...BUILTIN_JEXL_HELPERS];
971
+ var PREVIEW_URL_RESERVED_ROOTS = ["siteUrl", "id", ...BUILTIN_JEXL_HELPERS];
972
+ var COMPILE_CACHE = /* @__PURE__ */ new Map();
973
+ function compileExpression(expression) {
974
+ const cached = COMPILE_CACHE.get(expression);
975
+ if (cached) return cached;
976
+ const compiled = jexl2.compile(expression);
977
+ const next = { ast: compiled._ast };
978
+ COMPILE_CACHE.set(expression, next);
979
+ return next;
980
+ }
981
+ function isPlainObject(value) {
982
+ return !!value && typeof value === "object" && !Array.isArray(value);
983
+ }
984
+ function quoteSegment(value) {
985
+ return `["${value.replace(/"/g, '\\"')}"]`;
986
+ }
987
+ function fieldSegment(field, index) {
988
+ return typeof field.name === "string" && field.name.length > 0 ? `fields${quoteSegment(field.name)}` : `fields[${index}]`;
989
+ }
990
+ function blockSegment(block, index) {
991
+ return typeof block.slug === "string" && block.slug.length > 0 ? `blocks${quoteSegment(block.slug)}` : `blocks[${index}]`;
992
+ }
993
+ function collectionSegment(collection, index) {
994
+ return typeof collection.slug === "string" && collection.slug.length > 0 ? `collections${quoteSegment(collection.slug)}` : `collections[${index}]`;
995
+ }
996
+ function globalSegment(global, index) {
997
+ return typeof global.slug === "string" && global.slug.length > 0 ? `globals${quoteSegment(global.slug)}` : `globals[${index}]`;
998
+ }
999
+ function colorize(value, code, enabled) {
1000
+ return enabled ? `\x1B[${code}m${value}\x1B[0m` : value;
1001
+ }
1002
+ function collectRootIdentifiers(node, roots, seen) {
1003
+ if (!node || typeof node !== "object" || seen.has(node)) return;
1004
+ seen.add(node);
1005
+ const candidate = node;
1006
+ if (candidate.type === "Identifier") {
1007
+ if (candidate.from) {
1008
+ collectRootIdentifiers(candidate.from, roots, seen);
1009
+ return;
1010
+ }
1011
+ if (typeof candidate.value === "string" && candidate.value !== "null") {
1012
+ roots.add(candidate.value);
1013
+ }
1014
+ return;
1015
+ }
1016
+ if (Array.isArray(node)) {
1017
+ for (const entry of node) collectRootIdentifiers(entry, roots, seen);
1018
+ return;
1019
+ }
1020
+ for (const value of Object.values(node)) {
1021
+ if (Array.isArray(value)) {
1022
+ for (const entry of value) collectRootIdentifiers(entry, roots, seen);
1023
+ continue;
1024
+ }
1025
+ if (value && typeof value === "object") {
1026
+ collectRootIdentifiers(value, roots, seen);
1027
+ }
1028
+ }
1029
+ }
1030
+ function getInvalidRoots(expression, allowedRoots) {
1031
+ const { ast } = compileExpression(expression);
1032
+ const roots = /* @__PURE__ */ new Set();
1033
+ collectRootIdentifiers(ast, roots, /* @__PURE__ */ new Set());
1034
+ const allowed = new Set(allowedRoots);
1035
+ return [...roots].filter((root) => !allowed.has(root));
1036
+ }
1037
+ function validateDeclarativeHookExpression(expression, surface, path) {
1038
+ try {
1039
+ const invalidRoots = getInvalidRoots(expression, SURFACE_ROOTS[surface]);
1040
+ if (invalidRoots.length === 0) return [];
1041
+ return [
1042
+ {
1043
+ path,
1044
+ surface,
1045
+ expression,
1046
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${SURFACE_ROOTS[surface].map((root) => `"${root}"`).join(", ")}`
1047
+ }
1048
+ ];
1049
+ } catch (error) {
1050
+ return [
1051
+ {
1052
+ path,
1053
+ surface,
1054
+ expression,
1055
+ message: `has invalid syntax: ${error.message}`
1056
+ }
1057
+ ];
1058
+ }
1059
+ }
1060
+ function validateDeclarativeAccessExpression(expression, surface, path) {
1061
+ try {
1062
+ const invalidRoots = getInvalidRoots(expression, ACCESS_ROOTS);
1063
+ if (invalidRoots.length === 0) return [];
1064
+ return [
1065
+ {
1066
+ path,
1067
+ surface,
1068
+ expression,
1069
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${ACCESS_ROOTS.map((root) => `"${root}"`).join(", ")}`
1070
+ }
1071
+ ];
1072
+ } catch (error) {
1073
+ return [
1074
+ {
1075
+ path,
1076
+ surface,
1077
+ expression,
1078
+ message: `has invalid syntax: ${error.message}`
1079
+ }
1080
+ ];
1081
+ }
1082
+ }
1083
+ function validateAdminConditionExpression(expression, path, allowedRoots) {
1084
+ try {
1085
+ const invalidRoots = getInvalidRoots(expression, allowedRoots);
1086
+ if (invalidRoots.length === 0) return [];
1087
+ return [
1088
+ {
1089
+ path,
1090
+ surface: "field.admin.condition",
1091
+ expression,
1092
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${allowedRoots.map((root) => `"${root}"`).join(", ")}`
1093
+ }
1094
+ ];
1095
+ } catch (error) {
1096
+ return [
1097
+ {
1098
+ path,
1099
+ surface: "field.admin.condition",
1100
+ expression,
1101
+ message: `has invalid syntax: ${error.message}`
1102
+ }
1103
+ ];
1104
+ }
1105
+ }
1106
+ function validatePreviewUrlExpression(expression, path, allowedRoots) {
1107
+ try {
1108
+ const invalidRoots = getInvalidRoots(expression, allowedRoots);
1109
+ if (invalidRoots.length === 0) return [];
1110
+ return [
1111
+ {
1112
+ path,
1113
+ surface: "collection.admin.previewUrl",
1114
+ expression,
1115
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${allowedRoots.map((root) => `"${root}"`).join(", ")}`
1116
+ }
1117
+ ];
1118
+ } catch (error) {
1119
+ return [
1120
+ {
1121
+ path,
1122
+ surface: "collection.admin.previewUrl",
1123
+ expression,
1124
+ message: `has invalid syntax: ${error.message}`
1125
+ }
1126
+ ];
1127
+ }
1128
+ }
1129
+ function assertValidDeclarativeHookExpression(expression, surface, path) {
1130
+ const issues = validateDeclarativeHookExpression(expression, surface, path);
1131
+ if (issues.length === 0) return;
1132
+ throw new Error(`Invalid declarative hook at ${path}: ${issues[0].message}`);
1133
+ }
1134
+ function assertValidDeclarativeHookResult(result, surface, path) {
1135
+ if (isPlainObject(result)) return;
1136
+ throw new Error(`Invalid declarative hook result at ${path}: ${surface} expressions must return an object`);
1137
+ }
1138
+ function collectFieldIssues(fields, path, issues) {
1139
+ fields.forEach((field, index) => {
1140
+ const fieldPath = `${path}.${fieldSegment(field, index)}`;
1141
+ field.hooks?.beforeChange?.forEach((hook, hookIndex) => {
1142
+ if (typeof hook !== "string") return;
1143
+ issues.push(
1144
+ ...validateDeclarativeHookExpression(
1145
+ hook,
1146
+ "field.beforeChange",
1147
+ `${fieldPath}.hooks.beforeChange[${hookIndex}]`
1148
+ )
1149
+ );
1150
+ });
1151
+ field.hooks?.afterRead?.forEach((hook, hookIndex) => {
1152
+ if (typeof hook !== "string") return;
1153
+ issues.push({
1154
+ path: `${fieldPath}.hooks.afterRead[${hookIndex}]`,
1155
+ surface: "unsupported",
1156
+ expression: hook,
1157
+ message: "declarative strings are not supported on field hooks.afterRead"
1158
+ });
1159
+ });
1160
+ if (typeof field.admin?.hooks?.onChange === "string") {
1161
+ issues.push(
1162
+ ...validateDeclarativeHookExpression(
1163
+ field.admin.hooks.onChange,
1164
+ "field.admin.onChange",
1165
+ `${fieldPath}.admin.hooks.onChange`
1166
+ )
1167
+ );
1168
+ }
1169
+ if (typeof field.admin?.hooks?.options === "string") {
1170
+ issues.push({
1171
+ path: `${fieldPath}.admin.hooks.options`,
1172
+ surface: "unsupported",
1173
+ expression: field.admin.hooks.options,
1174
+ message: "declarative strings are not supported on field admin.hooks.options"
1175
+ });
1176
+ }
1177
+ if (Array.isArray(field.fields)) {
1178
+ collectFieldIssues(field.fields, fieldPath, issues);
1179
+ }
1180
+ if (Array.isArray(field.blocks)) {
1181
+ field.blocks.forEach((block, blockIndex) => {
1182
+ if (!Array.isArray(block.fields)) return;
1183
+ collectFieldIssues(block.fields, `${fieldPath}.${blockSegment(block, blockIndex)}`, issues);
1184
+ });
1185
+ }
1186
+ });
1187
+ }
1188
+ function collectFieldNames(fields) {
1189
+ return fields.flatMap(
1190
+ (field) => typeof field.name === "string" && field.name.length > 0 ? [field.name] : []
1191
+ );
1192
+ }
1193
+ function collectAdminConditionIssues(fields, path, rootFieldNames, issues) {
1194
+ const scopeFieldNames = collectFieldNames(fields);
1195
+ const allowedRoots = [.../* @__PURE__ */ new Set([...ADMIN_CONDITION_RESERVED_ROOTS, ...rootFieldNames, ...scopeFieldNames])];
1196
+ fields.forEach((field, index) => {
1197
+ const fieldPath = `${path}.${fieldSegment(field, index)}`;
1198
+ if (typeof field.admin?.condition === "string") {
1199
+ issues.push(
1200
+ ...validateAdminConditionExpression(
1201
+ field.admin.condition,
1202
+ `${fieldPath}.admin.condition`,
1203
+ allowedRoots
1204
+ )
1205
+ );
1206
+ }
1207
+ if (Array.isArray(field.fields)) {
1208
+ collectAdminConditionIssues(field.fields, fieldPath, rootFieldNames, issues);
1209
+ }
1210
+ if (Array.isArray(field.blocks)) {
1211
+ field.blocks.forEach((block, blockIndex) => {
1212
+ if (!Array.isArray(block.fields)) return;
1213
+ collectAdminConditionIssues(
1214
+ block.fields,
1215
+ `${fieldPath}.${blockSegment(block, blockIndex)}`,
1216
+ rootFieldNames,
1217
+ issues
1218
+ );
1219
+ });
1220
+ }
1221
+ });
1222
+ }
1223
+ function collectFieldAccessIssues(fields, path, issues) {
1224
+ fields.forEach((field, index) => {
1225
+ const fieldPath = `${path}.${fieldSegment(field, index)}`;
1226
+ if (typeof field.access?.read === "string") {
1227
+ issues.push(...validateDeclarativeAccessExpression(field.access.read, "field.access", `${fieldPath}.access.read`));
1228
+ }
1229
+ if (typeof field.access?.create === "string") {
1230
+ issues.push(
1231
+ ...validateDeclarativeAccessExpression(field.access.create, "field.access", `${fieldPath}.access.create`)
1232
+ );
1233
+ }
1234
+ if (typeof field.access?.update === "string") {
1235
+ issues.push(
1236
+ ...validateDeclarativeAccessExpression(field.access.update, "field.access", `${fieldPath}.access.update`)
1237
+ );
1238
+ }
1239
+ if (Array.isArray(field.fields)) {
1240
+ collectFieldAccessIssues(field.fields, fieldPath, issues);
1241
+ }
1242
+ if (Array.isArray(field.blocks)) {
1243
+ field.blocks.forEach((block, blockIndex) => {
1244
+ if (!Array.isArray(block.fields)) return;
1245
+ collectFieldAccessIssues(
1246
+ block.fields,
1247
+ `${fieldPath}.${blockSegment(block, blockIndex)}`,
1248
+ issues
1249
+ );
1250
+ });
1251
+ }
1252
+ });
1253
+ }
1254
+ function collectHookIssues(hooks, scope, path, issues) {
1255
+ if (!hooks) return;
1256
+ const supported = {
1257
+ beforeRead: `${scope}.beforeRead`,
1258
+ afterRead: `${scope}.afterRead`,
1259
+ beforeChange: `${scope}.beforeChange`
1260
+ };
1261
+ for (const [key, value] of Object.entries(hooks)) {
1262
+ if (!Array.isArray(value)) continue;
1263
+ value.forEach((hook, index) => {
1264
+ if (typeof hook !== "string") return;
1265
+ const surface = supported[key];
1266
+ if (!surface) {
1267
+ issues.push({
1268
+ path: `${path}.${key}[${index}]`,
1269
+ surface: "unsupported",
1270
+ expression: hook,
1271
+ message: `declarative strings are not supported on ${scope} hooks.${key}`
1272
+ });
1273
+ return;
1274
+ }
1275
+ issues.push(...validateDeclarativeHookExpression(hook, surface, `${path}.${key}[${index}]`));
1276
+ });
1277
+ }
1278
+ }
1279
+ function collectDeclarativeHookValidationIssues(config) {
1280
+ const issues = [];
1281
+ config.blocks?.forEach((block, blockIndex) => {
1282
+ if (!Array.isArray(block.fields)) return;
1283
+ collectFieldIssues(
1284
+ block.fields,
1285
+ blockSegment(block, blockIndex),
1286
+ issues
1287
+ );
1288
+ });
1289
+ config.collections.forEach((collection, collectionIndex) => {
1290
+ const collectionPath = collectionSegment(collection, collectionIndex);
1291
+ collectHookIssues(
1292
+ collection.hooks,
1293
+ "collection",
1294
+ `${collectionPath}.hooks`,
1295
+ issues
1296
+ );
1297
+ collectFieldIssues(collection.fields, collectionPath, issues);
1298
+ });
1299
+ config.globals?.forEach((global, globalIndex) => {
1300
+ const globalPath = globalSegment(global, globalIndex);
1301
+ collectHookIssues(
1302
+ global.hooks,
1303
+ "global",
1304
+ `${globalPath}.hooks`,
1305
+ issues
1306
+ );
1307
+ collectFieldIssues(global.fields, globalPath, issues);
1308
+ });
1309
+ return issues;
1310
+ }
1311
+ function collectDeclarativeAccessValidationIssues(config) {
1312
+ const issues = [];
1313
+ Object.entries(config.accessPolicies ?? {}).forEach(([name, value]) => {
1314
+ if (typeof value !== "string") return;
1315
+ issues.push(
1316
+ ...validateDeclarativeAccessExpression(value, "config.accessPolicy", `accessPolicies.${name}`)
1317
+ );
1318
+ });
1319
+ config.blocks?.forEach((block, blockIndex) => {
1320
+ if (!Array.isArray(block.fields)) return;
1321
+ collectFieldAccessIssues(
1322
+ block.fields,
1323
+ blockSegment(block, blockIndex),
1324
+ issues
1325
+ );
1326
+ });
1327
+ config.collections.forEach((collection, collectionIndex) => {
1328
+ const collectionPath = collectionSegment(collection, collectionIndex);
1329
+ if (typeof collection.access?.read === "string") {
1330
+ issues.push(
1331
+ ...validateDeclarativeAccessExpression(
1332
+ collection.access.read,
1333
+ "collection.access",
1334
+ `${collectionPath}.access.read`
1335
+ )
1336
+ );
1337
+ }
1338
+ if (typeof collection.access?.create === "string") {
1339
+ issues.push(
1340
+ ...validateDeclarativeAccessExpression(
1341
+ collection.access.create,
1342
+ "collection.access",
1343
+ `${collectionPath}.access.create`
1344
+ )
1345
+ );
1346
+ }
1347
+ if (typeof collection.access?.update === "string") {
1348
+ issues.push(
1349
+ ...validateDeclarativeAccessExpression(
1350
+ collection.access.update,
1351
+ "collection.access",
1352
+ `${collectionPath}.access.update`
1353
+ )
1354
+ );
1355
+ }
1356
+ if (typeof collection.access?.delete === "string") {
1357
+ issues.push(
1358
+ ...validateDeclarativeAccessExpression(
1359
+ collection.access.delete,
1360
+ "collection.access",
1361
+ `${collectionPath}.access.delete`
1362
+ )
1363
+ );
1364
+ }
1365
+ if (typeof collection.access?.readAudit === "string") {
1366
+ issues.push(
1367
+ ...validateDeclarativeAccessExpression(
1368
+ collection.access.readAudit,
1369
+ "collection.access",
1370
+ `${collectionPath}.access.readAudit`
1371
+ )
1372
+ );
1373
+ }
1374
+ collectFieldAccessIssues(collection.fields, collectionPath, issues);
1375
+ });
1376
+ config.globals?.forEach((global, globalIndex) => {
1377
+ const globalPath = globalSegment(global, globalIndex);
1378
+ if (typeof global.access?.read === "string") {
1379
+ issues.push(
1380
+ ...validateDeclarativeAccessExpression(global.access.read, "global.access", `${globalPath}.access.read`)
1381
+ );
1382
+ }
1383
+ if (typeof global.access?.update === "string") {
1384
+ issues.push(
1385
+ ...validateDeclarativeAccessExpression(
1386
+ global.access.update,
1387
+ "global.access",
1388
+ `${globalPath}.access.update`
1389
+ )
1390
+ );
1391
+ }
1392
+ collectFieldAccessIssues(global.fields, globalPath, issues);
1393
+ });
1394
+ return issues;
1395
+ }
1396
+ function collectAdminConditionValidationIssues(config) {
1397
+ const issues = [];
1398
+ config.blocks?.forEach((block, blockIndex) => {
1399
+ if (!Array.isArray(block.fields)) return;
1400
+ collectAdminConditionIssues(
1401
+ block.fields,
1402
+ blockSegment(block, blockIndex),
1403
+ collectFieldNames(block.fields),
1404
+ issues
1405
+ );
1406
+ });
1407
+ config.collections.forEach((collection, collectionIndex) => {
1408
+ const collectionPath = collectionSegment(collection, collectionIndex);
1409
+ const rootFieldNames = collectFieldNames(collection.fields);
1410
+ collectAdminConditionIssues(collection.fields, collectionPath, rootFieldNames, issues);
1411
+ });
1412
+ config.globals?.forEach((global, globalIndex) => {
1413
+ const globalPath = globalSegment(global, globalIndex);
1414
+ const rootFieldNames = collectFieldNames(global.fields);
1415
+ collectAdminConditionIssues(global.fields, globalPath, rootFieldNames, issues);
1416
+ });
1417
+ return issues;
1418
+ }
1419
+ function collectPreviewUrlValidationIssues(config) {
1420
+ const issues = [];
1421
+ config.collections.forEach((collection, collectionIndex) => {
1422
+ if (typeof collection.admin?.previewUrl !== "string") return;
1423
+ const collectionPath = collectionSegment(collection, collectionIndex);
1424
+ const allowedRoots = [
1425
+ .../* @__PURE__ */ new Set([...PREVIEW_URL_RESERVED_ROOTS, ...collectFieldNames(collection.fields)])
1426
+ ];
1427
+ issues.push(
1428
+ ...validatePreviewUrlExpression(
1429
+ collection.admin.previewUrl,
1430
+ `${collectionPath}.admin.previewUrl`,
1431
+ allowedRoots
1432
+ )
1433
+ );
1434
+ });
1435
+ return issues;
1436
+ }
1437
+ function assertValidAdminConditionsInConfig(config, source = "config") {
1438
+ const diagnostics = collectAdminConditionValidationIssues(config).map((issue) => ({
1439
+ severity: "error",
1440
+ source: "adminCondition",
1441
+ path: issue.path,
1442
+ surface: issue.surface,
1443
+ message: issue.message,
1444
+ expression: issue.expression
1445
+ }));
1446
+ if (diagnostics.length === 0) return;
1447
+ throw new ConfigValidationError(source, diagnostics);
1448
+ }
1449
+ function assertValidPreviewUrlsInConfig(config, source = "config") {
1450
+ const diagnostics = collectPreviewUrlValidationIssues(config).map((issue) => ({
1451
+ severity: "error",
1452
+ source: "previewUrl",
1453
+ path: issue.path,
1454
+ surface: issue.surface,
1455
+ message: issue.message,
1456
+ expression: issue.expression
1457
+ }));
1458
+ if (diagnostics.length === 0) return;
1459
+ throw new ConfigValidationError(source, diagnostics);
1460
+ }
1461
+ function collectConfigDiagnostics(config) {
1462
+ const hookIssues = collectDeclarativeHookValidationIssues(config).map((issue) => ({
1463
+ severity: "error",
1464
+ source: "declarativeHook",
1465
+ path: issue.path,
1466
+ surface: issue.surface,
1467
+ message: issue.message,
1468
+ expression: issue.expression
1469
+ }));
1470
+ const accessIssues = collectDeclarativeAccessValidationIssues(config).map((issue) => ({
1471
+ severity: "error",
1472
+ source: "declarativeAccess",
1473
+ path: issue.path,
1474
+ surface: issue.surface,
1475
+ message: issue.message,
1476
+ expression: issue.expression
1477
+ }));
1478
+ const adminConditionIssues = collectAdminConditionValidationIssues(config).map((issue) => ({
1479
+ severity: "error",
1480
+ source: "adminCondition",
1481
+ path: issue.path,
1482
+ surface: issue.surface,
1483
+ message: issue.message,
1484
+ expression: issue.expression
1485
+ }));
1486
+ const previewUrlIssues = collectPreviewUrlValidationIssues(config).map((issue) => ({
1487
+ severity: "error",
1488
+ source: "previewUrl",
1489
+ path: issue.path,
1490
+ surface: issue.surface,
1491
+ message: issue.message,
1492
+ expression: issue.expression
1493
+ }));
1494
+ return [...hookIssues, ...accessIssues, ...adminConditionIssues, ...previewUrlIssues];
1495
+ }
1496
+ function formatConfigDiagnostics(source, diagnostics, options = {}) {
1497
+ const color = options.color ?? false;
1498
+ const header = `${colorize("Config validation failed", 31, color)} in ${colorize(source, 36, color)}`;
1499
+ const docLink = `${colorize(" Learn how to write declarative rules:", 90, color)} ${colorize("https://docs.dyrected.com/docs/features/admin/form-and-field-hooks", 34, color)}`;
1500
+ const lines = diagnostics.flatMap((issue, index) => [
1501
+ `${colorize(`${index + 1}.`, 31, color)} ${colorize(issue.path, 1, color)}`,
1502
+ ` ${issue.message}`,
1503
+ ` ${colorize("surface:", 90, color)} ${issue.surface}`
1504
+ ]);
1505
+ return `${header}
1506
+ ${lines.join("\n")}
1507
+
1508
+ ${docLink}`;
1509
+ }
1510
+ var ConfigValidationError = class extends Error {
1511
+ diagnostics;
1512
+ source;
1513
+ constructor(source, diagnostics) {
1514
+ super(formatConfigDiagnostics(source, diagnostics));
1515
+ this.name = "ConfigValidationError";
1516
+ this.source = source;
1517
+ this.diagnostics = diagnostics;
1518
+ }
1519
+ };
1520
+ function isConfigValidationError(error) {
1521
+ return error instanceof ConfigValidationError;
1522
+ }
1523
+ function assertValidDeclarativeHooksInConfig(config, source = "config") {
1524
+ const diagnostics = collectDeclarativeHookValidationIssues(config).map((issue) => ({
1525
+ severity: "error",
1526
+ source: "declarativeHook",
1527
+ path: issue.path,
1528
+ surface: issue.surface,
1529
+ message: issue.message,
1530
+ expression: issue.expression
1531
+ }));
1532
+ if (diagnostics.length === 0) return;
1533
+ throw new ConfigValidationError(source, diagnostics);
1534
+ }
1535
+ function assertValidDeclarativeAccessInConfig(config, source = "config") {
1536
+ const diagnostics = collectDeclarativeAccessValidationIssues(config).map((issue) => ({
1537
+ severity: "error",
1538
+ source: "declarativeAccess",
1539
+ path: issue.path,
1540
+ surface: issue.surface,
1541
+ message: issue.message,
1542
+ expression: issue.expression
1543
+ }));
1544
+ if (diagnostics.length === 0) return;
1545
+ throw new ConfigValidationError(source, diagnostics);
1546
+ }
1547
+
1548
+ // src/auth/token.ts
1549
+ import { SignJWT, jwtVerify, decodeJwt } from "jose";
1550
+ import { TextEncoder } from "util";
1551
+ function getSecret() {
1552
+ const secret = process.env.DYRECTED_JWT_SECRET;
1553
+ if (!secret) {
1554
+ throw new Error(
1555
+ "[dyrected/core] DYRECTED_JWT_SECRET is not set. Add it to your environment variables to enable auth collections."
1556
+ );
1557
+ }
1558
+ return new TextEncoder().encode(secret);
1559
+ }
1560
+ var DEFAULT_EXPIRY = "7d";
1561
+ async function signCollectionToken(payload, expiresIn = DEFAULT_EXPIRY) {
1562
+ return new SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(getSecret());
1563
+ }
1564
+ async function verifyCollectionToken(token) {
1565
+ const { payload } = await jwtVerify(token, getSecret());
1566
+ return payload;
1567
+ }
1568
+ function decodeCollectionToken(token) {
1569
+ try {
1570
+ return decodeJwt(token);
1571
+ } catch {
1572
+ return null;
1573
+ }
1574
+ }
1575
+
1576
+ // src/auth/sessions.ts
1577
+ var AUTH_SESSIONS_COLLECTION = "__auth_sessions";
1578
+ async function issueAuthSessionToken(args) {
1579
+ const sessionId = createSessionId();
1580
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1581
+ const db = args.config.db;
1582
+ if (db) {
1583
+ await db.create({
1584
+ collection: AUTH_SESSIONS_COLLECTION,
1585
+ data: {
1586
+ id: sessionId,
1587
+ userId: args.userId,
1588
+ email: args.email,
1589
+ collection: args.collection,
1590
+ authSource: args.authSource ?? "local",
1591
+ providerId: args.providerId,
1592
+ lastIp: args.ip,
1593
+ lastSeenAt: now,
1594
+ revokedAt: null,
1595
+ expiresAt: null
1596
+ }
1597
+ });
1598
+ }
1599
+ const token = await signCollectionToken(
1600
+ {
1601
+ sub: args.userId,
1602
+ email: args.email,
1603
+ collection: args.collection,
1604
+ authSource: args.authSource,
1605
+ providerId: args.providerId,
1606
+ sid: sessionId
1607
+ },
1608
+ args.expiresIn
1609
+ );
1610
+ const payload = decodeCollectionToken(token);
1611
+ const expiresAt = payload?.exp != null ? new Date(payload.exp * 1e3).toISOString() : null;
1612
+ if (db && expiresAt) {
1613
+ await db.update({
1614
+ collection: AUTH_SESSIONS_COLLECTION,
1615
+ id: sessionId,
1616
+ data: {
1617
+ expiresAt,
1618
+ lastSeenAt: now,
1619
+ lastIp: args.ip
1620
+ }
1621
+ });
1622
+ }
1623
+ return token;
1624
+ }
1625
+ async function getAuthSession(config, sessionId) {
1626
+ const db = config.db;
1627
+ if (!db) return null;
1628
+ return await db.findOne({
1629
+ collection: AUTH_SESSIONS_COLLECTION,
1630
+ id: sessionId
1631
+ });
1632
+ }
1633
+ function isAuthSessionActive(session) {
1634
+ if (!session) return false;
1635
+ if (session.revokedAt) return false;
1636
+ if (session.expiresAt && new Date(session.expiresAt).getTime() <= Date.now()) {
1637
+ return false;
1638
+ }
1639
+ return true;
1640
+ }
1641
+ async function touchAuthSession(config, sessionId, args) {
1642
+ const db = config.db;
1643
+ if (!db) return;
1644
+ await db.update({
1645
+ collection: AUTH_SESSIONS_COLLECTION,
1646
+ id: sessionId,
1647
+ data: {
1648
+ lastSeenAt: (/* @__PURE__ */ new Date()).toISOString(),
1649
+ ...args.ip ? { lastIp: args.ip } : {}
1650
+ }
1651
+ });
1652
+ }
1653
+ async function revokeAuthSession(config, sessionId) {
1654
+ const db = config.db;
1655
+ if (!db) return;
1656
+ await db.update({
1657
+ collection: AUTH_SESSIONS_COLLECTION,
1658
+ id: sessionId,
1659
+ data: {
1660
+ revokedAt: (/* @__PURE__ */ new Date()).toISOString()
1661
+ }
1662
+ });
1663
+ }
1664
+ async function revokeAllAuthSessions(config, args) {
1665
+ const db = config.db;
1666
+ if (!db) return 0;
1667
+ let page = 1;
1668
+ let revoked = 0;
1669
+ while (true) {
1670
+ const result = await db.find({
1671
+ collection: AUTH_SESSIONS_COLLECTION,
1672
+ where: {
1673
+ userId: { equals: args.userId },
1674
+ collection: { equals: args.collection }
1675
+ },
1676
+ page,
1677
+ limit: 100
1678
+ });
1679
+ for (const session of result.docs) {
1680
+ if (session.revokedAt) continue;
1681
+ await revokeAuthSession(config, session.id);
1682
+ revoked += 1;
1683
+ }
1684
+ if (!result.hasNextPage) break;
1685
+ page += 1;
1686
+ }
1687
+ return revoked;
1688
+ }
1689
+ function createSessionId() {
1690
+ return globalThis.crypto?.randomUUID?.() ? globalThis.crypto.randomUUID() : `sess_${Date.now()}_${Math.random().toString(36).slice(2)}`;
1691
+ }
1692
+
1693
+ // src/utils/block-references.ts
1694
+ function mergeUniqueBlocks(blocks) {
1695
+ const seen = /* @__PURE__ */ new Map();
1696
+ for (const block of blocks) {
1697
+ const existing = seen.get(block.slug);
1698
+ if (existing && existing !== block) {
1699
+ throw new Error(
1700
+ `Duplicate block slug "${block.slug}" found in the reusable block registry. Block slugs must be unique.`
1701
+ );
1702
+ }
1703
+ if (!existing) seen.set(block.slug, block);
1704
+ }
1705
+ return Array.from(seen.values());
1706
+ }
1707
+ function buildRegistry(blocks) {
1708
+ return new Map(blocks.map((block) => [block.slug, block]));
1709
+ }
1710
+ function resolveField(field, registry, blockCache) {
1711
+ const next = { ...field };
1712
+ if (next.fields) {
1713
+ next.fields = next.fields.map(
1714
+ (child) => resolveField(child, registry, blockCache)
1715
+ );
1716
+ }
1717
+ if (next.type !== "blocks") return next;
1718
+ const hasInlineBlocks = Array.isArray(next.blocks) && next.blocks.length > 0;
1719
+ const hasReferences = Array.isArray(next.blockReferences) && next.blockReferences.length > 0;
1720
+ if (hasInlineBlocks && hasReferences) {
1721
+ throw new Error(
1722
+ `Blocks field "${next.name ?? "(unnamed)"}" cannot define both "blocks" and "blockReferences". Use one or the other.`
1723
+ );
1724
+ }
1725
+ if (hasReferences) {
1726
+ next.blocks = next.blockReferences.map((slug) => {
1727
+ const block = registry.get(slug);
1728
+ if (!block) {
1729
+ throw new Error(
1730
+ `Unknown block reference "${slug}" on blocks field "${next.name ?? "(unnamed)"}". Add it to defineConfig({ blocks: [...] }).`
1731
+ );
1732
+ }
1733
+ return resolveBlock(block, registry, blockCache);
1734
+ });
1735
+ return next;
1736
+ }
1737
+ if (hasInlineBlocks) {
1738
+ next.blocks = next.blocks.map(
1739
+ (block) => resolveBlock(block, registry, blockCache)
1740
+ );
1741
+ }
1742
+ return next;
1743
+ }
1744
+ function resolveBlock(block, registry, blockCache) {
1745
+ const cached = blockCache.get(block);
1746
+ if (cached) return cached;
1747
+ const resolved = {
1748
+ ...block,
1749
+ fields: []
1750
+ };
1751
+ blockCache.set(block, resolved);
1752
+ resolved.fields = block.fields.map(
1753
+ (field) => resolveField(field, registry, blockCache)
1754
+ );
1755
+ return resolved;
1756
+ }
1757
+ function resolveFields(fields, registry, blockCache) {
1758
+ return fields.map((field) => resolveField(field, registry, blockCache));
1759
+ }
1760
+ function normalizeSchemaFragment(fragment) {
1761
+ const reusableBlocks = mergeUniqueBlocks(fragment.blocks ?? []);
1762
+ const registry = buildRegistry(reusableBlocks);
1763
+ const blockCache = /* @__PURE__ */ new WeakMap();
1764
+ const resolvedBlocks = reusableBlocks.map(
1765
+ (block) => resolveBlock(block, registry, blockCache)
1766
+ );
1767
+ const resolvedCollections = (fragment.collections ?? []).map(
1768
+ (collection) => ({
1769
+ ...collection,
1770
+ fields: resolveFields(collection.fields ?? [], registry, blockCache)
1771
+ })
1772
+ );
1773
+ const resolvedGlobals = (fragment.globals ?? []).map((global) => ({
1774
+ ...global,
1775
+ fields: resolveFields(global.fields ?? [], registry, blockCache)
1776
+ }));
1777
+ return {
1778
+ ...fragment,
1779
+ ...fragment.blocks ? { blocks: resolvedBlocks } : {},
1780
+ ...fragment.collections ? { collections: resolvedCollections } : {},
1781
+ ...fragment.globals ? { globals: resolvedGlobals } : {}
1782
+ };
1783
+ }
1784
+ function mergeDynamicConfig(baseConfig, dynamic) {
1785
+ const normalizedDynamic = normalizeSchemaFragment({
1786
+ ...dynamic,
1787
+ blocks: [...baseConfig.blocks ?? [], ...dynamic.blocks ?? []]
1788
+ });
1789
+ return {
1790
+ ...baseConfig,
1791
+ ...normalizedDynamic.blocks ? { blocks: normalizedDynamic.blocks } : {},
1792
+ ...dynamic.accessPolicies ? {
1793
+ accessPolicies: {
1794
+ ...baseConfig.accessPolicies ?? {},
1795
+ ...dynamic.accessPolicies
1796
+ }
1797
+ } : {},
1798
+ ...dynamic.admin ? { admin: { ...baseConfig.admin, ...dynamic.admin } } : {},
1799
+ ...dynamic.adminAuth ? { adminAuth: { ...baseConfig.adminAuth, ...dynamic.adminAuth } } : {},
1800
+ collections: normalizedDynamic.collections ? [...baseConfig.collections, ...normalizedDynamic.collections] : baseConfig.collections,
1801
+ globals: normalizedDynamic.globals ? [...baseConfig.globals, ...normalizedDynamic.globals] : baseConfig.globals
1802
+ };
1803
+ }
1804
+
1805
+ // src/utils/config.ts
1806
+ var AUDIT_COLLECTION_SLUG = "__audit";
1807
+ var SYSTEM_FIELDS = [
1808
+ {
1809
+ name: "createdAt",
1810
+ type: "date",
1811
+ label: "Created At",
1812
+ admin: { readOnly: true, hidden: true }
1813
+ },
1814
+ {
1815
+ name: "updatedAt",
1816
+ type: "date",
1817
+ label: "Updated At",
1818
+ admin: { readOnly: true, hidden: true }
1819
+ },
1820
+ {
1821
+ name: "createdBy",
1822
+ type: "text",
1823
+ label: "Created By",
1824
+ admin: { readOnly: true, hidden: true }
1825
+ },
1826
+ {
1827
+ name: "updatedBy",
1828
+ type: "text",
1829
+ label: "Updated By",
1830
+ admin: { readOnly: true, hidden: true }
1831
+ }
1832
+ ];
1833
+ var AUDIT_COLLECTION = {
1834
+ slug: AUDIT_COLLECTION_SLUG,
1835
+ labels: { singular: "Audit Log", plural: "Audit Logs" },
1836
+ fields: [
1837
+ { name: "collection", type: "text", label: "Collection", required: true },
1838
+ { name: "documentId", type: "text", label: "Document ID" },
1839
+ {
1840
+ name: "operation",
1841
+ type: "select",
1842
+ label: "Operation",
1843
+ options: ["create", "update", "delete"],
1844
+ required: true
1845
+ },
1846
+ { name: "user", type: "text", label: "User ID" },
1847
+ { name: "timestamp", type: "date", label: "Timestamp", required: true },
1848
+ { name: "changes", type: "json", label: "Changes" }
1849
+ ],
1850
+ access: {
1851
+ read: () => false,
1852
+ create: () => false,
1853
+ update: () => false,
1854
+ delete: () => false
1855
+ },
1856
+ admin: { hidden: true }
1857
+ };
1858
+ var WORKFLOW_HISTORY_COLLECTION_CONFIG = {
1859
+ slug: WORKFLOW_HISTORY_COLLECTION,
1860
+ labels: { singular: "Workflow transition", plural: "Workflow transitions" },
1861
+ fields: [
1862
+ { name: "collection", type: "text", required: true },
1863
+ { name: "documentId", type: "text", required: true },
1864
+ { name: "transition", type: "text", required: true },
1865
+ { name: "from", type: "text", required: true },
1866
+ { name: "to", type: "text", required: true },
1867
+ { name: "revision", type: "number", required: true },
1868
+ { name: "comment", type: "textarea" },
1869
+ { name: "actorId", type: "text" },
1870
+ { name: "createdAt", type: "date", required: true }
1871
+ ],
1872
+ access: {
1873
+ read: ({ user }) => !!user,
1874
+ create: () => false,
1875
+ update: () => false,
1876
+ delete: () => false
1877
+ },
1878
+ admin: { hidden: true }
1879
+ };
1880
+ var LIFECYCLE_EVENTS_COLLECTION_CONFIG = {
1881
+ slug: LIFECYCLE_EVENTS_COLLECTION,
1882
+ labels: { singular: "Lifecycle event", plural: "Lifecycle events" },
1883
+ fields: [
1884
+ { name: "name", type: "text", required: true },
1885
+ { name: "collection", type: "text", required: true },
1886
+ { name: "documentId", type: "text", required: true },
1887
+ { name: "occurredAt", type: "date", required: true },
1888
+ { name: "actorId", type: "text" },
1889
+ { name: "payload", type: "json", required: true },
1890
+ { name: "attempts", type: "number", required: true },
1891
+ {
1892
+ name: "status",
1893
+ type: "select",
1894
+ options: ["pending", "processing", "delivered", "failed"],
1895
+ required: true
1896
+ },
1897
+ { name: "nextAttemptAt", type: "date" },
1898
+ { name: "deliveredAt", type: "date" },
1899
+ { name: "lastError", type: "textarea" }
1900
+ ],
1901
+ access: {
1902
+ read: ({ user }) => !!user?.roles?.includes("admin"),
1903
+ create: () => false,
1904
+ update: () => false,
1905
+ delete: () => false
1906
+ },
1907
+ admin: { hidden: true }
1908
+ };
1909
+ var AUTH_SESSIONS_COLLECTION_CONFIG = {
1910
+ slug: AUTH_SESSIONS_COLLECTION,
1911
+ labels: { singular: "Auth session", plural: "Auth sessions" },
1912
+ fields: [
1913
+ { name: "userId", type: "text", required: true },
1914
+ { name: "email", type: "email", required: true },
1915
+ { name: "collection", type: "text", required: true },
1916
+ { name: "authSource", type: "text" },
1917
+ { name: "providerId", type: "text" },
1918
+ { name: "lastIp", type: "text" },
1919
+ { name: "lastSeenAt", type: "date" },
1920
+ { name: "expiresAt", type: "date" },
1921
+ { name: "revokedAt", type: "date" }
1922
+ ],
1923
+ access: {
1924
+ read: () => false,
1925
+ create: () => false,
1926
+ update: () => false,
1927
+ delete: () => false
1928
+ },
1929
+ admin: { hidden: true }
1930
+ };
1931
+ function normalizeConfig(config) {
1932
+ const schemaAwareConfig = normalizeSchemaFragment(config);
1933
+ assertValidDeclarativeHooksInConfig(schemaAwareConfig, "config");
1934
+ assertValidDeclarativeAccessInConfig(schemaAwareConfig, "config");
1935
+ assertValidAdminConditionsInConfig(schemaAwareConfig, "config");
1936
+ assertValidPreviewUrlsInConfig(schemaAwareConfig, "config");
1937
+ const collections = schemaAwareConfig?.collections || [];
1938
+ const globals = schemaAwareConfig?.globals || [];
1939
+ const needsAudit = collections.some((col) => col.audit);
1940
+ const needsWorkflow = collections.some((col) => col.workflow || col.drafts);
1941
+ const needsAuthSessions = collections.some((col) => !!col.auth);
1942
+ const adminAuthCollectionSlug = getAdminAuthCollection({
1943
+ collections,
1944
+ adminAuth: schemaAwareConfig.adminAuth
1945
+ })?.slug;
1946
+ const normalizedCollections = collections.map((col) => {
1947
+ let fields = col.fields || [];
1948
+ const existingFieldNames = new Set(fields.map((f) => f.name));
1949
+ if (col.auth) {
1950
+ if (!existingFieldNames.has("email")) {
1951
+ fields = [
1952
+ ...fields,
1953
+ {
1954
+ name: "email",
1955
+ type: "email",
1956
+ label: "Email",
1957
+ required: true,
1958
+ unique: true,
1959
+ promoted: true,
1960
+ access: {
1961
+ update: "!id"
1962
+ }
1963
+ }
1964
+ ];
1965
+ }
1966
+ if (!existingFieldNames.has("password")) {
1967
+ fields = [
1968
+ ...fields,
1969
+ {
1970
+ name: "password",
1971
+ type: "text",
1972
+ label: "Password",
1973
+ required: true,
1974
+ access: {
1975
+ update: "!id || user.id == id"
1976
+ }
1977
+ }
1978
+ ];
1979
+ }
1980
+ if (!existingFieldNames.has("roles")) {
1981
+ fields = [
1982
+ ...fields,
1983
+ {
1984
+ name: "roles",
1985
+ type: "select",
1986
+ label: "Roles",
1987
+ defaultValue: [],
1988
+ options: [
1989
+ { value: "admin", label: "Admin" },
1990
+ { value: "editor", label: "Editor" },
1991
+ { value: "viewer", label: "Viewer" }
1992
+ ],
1993
+ access: {
1994
+ update: "user.roles && 'admin' in user.roles"
1995
+ }
1996
+ }
1997
+ ];
1998
+ }
1999
+ if (!existingFieldNames.has("status")) {
2000
+ fields = [
2001
+ ...fields,
2002
+ {
2003
+ name: "status",
2004
+ type: "select",
2005
+ label: "Status",
2006
+ defaultValue: "active",
2007
+ options: [
2008
+ { value: "active", label: "Active" },
2009
+ { value: "pending", label: "Pending" }
2010
+ ],
2011
+ access: {
2012
+ update: "user.roles && 'admin' in user.roles && user.id != id"
2013
+ },
2014
+ admin: {
2015
+ condition: `!(data.roles && "admin" in data.roles)`
2016
+ }
2017
+ }
2018
+ ];
2019
+ }
2020
+ fields = fields.map((field) => {
2021
+ if (field.name === "email") {
2022
+ return {
2023
+ ...field,
2024
+ // Email is the login identifier. Keep the integrity constraints
2025
+ // auth relies on even when the field is explicitly redefined, so a
2026
+ // custom `email` field can never silently drop uniqueness.
2027
+ required: true,
2028
+ unique: true,
2029
+ promoted: true,
2030
+ access: {
2031
+ ...field.access || {},
2032
+ update: "!id"
2033
+ }
2034
+ };
2035
+ }
2036
+ if (field.name === "password") {
2037
+ return {
2038
+ ...field,
2039
+ // Password is required to authenticate; enforce it regardless of
2040
+ // how the field was declared.
2041
+ required: true,
2042
+ admin: { ...field.admin || {} },
2043
+ access: {
2044
+ ...field.access || {},
2045
+ update: "!id || user.id == id"
2046
+ }
2047
+ };
2048
+ }
2049
+ if (field.name === "roles") {
2050
+ return {
2051
+ ...field,
2052
+ access: {
2053
+ ...field.access || {},
2054
+ // Must be an admin; cannot edit own roles (no self-elevation).
2055
+ update: "user.roles && 'admin' in user.roles && user.id != id"
2056
+ }
2057
+ };
2058
+ }
2059
+ if (field.name === "status") {
2060
+ return {
2061
+ ...field,
2062
+ access: {
2063
+ ...field.access || {},
2064
+ update: "user.roles && 'admin' in user.roles && user.id != id"
2065
+ }
2066
+ };
2067
+ }
2068
+ return field;
2069
+ });
2070
+ }
2071
+ if (adminAuthCollectionSlug && col.slug === adminAuthCollectionSlug && schemaAwareConfig.adminAuth?.mode === "external") {
2072
+ const externalAdminFields = [
2073
+ {
2074
+ name: "authProvider",
2075
+ type: "text",
2076
+ label: "Auth Provider",
2077
+ admin: { readOnly: true, hidden: true }
2078
+ },
2079
+ {
2080
+ name: "externalSubject",
2081
+ type: "text",
2082
+ label: "External Subject",
2083
+ admin: { readOnly: true, hidden: true }
2084
+ },
2085
+ {
2086
+ name: "authSource",
2087
+ type: "text",
2088
+ label: "Auth Source",
2089
+ admin: { readOnly: true, hidden: true }
2090
+ },
2091
+ {
2092
+ name: "lastLoginAt",
2093
+ type: "date",
2094
+ label: "Last Login At",
2095
+ admin: { readOnly: true, hidden: true }
2096
+ }
2097
+ ];
2098
+ for (const field of externalAdminFields) {
2099
+ if (!existingFieldNames.has(field.name)) {
2100
+ fields = [...fields, field];
2101
+ }
2102
+ }
2103
+ }
2104
+ const updatedFieldNames = new Set(fields.map((f) => f.name));
2105
+ const fieldsToInject = SYSTEM_FIELDS.filter((f) => !updatedFieldNames.has(f.name));
2106
+ const workflow = col.workflow || (col.drafts ? simplePublishingWorkflow() : void 0);
2107
+ return {
2108
+ ...col,
2109
+ workflow,
2110
+ fields: [...fields, ...fieldsToInject]
2111
+ };
2112
+ });
2113
+ const hasAuditCollection = normalizedCollections.some((col) => col.slug === AUDIT_COLLECTION_SLUG);
2114
+ const systemCollections = [];
2115
+ if (needsAudit && !hasAuditCollection) systemCollections.push(AUDIT_COLLECTION);
2116
+ if (needsWorkflow && !normalizedCollections.some((col) => col.slug === WORKFLOW_HISTORY_COLLECTION)) {
2117
+ systemCollections.push(WORKFLOW_HISTORY_COLLECTION_CONFIG);
2118
+ }
2119
+ if (needsWorkflow && !normalizedCollections.some((col) => col.slug === LIFECYCLE_EVENTS_COLLECTION)) {
2120
+ systemCollections.push(LIFECYCLE_EVENTS_COLLECTION_CONFIG);
2121
+ }
2122
+ if (needsAuthSessions && !normalizedCollections.some((col) => col.slug === AUTH_SESSIONS_COLLECTION)) {
2123
+ systemCollections.push(AUTH_SESSIONS_COLLECTION_CONFIG);
2124
+ }
2125
+ return {
2126
+ ...schemaAwareConfig,
2127
+ collections: [...normalizedCollections, ...systemCollections],
2128
+ globals
2129
+ };
2130
+ }
2131
+
2132
+ // src/utils/hooks.ts
2133
+ import jexl3 from "jexl";
2134
+ async function runCollectionHooks(hooks, args, options = {}) {
2135
+ if (!hooks || hooks.length === 0) {
2136
+ return args.data ?? args.doc ?? args.query ?? void 0;
2137
+ }
2138
+ const payloadKey = args.data !== void 0 ? "data" : args.doc !== void 0 ? "doc" : "query" in args ? "query" : void 0;
2139
+ let currentPayload = payloadKey === void 0 ? void 0 : args[payloadKey];
2140
+ for (const hook of hooks) {
2141
+ try {
2142
+ const hookArgs = {
2143
+ ...args,
2144
+ ...payloadKey !== void 0 ? { [payloadKey]: currentPayload } : {}
2145
+ };
2146
+ const result = typeof hook === "string" ? await (() => {
2147
+ if (options.surface) {
2148
+ assertValidDeclarativeHookExpression(
2149
+ hook,
2150
+ options.surface,
2151
+ options.path ?? options.surface
2152
+ );
2153
+ }
2154
+ return jexl3.eval(hook, hookArgs);
2155
+ })() : await hook(hookArgs);
2156
+ if (result !== void 0) {
2157
+ if (typeof hook === "string" && options.surface) {
2158
+ assertValidDeclarativeHookResult(
2159
+ result,
2160
+ options.surface,
2161
+ options.path ?? options.surface
2162
+ );
2163
+ }
2164
+ currentPayload = typeof hook === "string" && currentPayload && typeof currentPayload === "object" && !Array.isArray(currentPayload) && result && typeof result === "object" && !Array.isArray(result) ? {
2165
+ ...currentPayload,
2166
+ ...result
2167
+ } : result;
2168
+ }
2169
+ } catch (err) {
2170
+ if (options.isolated) {
2171
+ getConfigLogger(void 0, "hooks").error({
2172
+ err,
2173
+ msg: "Side-effect hook failed after a successful write"
2174
+ });
2175
+ } else {
2176
+ throw err;
2177
+ }
2178
+ }
2179
+ }
2180
+ return currentPayload;
2181
+ }
2182
+ async function executeFieldBeforeChange(fields, data, originalDoc, user, db, pathPrefix = "") {
2183
+ if (!data || typeof data !== "object") return data;
2184
+ const result = { ...data };
2185
+ for (const field of fields) {
2186
+ if (!field.name) continue;
2187
+ const fieldPath = pathPrefix ? `${pathPrefix}.${field.name}` : field.name;
2188
+ const value = result[field.name];
2189
+ const origValue = originalDoc?.[field.name];
2190
+ let updatedValue = value;
2191
+ if (field.hooks?.beforeChange) {
2192
+ for (const hook of field.hooks.beforeChange) {
2193
+ const hookArgs = {
2194
+ value: updatedValue,
2195
+ originalDoc: originalDoc ?? void 0,
2196
+ data: result,
2197
+ user,
2198
+ db
2199
+ };
2200
+ updatedValue = typeof hook === "string" ? await (() => {
2201
+ assertValidDeclarativeHookExpression(
2202
+ hook,
2203
+ "field.beforeChange",
2204
+ fieldPath
2205
+ );
2206
+ return jexl3.eval(hook, hookArgs);
2207
+ })() : await hook(hookArgs);
2208
+ }
2209
+ result[field.name] = updatedValue;
2210
+ }
2211
+ if (updatedValue !== void 0 && updatedValue !== null) {
2212
+ if (field.type === "object" && field.fields) {
2213
+ result[field.name] = await executeFieldBeforeChange(
2214
+ field.fields,
2215
+ updatedValue,
2216
+ origValue,
2217
+ user,
2218
+ db,
2219
+ fieldPath
2220
+ );
2221
+ } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
2222
+ const arrayResult = [];
2223
+ for (let i = 0; i < updatedValue.length; i++) {
2224
+ const item = updatedValue[i];
2225
+ const origItem = Array.isArray(origValue) ? origValue[i] : null;
2226
+ arrayResult.push(
2227
+ await executeFieldBeforeChange(
2228
+ field.fields,
2229
+ item,
2230
+ origItem,
2231
+ user,
2232
+ db,
2233
+ fieldPath
2234
+ )
2235
+ );
2236
+ }
2237
+ result[field.name] = arrayResult;
2238
+ } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
2239
+ const blocksResult = [];
2240
+ for (let i = 0; i < updatedValue.length; i++) {
2241
+ const blockData = updatedValue[i];
2242
+ const origBlock = Array.isArray(origValue) ? origValue[i] : null;
2243
+ const blockConfig = field.blocks.find(
2244
+ (b) => b.slug === blockData.blockType
2245
+ );
2246
+ if (blockConfig) {
2247
+ blocksResult.push(
2248
+ await executeFieldBeforeChange(
2249
+ blockConfig.fields,
2250
+ blockData,
2251
+ origBlock,
2252
+ user,
2253
+ db,
2254
+ fieldPath
2255
+ )
2256
+ );
2257
+ } else {
2258
+ blocksResult.push(blockData);
2259
+ }
2260
+ }
2261
+ result[field.name] = blocksResult;
2262
+ }
2263
+ }
2264
+ }
2265
+ return result;
2266
+ }
2267
+ async function executeFieldAfterRead(fields, doc, user, db) {
2268
+ if (!doc || typeof doc !== "object") return doc;
2269
+ const result = { ...doc };
2270
+ for (const field of fields) {
2271
+ if (!field.name) continue;
2272
+ const value = result[field.name];
2273
+ let updatedValue = value;
2274
+ if (field.hooks?.afterRead) {
2275
+ for (const hook of field.hooks.afterRead) {
2276
+ const typedHook = hook;
2277
+ const hookArgs = {
2278
+ value: updatedValue,
2279
+ doc: result,
2280
+ user,
2281
+ db
2282
+ };
2283
+ updatedValue = await typedHook(hookArgs);
2284
+ }
2285
+ result[field.name] = updatedValue;
2286
+ }
2287
+ if (updatedValue !== void 0 && updatedValue !== null) {
2288
+ if (field.type === "object" && field.fields) {
2289
+ result[field.name] = await executeFieldAfterRead(
2290
+ field.fields,
2291
+ updatedValue,
2292
+ user,
2293
+ db
2294
+ );
2295
+ } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
2296
+ const arrayResult = [];
2297
+ for (const item of updatedValue) {
2298
+ arrayResult.push(
2299
+ await executeFieldAfterRead(
2300
+ field.fields,
2301
+ item,
2302
+ user,
2303
+ db
2304
+ )
2305
+ );
2306
+ }
2307
+ result[field.name] = arrayResult;
2308
+ } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
2309
+ const blocksResult = [];
2310
+ for (const blockData of updatedValue) {
2311
+ const typedBlock = blockData;
2312
+ const blockConfig = field.blocks.find(
2313
+ (b) => b.slug === typedBlock.blockType
2314
+ );
2315
+ if (blockConfig) {
2316
+ blocksResult.push(
2317
+ await executeFieldAfterRead(
2318
+ blockConfig.fields,
2319
+ typedBlock,
2320
+ user,
2321
+ db
2322
+ )
2323
+ );
2324
+ } else {
2325
+ blocksResult.push(blockData);
2326
+ }
2327
+ }
2328
+ result[field.name] = blocksResult;
2329
+ }
2330
+ }
2331
+ }
2332
+ return result;
2333
+ }
2334
+
2335
+ // src/utils/openapi.ts
2336
+ function getCollectionLabels(collection) {
2337
+ return collection.labels || { singular: collection.slug, plural: collection.slug };
2338
+ }
2339
+ function getCollectionTag(collection) {
2340
+ return `Collection: ${getCollectionLabels(collection).plural}`;
2341
+ }
2342
+ function getGlobalTag(global) {
2343
+ return `Global: ${global.label || global.slug}`;
2344
+ }
2345
+ function generateOpenApi(config) {
2346
+ const spec = {
2347
+ openapi: "3.0.0",
2348
+ info: {
2349
+ title: "Dyrected API",
2350
+ version: "1.0.0",
2351
+ description: "Automatically generated OpenAPI specification for the Dyrected project."
2352
+ },
2353
+ components: {
2354
+ schemas: {
2355
+ WorkflowMetadata: {
2356
+ type: "object",
2357
+ required: ["state", "revision"],
2358
+ properties: {
2359
+ state: { type: "string" },
2360
+ revision: { type: "integer", minimum: 1 },
2361
+ publishedRevision: { type: "integer", minimum: 1 },
2362
+ publishedAt: { type: "string", format: "date-time" },
2363
+ publishedBy: { type: "string" },
2364
+ availableTransitions: { type: "array", items: { type: "string" } }
2365
+ }
2366
+ },
2367
+ WorkflowTransitionRequest: {
2368
+ type: "object",
2369
+ properties: {
2370
+ expectedRevision: { type: "integer", minimum: 1 },
2371
+ comment: { type: "string" }
2372
+ }
2373
+ },
2374
+ WorkflowHistoryEntry: {
2375
+ type: "object",
2376
+ required: [
2377
+ "collection",
2378
+ "documentId",
2379
+ "transition",
2380
+ "from",
2381
+ "to",
2382
+ "revision",
2383
+ "createdAt"
2384
+ ],
2385
+ properties: {
2386
+ id: { type: "string" },
2387
+ collection: { type: "string" },
2388
+ documentId: { type: "string" },
2389
+ transition: { type: "string" },
2390
+ from: { type: "string" },
2391
+ to: { type: "string" },
2392
+ revision: { type: "integer" },
2393
+ comment: { type: "string", nullable: true },
2394
+ actorId: { type: "string", nullable: true },
2395
+ createdAt: { type: "string", format: "date-time" }
2396
+ }
2397
+ },
2398
+ AuditEntry: {
2399
+ type: "object",
2400
+ required: ["collection", "operation", "timestamp"],
2401
+ properties: {
2402
+ id: { type: "string" },
2403
+ collection: { type: "string" },
2404
+ documentId: { type: "string", nullable: true },
2405
+ operation: { type: "string" },
2406
+ user: { type: "string", nullable: true },
2407
+ timestamp: { type: "string", format: "date-time" },
2408
+ changes: {
2409
+ oneOf: [
2410
+ { type: "string" },
2411
+ { type: "object", additionalProperties: true },
2412
+ { type: "null" }
2413
+ ]
2414
+ }
2415
+ }
2416
+ },
2417
+ Error: {
2418
+ type: "object",
2419
+ properties: {
2420
+ message: { type: "string" },
2421
+ errors: {
2422
+ type: "array",
2423
+ items: { type: "object", additionalProperties: true }
2424
+ }
2425
+ }
2426
+ },
2427
+ AuthCredentials: {
2428
+ type: "object",
2429
+ required: ["email", "password"],
2430
+ properties: {
2431
+ email: { type: "string", format: "email" },
2432
+ password: { type: "string" }
2433
+ }
2434
+ },
2435
+ TokenResponse: {
2436
+ type: "object",
2437
+ properties: {
2438
+ token: { type: "string" },
2439
+ user: { type: "object", additionalProperties: true }
2440
+ }
2441
+ }
2442
+ },
2443
+ securitySchemes: {
2444
+ ApiKeyAuth: {
2445
+ type: "apiKey",
2446
+ in: "header",
2447
+ name: "x-api-key"
2448
+ }
2449
+ }
2450
+ },
2451
+ paths: {},
2452
+ security: [{ ApiKeyAuth: [] }]
2453
+ };
2454
+ spec.paths["/api/schemas"] = {
2455
+ get: {
2456
+ tags: ["System"],
2457
+ summary: "Get the serialized Dyrected schema",
2458
+ security: [],
2459
+ responses: {
2460
+ 200: { description: "Collection and global schema definitions" }
2461
+ }
2462
+ }
2463
+ };
2464
+ spec.paths["/api/openapi.json"] = {
2465
+ get: {
2466
+ tags: ["System"],
2467
+ summary: "Get the OpenAPI specification",
2468
+ security: [],
2469
+ responses: { 200: { description: "OpenAPI 3.0 document" } }
2470
+ }
2471
+ };
2472
+ spec.paths["/api/docs"] = {
2473
+ get: {
2474
+ tags: ["System"],
2475
+ summary: "Open interactive API documentation",
2476
+ security: [],
2477
+ responses: { 200: { description: "Swagger UI HTML" } }
2478
+ }
2479
+ };
2480
+ spec.paths["/api/dyrected/options/{collection}/{field}"] = {
2481
+ get: {
2482
+ tags: ["System"],
2483
+ summary: "Resolve dynamic field options",
2484
+ parameters: [
2485
+ {
2486
+ name: "collection",
2487
+ in: "path",
2488
+ required: true,
2489
+ schema: { type: "string" }
2490
+ },
2491
+ {
2492
+ name: "field",
2493
+ in: "path",
2494
+ required: true,
2495
+ schema: { type: "string" }
2496
+ }
2497
+ ],
2498
+ responses: { 200: { description: "Resolved option items" } }
2499
+ }
2500
+ };
2501
+ spec.paths["/api/preferences/{key}"] = {
2502
+ get: {
2503
+ tags: ["Preferences"],
2504
+ summary: "Get an authenticated user preference",
2505
+ parameters: [
2506
+ { name: "key", in: "path", required: true, schema: { type: "string" } }
2507
+ ],
2508
+ responses: { 200: { description: "Preference value" } }
2509
+ },
2510
+ put: {
2511
+ tags: ["Preferences"],
2512
+ summary: "Set an authenticated user preference",
2513
+ parameters: [
2514
+ { name: "key", in: "path", required: true, schema: { type: "string" } }
2515
+ ],
2516
+ requestBody: {
2517
+ required: true,
2518
+ content: { "application/json": { schema: { type: "object" } } }
2519
+ },
2520
+ responses: { 200: { description: "Updated preference" } }
2521
+ }
2522
+ };
2523
+ spec.paths["/api/preview-token"] = {
2524
+ post: {
2525
+ tags: ["Preview"],
2526
+ summary: "Create a preview token",
2527
+ responses: { 200: { description: "Short-lived preview token" } }
2528
+ }
2529
+ };
2530
+ spec.paths["/api/preview-data"] = {
2531
+ get: {
2532
+ tags: ["Preview"],
2533
+ summary: "Resolve preview data from a token",
2534
+ security: [],
2535
+ parameters: [
2536
+ {
2537
+ name: "token",
2538
+ in: "query",
2539
+ required: true,
2540
+ schema: { type: "string" }
2541
+ }
2542
+ ],
2543
+ responses: { 200: { description: "Preview document data" } }
2544
+ }
2545
+ };
2546
+ spec.paths["/api/audit"] = {
2547
+ get: {
2548
+ tags: ["Audit"],
2549
+ summary: "Get audit entries across all readable audited collections",
2550
+ parameters: [
2551
+ {
2552
+ name: "limit",
2553
+ in: "query",
2554
+ schema: { type: "integer", default: 50, maximum: 100 }
2555
+ },
2556
+ { name: "page", in: "query", schema: { type: "integer", default: 1 } },
2557
+ {
2558
+ name: "where",
2559
+ in: "query",
2560
+ schema: { type: "string" },
2561
+ description: "JSON filter"
2562
+ },
2563
+ {
2564
+ name: "sort",
2565
+ in: "query",
2566
+ schema: { type: "string", default: "-timestamp" }
2567
+ }
2568
+ ],
2569
+ responses: {
2570
+ 200: {
2571
+ description: "Audit entries",
2572
+ content: {
2573
+ "application/json": {
2574
+ schema: {
2575
+ type: "object",
2576
+ properties: {
2577
+ docs: {
2578
+ type: "array",
2579
+ items: { $ref: "#/components/schemas/AuditEntry" }
2580
+ },
2581
+ total: { type: "integer" },
2582
+ limit: { type: "integer" },
2583
+ page: { type: "integer" }
2584
+ }
2585
+ }
2586
+ }
2587
+ }
2588
+ }
2589
+ }
2590
+ }
2591
+ };
2592
+ for (const collection of config.collections) {
2593
+ spec.components.schemas[collection.slug] = collectionToSchema(collection);
2594
+ }
2595
+ for (const global of config.globals) {
2596
+ spec.components.schemas[global.slug] = globalToSchema(global);
2597
+ }
2598
+ for (const collection of config.collections) {
2599
+ const slug = collection.slug;
2600
+ const path = `/api/collections/${slug}`;
2601
+ const labels = getCollectionLabels(collection);
2602
+ const collectionTag = getCollectionTag(collection);
2603
+ spec.paths[path] = {
2604
+ get: {
2605
+ tags: [collectionTag],
2606
+ summary: `Find ${labels.plural}`,
2607
+ parameters: [
2608
+ {
2609
+ name: "limit",
2610
+ in: "query",
2611
+ schema: { type: "integer", default: 10 }
2612
+ },
2613
+ {
2614
+ name: "page",
2615
+ in: "query",
2616
+ schema: { type: "integer", default: 1 }
2617
+ },
2618
+ {
2619
+ name: "where",
2620
+ in: "query",
2621
+ schema: { type: "string" },
2622
+ description: "JSON filter"
2623
+ },
2624
+ {
2625
+ name: "search",
2626
+ in: "query",
2627
+ schema: { type: "string" },
2628
+ description: "Free-text search across configured searchable fields"
2629
+ },
2630
+ {
2631
+ name: "sort",
2632
+ in: "query",
2633
+ schema: { type: "string" },
2634
+ description: "Sort field (e.g. -createdAt)"
2635
+ }
2636
+ ],
2637
+ responses: {
2638
+ 200: {
2639
+ description: "Success",
2640
+ content: {
2641
+ "application/json": {
2642
+ schema: {
2643
+ type: "object",
2644
+ properties: {
2645
+ docs: {
2646
+ type: "array",
2647
+ items: { $ref: `#/components/schemas/${slug}` }
2648
+ },
2649
+ total: { type: "integer" },
2650
+ limit: { type: "integer" },
2651
+ page: { type: "integer" }
2652
+ }
2653
+ }
2654
+ }
2655
+ }
2656
+ }
2657
+ }
2658
+ },
2659
+ post: {
2660
+ tags: [collectionTag],
2661
+ summary: `Create ${labels.singular}`,
2662
+ requestBody: {
2663
+ required: true,
2664
+ content: {
2665
+ "application/json": {
2666
+ schema: { $ref: `#/components/schemas/${slug}` }
2667
+ }
2668
+ }
2669
+ },
2670
+ responses: {
2671
+ 201: {
2672
+ description: "Created",
2673
+ content: {
2674
+ "application/json": {
2675
+ schema: { $ref: `#/components/schemas/${slug}` }
2676
+ }
2677
+ }
2678
+ }
2679
+ }
2680
+ }
2681
+ };
2682
+ spec.paths[`${path}/{id}`] = {
2683
+ get: {
2684
+ tags: [collectionTag],
2685
+ summary: `Get a single ${labels.singular}`,
2686
+ parameters: [
2687
+ {
2688
+ name: "id",
2689
+ in: "path",
2690
+ required: true,
2691
+ schema: { type: "string" }
2692
+ }
2693
+ ],
2694
+ responses: {
2695
+ 200: {
2696
+ description: "Success",
2697
+ content: {
2698
+ "application/json": {
2699
+ schema: { $ref: `#/components/schemas/${slug}` }
2700
+ }
2701
+ }
2702
+ }
2703
+ }
2704
+ },
2705
+ patch: {
2706
+ tags: [collectionTag],
2707
+ summary: `Update ${labels.singular}`,
2708
+ parameters: [
2709
+ {
2710
+ name: "id",
2711
+ in: "path",
2712
+ required: true,
2713
+ schema: { type: "string" }
2714
+ }
2715
+ ],
2716
+ requestBody: {
2717
+ required: true,
2718
+ content: {
2719
+ "application/json": {
2720
+ schema: { $ref: `#/components/schemas/${slug}` }
2721
+ }
2722
+ }
2723
+ },
2724
+ responses: {
2725
+ 200: {
2726
+ description: "Updated",
2727
+ content: {
2728
+ "application/json": {
2729
+ schema: { $ref: `#/components/schemas/${slug}` }
2730
+ }
2731
+ }
2732
+ }
2733
+ }
2734
+ },
2735
+ delete: {
2736
+ tags: [collectionTag],
2737
+ summary: `Delete ${labels.singular}`,
2738
+ parameters: [
2739
+ {
2740
+ name: "id",
2741
+ in: "path",
2742
+ required: true,
2743
+ schema: { type: "string" }
2744
+ }
2745
+ ],
2746
+ responses: {
2747
+ 204: { description: "Deleted" }
2748
+ }
2749
+ }
2750
+ };
2751
+ spec.paths[`${path}/delete-many`] = {
2752
+ delete: {
2753
+ tags: [collectionTag],
2754
+ summary: `Delete multiple ${labels.plural}`,
2755
+ requestBody: {
2756
+ required: true,
2757
+ content: {
2758
+ "application/json": {
2759
+ schema: {
2760
+ type: "object",
2761
+ required: ["ids"],
2762
+ properties: {
2763
+ ids: { type: "array", items: { type: "string" } }
2764
+ }
2765
+ }
2766
+ }
2767
+ }
2768
+ },
2769
+ responses: { 200: { description: "Deleted and failed document IDs" } }
2770
+ }
2771
+ };
2772
+ if (collection.audit) {
2773
+ spec.paths[`${path}/__audit`] = {
2774
+ get: {
2775
+ tags: [collectionTag],
2776
+ summary: `Get ${labels.singular} audit entries`,
2777
+ parameters: [
2778
+ {
2779
+ name: "limit",
2780
+ in: "query",
2781
+ schema: { type: "integer", default: 50, maximum: 100 }
2782
+ },
2783
+ {
2784
+ name: "page",
2785
+ in: "query",
2786
+ schema: { type: "integer", default: 1 }
2787
+ },
2788
+ {
2789
+ name: "where",
2790
+ in: "query",
2791
+ schema: { type: "string" },
2792
+ description: "JSON filter"
2793
+ },
2794
+ {
2795
+ name: "sort",
2796
+ in: "query",
2797
+ schema: { type: "string", default: "-timestamp" }
2798
+ }
2799
+ ],
2800
+ responses: {
2801
+ 200: {
2802
+ description: "Audit entries for this collection",
2803
+ content: {
2804
+ "application/json": {
2805
+ schema: {
2806
+ type: "object",
2807
+ properties: {
2808
+ docs: {
2809
+ type: "array",
2810
+ items: { $ref: "#/components/schemas/AuditEntry" }
2811
+ },
2812
+ total: { type: "integer" },
2813
+ limit: { type: "integer" },
2814
+ page: { type: "integer" }
2815
+ }
2816
+ }
2817
+ }
2818
+ }
2819
+ },
2820
+ 403: { description: "Collection read access denied" },
2821
+ 404: { description: "Audit is not enabled for this collection" }
2822
+ }
2823
+ }
2824
+ };
2825
+ }
2826
+ if (collection.upload) {
2827
+ spec.paths[`${path}/media`] = {
2828
+ get: {
2829
+ tags: [collectionTag],
2830
+ summary: `List ${labels.plural}`,
2831
+ responses: { 200: { description: "Paginated media documents" } }
2832
+ },
2833
+ post: {
2834
+ tags: [collectionTag],
2835
+ summary: `Upload ${labels.singular}`,
2836
+ requestBody: {
2837
+ required: true,
2838
+ content: {
2839
+ "multipart/form-data": {
2840
+ schema: {
2841
+ type: "object",
2842
+ required: ["file"],
2843
+ properties: { file: { type: "string", format: "binary" } }
2844
+ }
2845
+ }
2846
+ }
2847
+ },
2848
+ responses: { 201: { description: "Uploaded media document" } }
2849
+ }
2850
+ };
2851
+ spec.paths[`${path}/media/{filename}`] = {
2852
+ get: {
2853
+ tags: [collectionTag],
2854
+ summary: `Serve ${labels.singular} bytes`,
2855
+ parameters: [
2856
+ {
2857
+ name: "filename",
2858
+ in: "path",
2859
+ required: true,
2860
+ schema: { type: "string" }
2861
+ }
2862
+ ],
2863
+ security: [],
2864
+ responses: {
2865
+ 200: { description: "Stored file" },
2866
+ 404: { description: "File not found" }
2867
+ }
2868
+ }
2869
+ };
2870
+ }
2871
+ if (collection.auth) {
2872
+ const publicAuthPost = (summary) => ({
2873
+ tags: [collectionTag],
2874
+ summary,
2875
+ security: [],
2876
+ requestBody: {
2877
+ required: true,
2878
+ content: {
2879
+ "application/json": {
2880
+ schema: { type: "object", additionalProperties: true }
2881
+ }
2882
+ }
2883
+ },
2884
+ responses: {
2885
+ 200: { description: "Success" },
2886
+ 400: { description: "Invalid request" }
2887
+ }
2888
+ });
2889
+ spec.paths[`${path}/login`] = {
2890
+ post: {
2891
+ ...publicAuthPost(`Log in to ${labels.plural}`),
2892
+ requestBody: {
2893
+ required: true,
2894
+ content: {
2895
+ "application/json": {
2896
+ schema: { $ref: "#/components/schemas/AuthCredentials" }
2897
+ }
2898
+ }
2899
+ },
2900
+ responses: {
2901
+ 200: {
2902
+ description: "Authenticated",
2903
+ content: {
2904
+ "application/json": {
2905
+ schema: { $ref: "#/components/schemas/TokenResponse" }
2906
+ }
2907
+ }
2908
+ },
2909
+ 401: { description: "Invalid credentials" }
2910
+ }
2911
+ }
2912
+ };
2913
+ spec.paths[`${path}/logout`] = {
2914
+ post: {
2915
+ tags: [collectionTag],
2916
+ summary: `Log out of ${labels.plural}`,
2917
+ parameters: [
2918
+ {
2919
+ name: "allSessions",
2920
+ in: "query",
2921
+ required: false,
2922
+ schema: { type: "boolean" },
2923
+ description: "Revoke every active session for this account instead of only the current one."
2924
+ }
2925
+ ],
2926
+ responses: { 200: { description: "Logged out" } }
2927
+ }
2928
+ };
2929
+ spec.paths[`${path}/init`] = {
2930
+ get: {
2931
+ tags: [collectionTag],
2932
+ summary: `Get ${labels.plural} initialization state`,
2933
+ security: [],
2934
+ responses: { 200: { description: "Initialization state" } }
2935
+ }
2936
+ };
2937
+ spec.paths[`${path}/first-user`] = {
2938
+ post: publicAuthPost(`Register the first ${labels.singular}`)
2939
+ };
2940
+ spec.paths[`${path}/me`] = {
2941
+ get: {
2942
+ tags: [collectionTag],
2943
+ summary: `Get the current ${labels.singular}`,
2944
+ responses: { 200: { description: "Authenticated user" } }
2945
+ }
2946
+ };
2947
+ spec.paths[`${path}/refresh-token`] = {
2948
+ post: {
2949
+ tags: [collectionTag],
2950
+ summary: "Refresh an authentication token",
2951
+ responses: {
2952
+ 200: {
2953
+ description: "Refreshed token for the current active session"
2954
+ }
2955
+ }
2956
+ }
2957
+ };
2958
+ spec.paths[`${path}/forgot-password`] = {
2959
+ post: publicAuthPost("Request a password reset")
2960
+ };
2961
+ spec.paths[`${path}/reset-password`] = {
2962
+ post: publicAuthPost("Reset a password")
2963
+ };
2964
+ spec.paths[`${path}/invite`] = {
2965
+ post: {
2966
+ tags: [collectionTag],
2967
+ summary: `Invite a ${labels.singular}`,
2968
+ responses: { 200: { description: "Invitation sent" } }
2969
+ }
2970
+ };
2971
+ spec.paths[`${path}/accept-invite`] = {
2972
+ post: publicAuthPost("Accept an invitation")
2973
+ };
2974
+ spec.paths[`${path}/{id}/change-password`] = {
2975
+ post: {
2976
+ tags: [collectionTag],
2977
+ summary: `Change a ${labels.singular} password`,
2978
+ parameters: [
2979
+ {
2980
+ name: "id",
2981
+ in: "path",
2982
+ required: true,
2983
+ schema: { type: "string" }
2984
+ }
2985
+ ],
2986
+ responses: {
2987
+ 200: {
2988
+ description: "Password changed and active sessions revoked"
2989
+ }
2990
+ }
2991
+ }
2992
+ };
2993
+ }
2994
+ if (collection.workflow) {
2995
+ spec.paths[`${path}/{id}/transitions/{transition}`] = {
2996
+ post: {
2997
+ tags: [collectionTag],
2998
+ summary: `Transition ${labels.singular} workflow`,
2999
+ parameters: [
3000
+ {
3001
+ name: "id",
3002
+ in: "path",
3003
+ required: true,
3004
+ schema: { type: "string" }
3005
+ },
3006
+ {
3007
+ name: "transition",
3008
+ in: "path",
3009
+ required: true,
3010
+ schema: {
3011
+ type: "string",
3012
+ enum: collection.workflow.transitions.map((item) => item.name)
3013
+ }
3014
+ }
3015
+ ],
3016
+ requestBody: {
3017
+ content: {
3018
+ "application/json": {
3019
+ schema: {
3020
+ $ref: "#/components/schemas/WorkflowTransitionRequest"
3021
+ }
3022
+ }
3023
+ }
3024
+ },
3025
+ responses: {
3026
+ 200: {
3027
+ description: "Transition applied",
3028
+ content: {
3029
+ "application/json": {
3030
+ schema: { $ref: `#/components/schemas/${slug}` }
3031
+ }
3032
+ }
3033
+ },
3034
+ 400: { description: "Required transition input is missing" },
3035
+ 403: { description: "Transition capability denied" },
3036
+ 409: { description: "Invalid state or stale revision" }
3037
+ }
3038
+ }
3039
+ };
3040
+ spec.paths[`${path}/{id}/workflow-history`] = {
3041
+ get: {
3042
+ tags: [collectionTag],
3043
+ summary: `Get ${labels.singular} workflow history`,
3044
+ parameters: [
3045
+ {
3046
+ name: "id",
3047
+ in: "path",
3048
+ required: true,
3049
+ schema: { type: "string" }
3050
+ },
3051
+ {
3052
+ name: "limit",
3053
+ in: "query",
3054
+ schema: { type: "integer", default: 50, maximum: 100 }
3055
+ }
3056
+ ],
3057
+ responses: {
3058
+ 200: {
3059
+ description: "Workflow transition history",
3060
+ content: {
3061
+ "application/json": {
3062
+ schema: {
3063
+ type: "object",
3064
+ properties: {
3065
+ docs: {
3066
+ type: "array",
3067
+ items: {
3068
+ $ref: "#/components/schemas/WorkflowHistoryEntry"
3069
+ }
3070
+ },
3071
+ total: { type: "integer" },
3072
+ limit: { type: "integer" },
3073
+ page: { type: "integer" }
3074
+ }
3075
+ }
3076
+ }
3077
+ }
3078
+ },
3079
+ 403: { description: "Collection read access denied" }
3080
+ }
3081
+ }
3082
+ };
3083
+ }
3084
+ }
3085
+ for (const global of config.globals) {
3086
+ const slug = global.slug;
3087
+ const path = `/api/globals/${slug}`;
3088
+ const globalTag = getGlobalTag(global);
3089
+ spec.paths[path] = {
3090
+ get: {
3091
+ tags: [globalTag],
3092
+ summary: `Get ${global.label || slug}`,
3093
+ responses: {
3094
+ 200: {
3095
+ description: "Success",
3096
+ content: {
3097
+ "application/json": {
3098
+ schema: { $ref: `#/components/schemas/${slug}` }
3099
+ }
3100
+ }
3101
+ }
3102
+ }
3103
+ },
3104
+ patch: {
3105
+ tags: [globalTag],
3106
+ summary: `Update ${global.label || slug}`,
3107
+ requestBody: {
3108
+ required: true,
3109
+ content: {
3110
+ "application/json": {
3111
+ schema: { $ref: `#/components/schemas/${slug}` }
3112
+ }
3113
+ }
3114
+ },
3115
+ responses: {
3116
+ 200: {
3117
+ description: "Updated",
3118
+ content: {
3119
+ "application/json": {
3120
+ schema: { $ref: `#/components/schemas/${slug}` }
3121
+ }
3122
+ }
3123
+ }
3124
+ }
3125
+ }
3126
+ };
3127
+ }
3128
+ if (config.storage) {
3129
+ spec.paths["/api/media/{filename}"] = {
3130
+ get: {
3131
+ tags: ["Media"],
3132
+ summary: "Serve a stored file",
3133
+ security: [],
3134
+ parameters: [
3135
+ {
3136
+ name: "filename",
3137
+ in: "path",
3138
+ required: true,
3139
+ schema: { type: "string" }
3140
+ }
3141
+ ],
3142
+ responses: {
3143
+ 200: { description: "Stored file bytes" },
3144
+ 404: { description: "File not found" }
3145
+ }
3146
+ }
3147
+ };
3148
+ }
3149
+ return spec;
3150
+ }
3151
+ function collectionToSchema(collection) {
3152
+ const { properties, required } = fieldsToProperties(collection.fields);
3153
+ return {
3154
+ type: "object",
3155
+ properties: {
3156
+ id: { type: "string" },
3157
+ createdAt: { type: "string", format: "date-time" },
3158
+ updatedAt: { type: "string", format: "date-time" },
3159
+ ...collection.workflow ? { _workflow: { $ref: "#/components/schemas/WorkflowMetadata" } } : {},
3160
+ ...properties
3161
+ },
3162
+ required: ["id", ...required]
3163
+ };
3164
+ }
3165
+ function globalToSchema(global) {
3166
+ const { properties, required } = fieldsToProperties(global.fields);
3167
+ return {
3168
+ type: "object",
3169
+ properties,
3170
+ required
3171
+ };
3172
+ }
3173
+ function fieldsToProperties(fields) {
3174
+ const props = {};
3175
+ const required = [];
3176
+ for (const field of fields) {
3177
+ if (field.type === "row") {
3178
+ const nested = fieldsToProperties(field.fields || []);
3179
+ Object.assign(props, nested.properties);
3180
+ required.push(...nested.required);
3181
+ continue;
3182
+ }
3183
+ if (!field.name) continue;
3184
+ props[field.name] = fieldToSchema(field);
3185
+ if (field.required) {
3186
+ required.push(field.name);
3187
+ }
3188
+ }
3189
+ return { properties: props, required };
3190
+ }
3191
+ function fieldToSchema(field) {
3192
+ let schema;
3193
+ switch (field.type) {
3194
+ case "text":
3195
+ case "textarea":
3196
+ case "email":
3197
+ schema = { type: "string" };
3198
+ break;
3199
+ case "url":
3200
+ schema = {
3201
+ oneOf: [
3202
+ { type: "string" },
3203
+ { type: "object", additionalProperties: true }
3204
+ ]
3205
+ };
3206
+ break;
3207
+ case "icon":
3208
+ schema = { type: "string" };
3209
+ break;
3210
+ case "number":
3211
+ schema = { type: "number" };
3212
+ break;
3213
+ case "boolean":
3214
+ schema = { type: "boolean" };
3215
+ break;
3216
+ case "date":
3217
+ schema = { type: "string", format: "date" };
3218
+ break;
3219
+ case "datetime":
3220
+ schema = { type: "string", format: "date-time" };
3221
+ break;
3222
+ case "time":
3223
+ schema = { type: "string", format: "time" };
3224
+ break;
3225
+ case "select":
3226
+ case "radio":
3227
+ schema = {
3228
+ type: "string",
3229
+ enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
3230
+ };
3231
+ break;
3232
+ case "multiSelect":
3233
+ schema = {
3234
+ type: "array",
3235
+ items: {
3236
+ type: "string",
3237
+ enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
3238
+ }
3239
+ };
3240
+ break;
3241
+ case "relationship":
3242
+ case "image": {
3243
+ const valueSchema = {
3244
+ type: "string",
3245
+ description: `ID of a ${field.relationTo} record`
3246
+ };
3247
+ schema = field.hasMany ? { type: "array", items: valueSchema } : valueSchema;
3248
+ break;
3249
+ }
3250
+ case "join":
3251
+ schema = {
3252
+ type: "array",
3253
+ readOnly: true,
3254
+ items: { type: "object", additionalProperties: true }
3255
+ };
3256
+ break;
3257
+ case "object": {
3258
+ const { properties, required } = fieldsToProperties(field.fields || []);
3259
+ schema = { type: "object", properties, required };
3260
+ break;
3261
+ }
3262
+ case "array": {
3263
+ const { properties, required } = fieldsToProperties(field.fields || []);
3264
+ schema = {
3265
+ type: "array",
3266
+ items: { type: "object", properties, required }
3267
+ };
3268
+ break;
3269
+ }
3270
+ case "json":
3271
+ case "richText":
3272
+ schema = { type: "object", additionalProperties: true };
3273
+ break;
3274
+ case "blocks":
3275
+ schema = {
3276
+ type: "array",
3277
+ items: {
3278
+ oneOf: field.blocks?.map((block) => {
3279
+ const { properties, required } = fieldsToProperties(block.fields);
3280
+ return {
3281
+ type: "object",
3282
+ properties: {
3283
+ blockType: { type: "string", enum: [block.slug] },
3284
+ ...properties
3285
+ },
3286
+ required: ["blockType", ...required]
3287
+ };
3288
+ })
3289
+ }
3290
+ };
3291
+ break;
3292
+ default:
3293
+ schema = { type: "string" };
3294
+ }
3295
+ if (field.label) schema.description = field.label;
3296
+ return schema;
3297
+ }
3298
+
3299
+ export {
3300
+ signCollectionToken,
3301
+ verifyCollectionToken,
3302
+ issueAuthSessionToken,
3303
+ getAuthSession,
3304
+ isAuthSessionActive,
3305
+ touchAuthSession,
3306
+ revokeAuthSession,
3307
+ revokeAllAuthSessions,
3308
+ createObservabilityRuntime,
3309
+ bindObservabilityRuntime,
3310
+ getObservabilityRuntime,
3311
+ getConfigLogger,
3312
+ getRequestLogger,
3313
+ buildRequestLogger,
3314
+ shouldSampleRequest,
3315
+ redactHeaders,
3316
+ captureRequestBody,
3317
+ createRequestSpan,
3318
+ endRequestSpan,
3319
+ attachRequestMetrics,
3320
+ renderPrometheusMetrics,
3321
+ WORKFLOW_HISTORY_COLLECTION,
3322
+ LIFECYCLE_EVENTS_COLLECTION,
3323
+ definePublishingWorkflow,
3324
+ publishingWorkflow,
3325
+ simplePublishingWorkflow,
3326
+ workflowCapabilities,
3327
+ canViewWorkflowDraft,
3328
+ availableWorkflowTransitions,
3329
+ initializeWorkflowDocument,
3330
+ publishedStateName,
3331
+ materializeWorkflowDocument,
3332
+ createLifecycleEvent,
3333
+ dispatchLifecycleEvent,
3334
+ dispatchPendingLifecycleEvents,
3335
+ saveWorkflowDraft,
3336
+ createWorkflowDocument,
3337
+ transitionWorkflow,
3338
+ getAdminAuthCollection,
3339
+ resolveAdminAuthCollection,
3340
+ getPublicAdminAuthConfig,
3341
+ mergeDynamicConfig,
3342
+ validateDeclarativeHookExpression,
3343
+ validateDeclarativeAccessExpression,
3344
+ validateAdminConditionExpression,
3345
+ validatePreviewUrlExpression,
3346
+ assertValidDeclarativeHookExpression,
3347
+ assertValidDeclarativeHookResult,
3348
+ collectDeclarativeHookValidationIssues,
3349
+ collectDeclarativeAccessValidationIssues,
3350
+ collectAdminConditionValidationIssues,
3351
+ collectPreviewUrlValidationIssues,
3352
+ assertValidAdminConditionsInConfig,
3353
+ assertValidPreviewUrlsInConfig,
3354
+ collectConfigDiagnostics,
3355
+ formatConfigDiagnostics,
3356
+ ConfigValidationError,
3357
+ isConfigValidationError,
3358
+ assertValidDeclarativeHooksInConfig,
3359
+ assertValidDeclarativeAccessInConfig,
3360
+ normalizeConfig,
3361
+ runCollectionHooks,
3362
+ executeFieldBeforeChange,
3363
+ executeFieldAfterRead,
3364
+ generateOpenApi
3365
+ };