@pwfabric/embed 0.0.0-stage → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2064 @@
1
+ import * as React from 'react';
2
+ import * as ReactDOM from 'react-dom/client';
3
+ import { DataBoundSurfaceRenderer, BlockSurfaceRenderer, DynamicArtifactProvider, surfaceNeedsDataBinding, StaticConnector, createEntityFacade } from '@pwfabric/runtime';
4
+ import { isCapability } from '@pwfabric/runtime/capability';
5
+ import * as contracts_star from '@pwfabric/contracts';
6
+ import { ok, INITIAL_VERSION, parseVersion, contractId, err, validationError, defineCapability, CapabilityBuilder, validationErr, validationOk } from '@pwfabric/contracts';
7
+ import { z } from 'zod';
8
+
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget);
26
+ function needsDataBoundRenderer(surface) {
27
+ return surfaceNeedsDataBinding(surface);
28
+ }
29
+ function buildRendererProps(opts) {
30
+ const props = {};
31
+ if (opts.theme !== void 0) props.theme = opts.theme;
32
+ if (opts.viewport !== void 0) props.viewport = opts.viewport;
33
+ if (opts.capabilities !== void 0) props.capabilities = opts.capabilities;
34
+ if (opts.entityFacade !== void 0) props.entityFacade = opts.entityFacade;
35
+ if (opts.connections !== void 0) props.connections = opts.connections;
36
+ if (opts.dataServiceConfig !== void 0) props.dataServiceConfig = opts.dataServiceConfig;
37
+ if (opts.loadingStrategy !== void 0) props.loadingStrategy = opts.loadingStrategy;
38
+ if (opts.dataCache !== void 0) props.dataCache = opts.dataCache;
39
+ if (opts.interactionMode !== void 0) props.interactionMode = opts.interactionMode;
40
+ if (opts.basePath !== void 0) props.basePath = opts.basePath;
41
+ if (opts.imageAdapter !== void 0) props.imageAdapter = opts.imageAdapter;
42
+ if (opts.components !== void 0) props.components = opts.components;
43
+ if (opts.onEvent !== void 0) props.onEvent = opts.onEvent;
44
+ if (opts.gap !== void 0) props.gap = opts.gap;
45
+ if (opts.padding !== void 0) props.padding = opts.padding;
46
+ return props;
47
+ }
48
+ function missingBlockTypes(surface, dynamicBlocks, components) {
49
+ const known = /* @__PURE__ */ new Set();
50
+ for (const d of dynamicBlocks ?? []) known.add(d.blockType);
51
+ for (const k of Object.keys(components ?? {})) known.add(k);
52
+ const missing = /* @__PURE__ */ new Set();
53
+ const walk = (nodes) => {
54
+ if (!Array.isArray(nodes)) return;
55
+ for (const node of nodes) {
56
+ if (!node || typeof node !== "object") continue;
57
+ const n = node;
58
+ if (typeof n.type === "string" && n.type && !known.has(n.type)) missing.add(n.type);
59
+ walk(n.children);
60
+ }
61
+ };
62
+ walk(surface.blocks);
63
+ return [...missing];
64
+ }
65
+ function RebuildNeededBlock({ block, children }) {
66
+ return React.createElement(
67
+ "div",
68
+ {
69
+ "data-pw-rebuild-needed": block.type,
70
+ role: "note",
71
+ style: {
72
+ border: "1px dashed currentColor",
73
+ borderRadius: 6,
74
+ padding: 12,
75
+ opacity: 0.7,
76
+ fontSize: 13
77
+ }
78
+ },
79
+ React.createElement("span", null, `Rebuild needed: "${block.type}" is not in this preview yet.`),
80
+ children ?? null
81
+ );
82
+ }
83
+ function withPlaceholders(opts) {
84
+ if (!opts.placeholderMissingBlocks) return opts.components;
85
+ const missing = missingBlockTypes(opts.surface, opts.dynamicBlocks, opts.components);
86
+ if (missing.length === 0) return opts.components;
87
+ const added = Object.fromEntries(missing.map((t) => [t, RebuildNeededBlock]));
88
+ return { ...added, ...opts.components ?? {} };
89
+ }
90
+ function createSurfaceElement(opts) {
91
+ const useDataBound = needsDataBoundRenderer(opts.surface) || opts.connections != null;
92
+ const components = withPlaceholders(opts);
93
+ const shared = buildRendererProps(components && components !== opts.components ? { ...opts, components } : opts);
94
+ const rendererElement = useDataBound ? React.createElement(DataBoundSurfaceRenderer, {
95
+ surface: opts.surface,
96
+ ...shared
97
+ }) : React.createElement(BlockSurfaceRenderer, {
98
+ surface: opts.surface,
99
+ ...shared
100
+ });
101
+ return React.createElement(
102
+ DynamicArtifactProvider,
103
+ {
104
+ ...opts.dynamicBlocks && opts.dynamicBlocks.length > 0 ? { dynamicBlocks: opts.dynamicBlocks } : {},
105
+ ...opts.dynamicStarters && opts.dynamicStarters.length > 0 ? { dynamicStarters: opts.dynamicStarters } : {},
106
+ children: rendererElement
107
+ }
108
+ );
109
+ }
110
+ function resolveTarget(target) {
111
+ if (typeof target === "string") {
112
+ const el = document.querySelector(target);
113
+ if (!el) {
114
+ throw new Error(`[pwfabric-embed] target not found: ${target}`);
115
+ }
116
+ return el;
117
+ }
118
+ return target;
119
+ }
120
+ function mountSurface(target, opts, mountOptions) {
121
+ const container = resolveTarget(target);
122
+ const root = mountOptions?.hydrate ? ReactDOM.hydrateRoot(container, createSurfaceElement(opts)) : ReactDOM.createRoot(container);
123
+ if (!mountOptions?.hydrate) root.render(createSurfaceElement(opts));
124
+ return {
125
+ container,
126
+ unmount() {
127
+ root.unmount();
128
+ },
129
+ render(newOpts) {
130
+ root.render(createSurfaceElement(newOpts));
131
+ }
132
+ };
133
+ }
134
+ function createOfflineEntityFacade(seeds) {
135
+ const connector = new StaticConnector("offline");
136
+ const facade = createEntityFacade();
137
+ facade.connectors.register(connector);
138
+ if (seeds) {
139
+ for (const seed of seeds) {
140
+ facade.registerEntity(seed.definition, connector.name);
141
+ if (seed.records) {
142
+ for (const record of seed.records) {
143
+ void connector.create(seed.definition.id, record);
144
+ }
145
+ }
146
+ }
147
+ }
148
+ return facade;
149
+ }
150
+ function createOfflineNavigationProvider(options = {}) {
151
+ const basePath = options.basePath ?? "";
152
+ return {
153
+ type: "navigation",
154
+ data: {
155
+ mode: "offline",
156
+ basePath,
157
+ /** Resolve a href against the base path; absolute/anchor hrefs pass through. */
158
+ resolve(href) {
159
+ if (/^([a-z]+:)?\/\//i.test(href) || href.startsWith("#")) return href;
160
+ return `${basePath}${href}`;
161
+ },
162
+ /** No-op push — offline embeds have no history stack. */
163
+ push() {
164
+ }
165
+ }
166
+ };
167
+ }
168
+ function staticPersistenceCapability(data, initialState) {
169
+ const dataSources = Object.entries(data).map(([id, staticData]) => ({
170
+ id,
171
+ kind: "static",
172
+ staticData
173
+ }));
174
+ return {
175
+ type: "data",
176
+ capability: "platform/persistence",
177
+ config: {
178
+ dataSources,
179
+ ...initialState ? { initialState } : {}
180
+ }
181
+ };
182
+ }
183
+ function surfaceDeclares(surface, capability) {
184
+ return (surface.capabilities ?? []).some((c) => isCapability(c, capability));
185
+ }
186
+ function resolveOfflineCapabilities(opts) {
187
+ const capabilities = [...opts.capabilities ?? []];
188
+ if (surfaceDeclares(opts.surface, "platform/navigation") && !capabilities.some((c) => c.type === "navigation")) {
189
+ capabilities.push(
190
+ createOfflineNavigationProvider(opts.basePath ? { basePath: opts.basePath } : {})
191
+ );
192
+ }
193
+ let entityFacade = opts.entityFacade;
194
+ if (!entityFacade && surfaceDeclares(opts.surface, "platform/entities")) {
195
+ entityFacade = createOfflineEntityFacade();
196
+ }
197
+ return { capabilities, entityFacade };
198
+ }
199
+ function fatCoreOptions(opts) {
200
+ const { capabilities, entityFacade } = resolveOfflineCapabilities(opts);
201
+ const surface = opts.appearance ? { ...opts.surface, appearance: opts.appearance } : opts.surface;
202
+ return {
203
+ surface,
204
+ ...opts.blocks ? { dynamicBlocks: opts.blocks } : {},
205
+ ...capabilities.length > 0 ? { capabilities } : {},
206
+ ...entityFacade ? { entityFacade } : {},
207
+ ...opts.connections ? { connections: opts.connections } : {},
208
+ // A HAND-COPIED LIST. `RenderFatOptions` declares this and
209
+ // `RenderCoreOptions` accepts it; this line is the copy between them.
210
+ // Without it a pwapp visitor signs in, the gate lifts, and every data
211
+ // request still goes out anonymous — `getAccessToken` is never called
212
+ // because the DataService has no config.
213
+ ...opts.dataServiceConfig ? { dataServiceConfig: opts.dataServiceConfig } : {},
214
+ ...opts.loadingStrategy !== void 0 ? { loadingStrategy: opts.loadingStrategy } : {},
215
+ ...opts.dataCache !== void 0 ? { dataCache: opts.dataCache } : {},
216
+ ...opts.theme !== void 0 ? { theme: opts.theme } : {},
217
+ ...opts.viewport !== void 0 ? { viewport: opts.viewport } : {},
218
+ ...opts.interactionMode !== void 0 ? { interactionMode: opts.interactionMode } : {},
219
+ ...opts.basePath !== void 0 ? { basePath: opts.basePath } : {},
220
+ ...opts.imageAdapter !== void 0 ? { imageAdapter: opts.imageAdapter } : {},
221
+ ...opts.components !== void 0 ? { components: opts.components } : {},
222
+ ...opts.onEvent !== void 0 ? { onEvent: opts.onEvent } : {},
223
+ ...opts.gap !== void 0 ? { gap: opts.gap } : {},
224
+ ...opts.padding !== void 0 ? { padding: opts.padding } : {},
225
+ ...opts.placeholderMissingBlocks !== void 0 ? { placeholderMissingBlocks: opts.placeholderMissingBlocks } : {}
226
+ };
227
+ }
228
+ function renderFat(target, opts) {
229
+ const core = fatCoreOptions(opts);
230
+ const handle = mountSurface(target, core, opts.hydrate ? { hydrate: true } : void 0);
231
+ const firstFacade = core.entityFacade;
232
+ return {
233
+ container: handle.container,
234
+ unmount: () => handle.unmount(),
235
+ render: (next) => handle.render(next),
236
+ update(next) {
237
+ const withFacade = !next.entityFacade && firstFacade ? { ...next, entityFacade: firstFacade } : next;
238
+ handle.render(fatCoreOptions(withFacade));
239
+ }
240
+ };
241
+ }
242
+
243
+ // ../core/dist/index.js
244
+ var dist_exports = {};
245
+ __export(dist_exports, {
246
+ AppError: () => AppError,
247
+ BLOCK_CATEGORIES: () => BLOCK_CATEGORIES,
248
+ BLOCK_HOST_IMPORTS: () => BLOCK_HOST_IMPORTS,
249
+ BREAKPOINTS: () => BREAKPOINTS,
250
+ BREAKPOINT_ORDER: () => BREAKPOINT_ORDER,
251
+ CapabilityBuilder: () => CapabilityBuilder,
252
+ ConfigSchemaBuilder: () => ConfigSchemaBuilder,
253
+ ConsoleLogger: () => ConsoleLogger,
254
+ ContractBuilder: () => ContractBuilder,
255
+ CoreValidationError: () => ValidationError,
256
+ DEFAULT_BLOCK_LAYOUT: () => DEFAULT_BLOCK_LAYOUT,
257
+ DEFAULT_BUDGET: () => DEFAULT_BUDGET,
258
+ EditorAppError: () => EditorAppError,
259
+ ErrorCode: () => ErrorCode,
260
+ FieldBuilder: () => FieldBuilder,
261
+ ForbiddenError: () => ForbiddenError,
262
+ Logger: () => Logger,
263
+ MAX_NESTING_DEPTH: () => MAX_NESTING_DEPTH,
264
+ NetworkAppError: () => NetworkAppError,
265
+ NotFoundError: () => NotFoundError,
266
+ PWFabricError: () => PWFabricError,
267
+ SimpleConfigSchema: () => SimpleConfigSchema,
268
+ SimpleStateMachine: () => SimpleStateMachine,
269
+ SimpleStateStore: () => SimpleStateStore,
270
+ UnauthorizedError: () => UnauthorizedError,
271
+ VIEWPORT_PRESETS: () => VIEWPORT_PRESETS,
272
+ ValidationAppError: () => ValidationAppError,
273
+ anySchema: () => anySchema,
274
+ blockBundleExternals: () => blockBundleExternals,
275
+ blockHostGlobals: () => blockHostGlobals,
276
+ blockImportMap: () => blockImportMap,
277
+ blockLayoutSchema: () => blockLayoutSchema,
278
+ blockShimFiles: () => blockShimFiles,
279
+ computed: () => computed,
280
+ createChildContext: () => createChildContext,
281
+ createLogger: () => createLogger,
282
+ createMetricsState: () => createMetricsState,
283
+ createObservabilityLogger: () => createObservabilityLogger,
284
+ createSpan: () => createSpan,
285
+ createStateMachine: () => createStateMachine,
286
+ createStateStore: () => createStateStore,
287
+ createTraceContext: () => createTraceContext,
288
+ defineCapability: () => defineCapability,
289
+ defineConfigSchema: () => defineConfigSchema,
290
+ defineContract: () => defineContract,
291
+ extractTraceId: () => extractTraceId,
292
+ generateId: () => generateId2,
293
+ getBreakpointForWidth: () => getBreakpointForWidth,
294
+ getColumnsAtBreakpoint: () => getColumnsAtBreakpoint,
295
+ getHttpStatus: () => getHttpStatus,
296
+ getRating: () => getRating,
297
+ injectTraceId: () => injectTraceId,
298
+ isRetryable: () => isRetryable,
299
+ isScopeToken: () => isScopeToken,
300
+ objectSchema: () => objectSchema,
301
+ observeAllWebVitals: () => observeAllWebVitals,
302
+ observeCLS: () => observeCLS,
303
+ observeFCP: () => observeFCP,
304
+ observeFID: () => observeFID,
305
+ observeINP: () => observeINP,
306
+ observeLCP: () => observeLCP,
307
+ observeTTFB: () => observeTTFB,
308
+ passthroughContract: () => passthroughContract,
309
+ readScopeList: () => readScopeList,
310
+ resolveResponsiveValue: () => resolveResponsiveValue,
311
+ resolveSpanAtBreakpoint: () => resolveSpanAtBreakpoint,
312
+ responsiveBooleanSchema: () => responsiveBooleanSchema,
313
+ responsiveNumberSchema: () => responsiveNumberSchema,
314
+ retry: () => retry,
315
+ sleep: () => sleep,
316
+ specifiersForShim: () => specifiersForShim,
317
+ subscribeToSlice: () => subscribeToSlice,
318
+ unseededHostGlobals: () => unseededHostGlobals
319
+ });
320
+ __reExport(dist_exports, contracts_star);
321
+
322
+ // ../core/dist/errors.js
323
+ var PWFabricError = class extends Error {
324
+ code;
325
+ timestamp;
326
+ constructor(message, code, options) {
327
+ super(message, options);
328
+ this.name = "PWFabricError";
329
+ this.code = code;
330
+ this.timestamp = /* @__PURE__ */ new Date();
331
+ }
332
+ };
333
+ var ValidationError = class extends PWFabricError {
334
+ field;
335
+ constructor(message, field, options) {
336
+ super(message, "VALIDATION_ERROR", options);
337
+ this.name = "ValidationError";
338
+ this.field = field;
339
+ }
340
+ };
341
+ var NotFoundError = class extends PWFabricError {
342
+ resource;
343
+ constructor(resource, options) {
344
+ super(`${resource} not found`, "NOT_FOUND", options);
345
+ this.name = "NotFoundError";
346
+ this.resource = resource;
347
+ }
348
+ };
349
+ var UnauthorizedError = class extends PWFabricError {
350
+ constructor(message = "Unauthorized", options) {
351
+ super(message, "UNAUTHORIZED", options);
352
+ this.name = "UnauthorizedError";
353
+ }
354
+ };
355
+ var ForbiddenError = class extends PWFabricError {
356
+ constructor(message = "Forbidden", options) {
357
+ super(message, "FORBIDDEN", options);
358
+ this.name = "ForbiddenError";
359
+ }
360
+ };
361
+
362
+ // ../core/dist/logger.js
363
+ var Logger = class _Logger {
364
+ name;
365
+ minLevel;
366
+ static levels = {
367
+ debug: 0,
368
+ info: 1,
369
+ warn: 2,
370
+ error: 3
371
+ };
372
+ constructor(name, minLevel = "info") {
373
+ this.name = name;
374
+ this.minLevel = minLevel;
375
+ }
376
+ shouldLog(level) {
377
+ return _Logger.levels[level] >= _Logger.levels[this.minLevel];
378
+ }
379
+ log(level, message, context) {
380
+ if (!this.shouldLog(level))
381
+ return;
382
+ const entry = {
383
+ timestamp: /* @__PURE__ */ new Date()};
384
+ const output = `[${entry.timestamp.toISOString()}] [${level.toUpperCase()}] [${this.name}] ${message}`;
385
+ if (level === "error") {
386
+ console.error(output, context ?? "");
387
+ } else if (level === "warn") {
388
+ console.warn(output, context ?? "");
389
+ } else {
390
+ process.stdout.write(output + (context ? ` ${JSON.stringify(context)}` : "") + "\n");
391
+ }
392
+ }
393
+ debug(message, context) {
394
+ this.log("debug", message, context);
395
+ }
396
+ info(message, context) {
397
+ this.log("info", message, context);
398
+ }
399
+ warn(message, context) {
400
+ this.log("warn", message, context);
401
+ }
402
+ error(message, context) {
403
+ this.log("error", message, context);
404
+ }
405
+ child(name) {
406
+ return new _Logger(`${this.name}:${name}`, this.minLevel);
407
+ }
408
+ };
409
+ function createLogger(name, level) {
410
+ return new Logger(name, level);
411
+ }
412
+
413
+ // ../core/dist/errors/ErrorCode.js
414
+ var ErrorCode = {
415
+ // Validation errors (1xxx)
416
+ VALIDATION_FAILED: "VALIDATION_FAILED",
417
+ INVALID_INPUT: "INVALID_INPUT",
418
+ MISSING_REQUIRED: "MISSING_REQUIRED",
419
+ INVALID_FORMAT: "INVALID_FORMAT",
420
+ // Network errors (2xxx)
421
+ NETWORK_ERROR: "NETWORK_ERROR",
422
+ TIMEOUT: "TIMEOUT",
423
+ CONNECTION_FAILED: "CONNECTION_FAILED",
424
+ REQUEST_FAILED: "REQUEST_FAILED",
425
+ // Authentication errors (3xxx)
426
+ UNAUTHORIZED: "UNAUTHORIZED",
427
+ FORBIDDEN: "FORBIDDEN",
428
+ TOKEN_EXPIRED: "TOKEN_EXPIRED",
429
+ INVALID_CREDENTIALS: "INVALID_CREDENTIALS",
430
+ // Resource errors (4xxx)
431
+ NOT_FOUND: "NOT_FOUND",
432
+ ALREADY_EXISTS: "ALREADY_EXISTS",
433
+ CONFLICT: "CONFLICT",
434
+ GONE: "GONE",
435
+ // Runtime errors (5xxx)
436
+ RUNTIME_ERROR: "RUNTIME_ERROR",
437
+ INTERNAL_ERROR: "INTERNAL_ERROR",
438
+ SERVICE_UNAVAILABLE: "SERVICE_UNAVAILABLE",
439
+ NOT_IMPLEMENTED: "NOT_IMPLEMENTED",
440
+ // Editor errors (6xxx)
441
+ EDITOR_ERROR: "EDITOR_ERROR",
442
+ BLOCK_NOT_FOUND: "BLOCK_NOT_FOUND",
443
+ INVALID_OPERATION: "INVALID_OPERATION",
444
+ RENDER_ERROR: "RENDER_ERROR"
445
+ };
446
+ function getHttpStatus(code) {
447
+ switch (code) {
448
+ case ErrorCode.VALIDATION_FAILED:
449
+ case ErrorCode.INVALID_INPUT:
450
+ case ErrorCode.MISSING_REQUIRED:
451
+ case ErrorCode.INVALID_FORMAT:
452
+ return 400;
453
+ case ErrorCode.UNAUTHORIZED:
454
+ case ErrorCode.TOKEN_EXPIRED:
455
+ case ErrorCode.INVALID_CREDENTIALS:
456
+ return 401;
457
+ case ErrorCode.FORBIDDEN:
458
+ return 403;
459
+ case ErrorCode.NOT_FOUND:
460
+ case ErrorCode.BLOCK_NOT_FOUND:
461
+ case ErrorCode.GONE:
462
+ return 404;
463
+ case ErrorCode.CONFLICT:
464
+ case ErrorCode.ALREADY_EXISTS:
465
+ return 409;
466
+ case ErrorCode.TIMEOUT:
467
+ return 408;
468
+ case ErrorCode.SERVICE_UNAVAILABLE:
469
+ return 503;
470
+ case ErrorCode.NOT_IMPLEMENTED:
471
+ return 501;
472
+ default:
473
+ return 500;
474
+ }
475
+ }
476
+ function isRetryable(code) {
477
+ const retryableCodes = [
478
+ ErrorCode.NETWORK_ERROR,
479
+ ErrorCode.TIMEOUT,
480
+ ErrorCode.CONNECTION_FAILED,
481
+ ErrorCode.SERVICE_UNAVAILABLE
482
+ ];
483
+ return retryableCodes.includes(code);
484
+ }
485
+
486
+ // ../core/dist/errors/AppError.js
487
+ var AppError = class _AppError extends Error {
488
+ code;
489
+ timestamp;
490
+ context;
491
+ isRetryable;
492
+ httpStatus;
493
+ constructor(code, message, options) {
494
+ super(message, { cause: options?.cause });
495
+ this.name = "AppError";
496
+ this.code = code;
497
+ this.timestamp = /* @__PURE__ */ new Date();
498
+ this.context = options?.context;
499
+ this.isRetryable = isRetryable(code);
500
+ this.httpStatus = getHttpStatus(code);
501
+ }
502
+ /**
503
+ * Serialize error for API response
504
+ */
505
+ toJSON(traceId) {
506
+ return {
507
+ code: this.code,
508
+ message: this.message,
509
+ timestamp: this.timestamp.toISOString(),
510
+ ...traceId && { traceId },
511
+ ...this.context && { context: this.context }
512
+ };
513
+ }
514
+ /**
515
+ * Create error from unknown value
516
+ */
517
+ static from(error, code = "RUNTIME_ERROR") {
518
+ if (error instanceof _AppError) {
519
+ return error;
520
+ }
521
+ if (error instanceof Error) {
522
+ return new _AppError(code, error.message, { cause: error });
523
+ }
524
+ return new _AppError(code, String(error));
525
+ }
526
+ };
527
+ var ValidationAppError = class extends AppError {
528
+ field;
529
+ constructor(message, options) {
530
+ const baseOptions = {};
531
+ if (options?.cause) {
532
+ baseOptions.cause = options.cause;
533
+ }
534
+ if (options?.context || options?.field) {
535
+ baseOptions.context = { ...options?.context, field: options?.field };
536
+ }
537
+ super("VALIDATION_FAILED", message, baseOptions);
538
+ this.name = "ValidationAppError";
539
+ this.field = options?.field;
540
+ }
541
+ };
542
+ var NetworkAppError = class extends AppError {
543
+ url;
544
+ statusCode;
545
+ constructor(message, options) {
546
+ const baseOptions = {};
547
+ if (options?.cause) {
548
+ baseOptions.cause = options.cause;
549
+ }
550
+ if (options?.context || options?.url || options?.statusCode) {
551
+ baseOptions.context = {
552
+ ...options?.context,
553
+ url: options?.url,
554
+ statusCode: options?.statusCode
555
+ };
556
+ }
557
+ super("NETWORK_ERROR", message, baseOptions);
558
+ this.name = "NetworkAppError";
559
+ this.url = options?.url;
560
+ this.statusCode = options?.statusCode;
561
+ }
562
+ };
563
+ var EditorAppError = class extends AppError {
564
+ blockId;
565
+ operation;
566
+ constructor(message, options) {
567
+ const baseOptions = {};
568
+ if (options?.cause) {
569
+ baseOptions.cause = options.cause;
570
+ }
571
+ if (options?.context || options?.blockId || options?.operation) {
572
+ baseOptions.context = {
573
+ ...options?.context,
574
+ blockId: options?.blockId,
575
+ operation: options?.operation
576
+ };
577
+ }
578
+ super(options?.code ?? "EDITOR_ERROR", message, baseOptions);
579
+ this.name = "EditorAppError";
580
+ this.blockId = options?.blockId;
581
+ this.operation = options?.operation;
582
+ }
583
+ };
584
+
585
+ // ../core/dist/monitoring/metrics.js
586
+ var DEFAULT_BUDGET = {
587
+ LCP: 2500,
588
+ // 2.5s
589
+ FID: 100,
590
+ // 100ms
591
+ CLS: 0.1,
592
+ // 0.1
593
+ TTFB: 800,
594
+ // 800ms
595
+ INP: 200
596
+ // 200ms
597
+ };
598
+ function createMetricsState(budget = {}) {
599
+ return {
600
+ webVitals: {
601
+ LCP: null,
602
+ FID: null,
603
+ CLS: null,
604
+ TTFB: null,
605
+ INP: null,
606
+ FCP: null
607
+ },
608
+ timings: [],
609
+ renders: [],
610
+ budget: { ...DEFAULT_BUDGET, ...budget }
611
+ };
612
+ }
613
+ function getRating(name, value) {
614
+ const thresholds = {
615
+ LCP: [2500, 4e3],
616
+ FID: [100, 300],
617
+ CLS: [0.1, 0.25],
618
+ TTFB: [800, 1800],
619
+ INP: [200, 500],
620
+ FCP: [1800, 3e3]
621
+ };
622
+ const [good, poor] = thresholds[name];
623
+ if (value <= good)
624
+ return "good";
625
+ if (value <= poor)
626
+ return "needs-improvement";
627
+ return "poor";
628
+ }
629
+
630
+ // ../core/dist/monitoring/web-vitals.js
631
+ function createWebVitalMetric(name, value, delta, entries) {
632
+ return {
633
+ name,
634
+ value,
635
+ delta,
636
+ rating: getRating(name, value),
637
+ timestamp: Date.now(),
638
+ entries
639
+ };
640
+ }
641
+ function observeLCP(callback) {
642
+ if (typeof PerformanceObserver === "undefined")
643
+ return void 0;
644
+ let lastValue = 0;
645
+ const entries = [];
646
+ const observer = new PerformanceObserver((list) => {
647
+ for (const entry of list.getEntries()) {
648
+ const lcpEntry = entry;
649
+ entries.push(entry);
650
+ const value = lcpEntry.startTime;
651
+ const delta = value - lastValue;
652
+ lastValue = value;
653
+ callback(createWebVitalMetric("LCP", value, delta, [...entries]));
654
+ }
655
+ });
656
+ try {
657
+ observer.observe({ type: "largest-contentful-paint", buffered: true });
658
+ return () => observer.disconnect();
659
+ } catch {
660
+ return void 0;
661
+ }
662
+ }
663
+ function observeFID(callback) {
664
+ if (typeof PerformanceObserver === "undefined")
665
+ return void 0;
666
+ const entries = [];
667
+ const observer = new PerformanceObserver((list) => {
668
+ for (const entry of list.getEntries()) {
669
+ const fidEntry = entry;
670
+ entries.push(entry);
671
+ const value = fidEntry.processingStart - fidEntry.startTime;
672
+ callback(createWebVitalMetric("FID", value, value, [...entries]));
673
+ }
674
+ });
675
+ try {
676
+ observer.observe({ type: "first-input", buffered: true });
677
+ return () => observer.disconnect();
678
+ } catch {
679
+ return void 0;
680
+ }
681
+ }
682
+ function observeCLS(callback) {
683
+ if (typeof PerformanceObserver === "undefined")
684
+ return void 0;
685
+ let clsValue = 0;
686
+ const entries = [];
687
+ const observer = new PerformanceObserver((list) => {
688
+ for (const entry of list.getEntries()) {
689
+ const layoutShift = entry;
690
+ if (!layoutShift.hadRecentInput) {
691
+ const delta = layoutShift.value;
692
+ clsValue += delta;
693
+ entries.push(entry);
694
+ callback(createWebVitalMetric("CLS", clsValue, delta, [...entries]));
695
+ }
696
+ }
697
+ });
698
+ try {
699
+ observer.observe({ type: "layout-shift", buffered: true });
700
+ return () => observer.disconnect();
701
+ } catch {
702
+ return void 0;
703
+ }
704
+ }
705
+ function observeTTFB(callback) {
706
+ if (typeof window === "undefined" || typeof performance === "undefined")
707
+ return;
708
+ const navigationEntry = performance.getEntriesByType("navigation")[0];
709
+ if (navigationEntry) {
710
+ const value = navigationEntry.responseStart - navigationEntry.requestStart;
711
+ callback(createWebVitalMetric("TTFB", value, value, [navigationEntry]));
712
+ }
713
+ }
714
+ function observeINP(callback) {
715
+ if (typeof PerformanceObserver === "undefined")
716
+ return void 0;
717
+ let maxINP = 0;
718
+ const entries = [];
719
+ const observer = new PerformanceObserver((list) => {
720
+ for (const entry of list.getEntries()) {
721
+ const eventEntry = entry;
722
+ const duration = eventEntry.duration;
723
+ if (duration > maxINP) {
724
+ maxINP = duration;
725
+ entries.push(entry);
726
+ callback(createWebVitalMetric("INP", duration, duration, [...entries]));
727
+ }
728
+ }
729
+ });
730
+ try {
731
+ observer.observe({ type: "event", buffered: true });
732
+ return () => observer.disconnect();
733
+ } catch {
734
+ return void 0;
735
+ }
736
+ }
737
+ function observeFCP(callback) {
738
+ if (typeof PerformanceObserver === "undefined")
739
+ return void 0;
740
+ const entries = [];
741
+ const observer = new PerformanceObserver((list) => {
742
+ for (const entry of list.getEntries()) {
743
+ if (entry.name === "first-contentful-paint") {
744
+ entries.push(entry);
745
+ const value = entry.startTime;
746
+ callback(createWebVitalMetric("FCP", value, value, [...entries]));
747
+ }
748
+ }
749
+ });
750
+ try {
751
+ observer.observe({ type: "paint", buffered: true });
752
+ return () => observer.disconnect();
753
+ } catch {
754
+ return void 0;
755
+ }
756
+ }
757
+ function observeAllWebVitals(callback) {
758
+ const cleanups = [];
759
+ cleanups.push(observeLCP(callback));
760
+ cleanups.push(observeFID(callback));
761
+ cleanups.push(observeCLS(callback));
762
+ cleanups.push(observeINP(callback));
763
+ cleanups.push(observeFCP(callback));
764
+ observeTTFB(callback);
765
+ return () => {
766
+ for (const cleanup of cleanups) {
767
+ cleanup?.();
768
+ }
769
+ };
770
+ }
771
+
772
+ // ../core/dist/observability/logger.js
773
+ var LOG_LEVELS = {
774
+ debug: 0,
775
+ info: 1,
776
+ warn: 2,
777
+ error: 3
778
+ };
779
+ function isProduction() {
780
+ if (typeof process !== "undefined" && process.env) {
781
+ return false;
782
+ }
783
+ return false;
784
+ }
785
+ var ConsoleLogger = class _ConsoleLogger {
786
+ name;
787
+ minLevel;
788
+ production;
789
+ constructor(name, minLevel = "info") {
790
+ this.name = name;
791
+ this.minLevel = minLevel;
792
+ this.production = isProduction();
793
+ }
794
+ shouldLog(level) {
795
+ return LOG_LEVELS[level] >= LOG_LEVELS[this.minLevel];
796
+ }
797
+ formatEntry(level, message, context) {
798
+ return {
799
+ level,
800
+ message,
801
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
802
+ name: this.name,
803
+ ...context && { context }
804
+ };
805
+ }
806
+ log(level, message, context) {
807
+ if (!this.shouldLog(level))
808
+ return;
809
+ const entry = this.formatEntry(level, message, context);
810
+ if (this.production) {
811
+ const output = JSON.stringify(entry);
812
+ if (level === "error") {
813
+ console.error(output);
814
+ } else if (level === "warn") {
815
+ console.warn(output);
816
+ } else {
817
+ console.log(output);
818
+ }
819
+ } else {
820
+ const prefix = `[${entry.timestamp}] [${level.toUpperCase()}] [${this.name}]`;
821
+ const output = `${prefix} ${message}`;
822
+ if (level === "error") {
823
+ console.error(output, context ?? "");
824
+ } else if (level === "warn") {
825
+ console.warn(output, context ?? "");
826
+ } else {
827
+ console.log(output, context ?? "");
828
+ }
829
+ }
830
+ }
831
+ debug(message, context) {
832
+ this.log("debug", message, context);
833
+ }
834
+ info(message, context) {
835
+ this.log("info", message, context);
836
+ }
837
+ warn(message, context) {
838
+ this.log("warn", message, context);
839
+ }
840
+ error(message, context) {
841
+ this.log("error", message, context);
842
+ }
843
+ child(name) {
844
+ return new _ConsoleLogger(`${this.name}:${name}`, this.minLevel);
845
+ }
846
+ };
847
+ function createObservabilityLogger(name, minLevel) {
848
+ return new ConsoleLogger(name, minLevel);
849
+ }
850
+
851
+ // ../core/dist/observability/tracer.js
852
+ function generateId() {
853
+ const bytes = new Uint8Array(16);
854
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
855
+ crypto.getRandomValues(bytes);
856
+ } else {
857
+ for (let i = 0; i < bytes.length; i++) {
858
+ bytes[i] = Math.floor(Math.random() * 256);
859
+ }
860
+ }
861
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
862
+ }
863
+ function createTraceContext(parentSpanId) {
864
+ const context = {
865
+ traceId: generateId(),
866
+ spanId: generateId().slice(0, 16),
867
+ startTime: Date.now()
868
+ };
869
+ if (parentSpanId !== void 0) {
870
+ return { ...context, parentSpanId };
871
+ }
872
+ return context;
873
+ }
874
+ function createChildContext(parent) {
875
+ return {
876
+ traceId: parent.traceId,
877
+ spanId: generateId().slice(0, 16),
878
+ parentSpanId: parent.spanId,
879
+ startTime: Date.now()
880
+ };
881
+ }
882
+ function createSpan(name, parentContext) {
883
+ const context = parentContext ? createChildContext(parentContext) : createTraceContext();
884
+ const startTime = performance.now();
885
+ return {
886
+ context,
887
+ name,
888
+ startTime,
889
+ end() {
890
+ const endTime = performance.now();
891
+ return {
892
+ context,
893
+ name,
894
+ startTime,
895
+ endTime,
896
+ duration: endTime - startTime
897
+ };
898
+ }
899
+ };
900
+ }
901
+ function extractTraceId(headers) {
902
+ if (headers instanceof Headers) {
903
+ return headers.get("x-trace-id") ?? void 0;
904
+ }
905
+ return headers["x-trace-id"];
906
+ }
907
+ function injectTraceId(headers, traceId) {
908
+ if (headers instanceof Headers) {
909
+ headers.set("x-trace-id", traceId);
910
+ } else {
911
+ headers["x-trace-id"] = traceId;
912
+ }
913
+ }
914
+
915
+ // ../core/dist/utils.js
916
+ function sleep(ms) {
917
+ return new Promise((resolve) => setTimeout(resolve, ms));
918
+ }
919
+ async function retry(fn, options = {}) {
920
+ const { maxAttempts = 3, initialDelay = 1e3, maxDelay = 3e4, backoffFactor = 2 } = options;
921
+ let lastError;
922
+ let delay = initialDelay;
923
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
924
+ try {
925
+ return await fn();
926
+ } catch (error) {
927
+ lastError = error instanceof Error ? error : new Error(String(error));
928
+ if (attempt === maxAttempts) {
929
+ throw lastError;
930
+ }
931
+ await sleep(delay);
932
+ delay = Math.min(delay * backoffFactor, maxDelay);
933
+ }
934
+ }
935
+ throw lastError;
936
+ }
937
+ function generateId2() {
938
+ return crypto.randomUUID();
939
+ }
940
+ var SimpleSchema = class {
941
+ definition;
942
+ validator;
943
+ constructor(definition, validator) {
944
+ this.definition = definition;
945
+ this.validator = validator;
946
+ }
947
+ validate(data) {
948
+ return this.validator(data);
949
+ }
950
+ parse(data) {
951
+ const result = this.validate(data);
952
+ if (result.success) {
953
+ return result.data;
954
+ }
955
+ throw new Error(`Validation failed: ${JSON.stringify(result.error)}`);
956
+ }
957
+ safeParse(data) {
958
+ return this.validate(data);
959
+ }
960
+ toJsonSchema() {
961
+ return { type: "object" };
962
+ }
963
+ };
964
+ function anySchema() {
965
+ return new SimpleSchema({ type: "unknown" }, (data) => ok(data));
966
+ }
967
+ function objectSchema() {
968
+ return new SimpleSchema({ type: "object", properties: {}, required: [] }, (data) => {
969
+ if (typeof data !== "object" || data === null) {
970
+ return err([validationError([], "Expected object", "type_error")]);
971
+ }
972
+ return ok(data);
973
+ });
974
+ }
975
+ var SimpleContract = class {
976
+ id;
977
+ version;
978
+ metadata;
979
+ input;
980
+ output;
981
+ errors;
982
+ constructor(config) {
983
+ this.id = config.id;
984
+ this.version = config.version;
985
+ this.metadata = config.metadata;
986
+ this.input = config.input;
987
+ this.output = config.output;
988
+ this.errors = config.errors ?? [];
989
+ }
990
+ validateInput(data) {
991
+ return this.input.validate(data);
992
+ }
993
+ validateOutput(data) {
994
+ return this.output.validate(data);
995
+ }
996
+ validateError(data) {
997
+ for (const schema of this.errors) {
998
+ const result = schema.validate(data);
999
+ if (result.success) {
1000
+ return result;
1001
+ }
1002
+ }
1003
+ return err([validationError([], "Unknown error type", "unknown_error")]);
1004
+ }
1005
+ serialize() {
1006
+ return {
1007
+ id: this.id,
1008
+ version: `${this.version.major}.${this.version.minor}.${this.version.patch}`,
1009
+ metadata: this.metadata,
1010
+ input: {
1011
+ version: "1.0.0",
1012
+ definition: this.input.definition,
1013
+ jsonSchema: this.input.toJsonSchema()
1014
+ },
1015
+ output: {
1016
+ version: "1.0.0",
1017
+ definition: this.output.definition,
1018
+ jsonSchema: this.output.toJsonSchema()
1019
+ },
1020
+ errors: this.errors.map((e) => ({
1021
+ version: "1.0.0",
1022
+ definition: e.definition,
1023
+ jsonSchema: e.toJsonSchema()
1024
+ }))
1025
+ };
1026
+ }
1027
+ };
1028
+ var ContractBuilder = class {
1029
+ _id = "";
1030
+ _version = "0.1.0";
1031
+ _name = "";
1032
+ _description;
1033
+ _state = "draft";
1034
+ _tags;
1035
+ _inputSchema = anySchema();
1036
+ _outputSchema = anySchema();
1037
+ /**
1038
+ * Set the contract ID
1039
+ */
1040
+ id(id) {
1041
+ this._id = id;
1042
+ return this;
1043
+ }
1044
+ /**
1045
+ * Set the contract version
1046
+ */
1047
+ version(version) {
1048
+ this._version = version;
1049
+ return this;
1050
+ }
1051
+ /**
1052
+ * Set the contract name
1053
+ */
1054
+ name(name) {
1055
+ this._name = name;
1056
+ return this;
1057
+ }
1058
+ /**
1059
+ * Set the contract description
1060
+ */
1061
+ description(description) {
1062
+ this._description = description;
1063
+ return this;
1064
+ }
1065
+ /**
1066
+ * Set the contract state
1067
+ */
1068
+ state(state) {
1069
+ this._state = state;
1070
+ return this;
1071
+ }
1072
+ /**
1073
+ * Set the contract tags
1074
+ */
1075
+ tags(tags) {
1076
+ this._tags = tags;
1077
+ return this;
1078
+ }
1079
+ /**
1080
+ * Set the input schema
1081
+ */
1082
+ input(schema) {
1083
+ const builder = this;
1084
+ builder._inputSchema = schema;
1085
+ return builder;
1086
+ }
1087
+ /**
1088
+ * Set the output schema
1089
+ */
1090
+ output(schema) {
1091
+ const builder = this;
1092
+ builder._outputSchema = schema;
1093
+ return builder;
1094
+ }
1095
+ /**
1096
+ * Build the contract
1097
+ */
1098
+ build() {
1099
+ if (!this._id) {
1100
+ throw new Error("Contract ID is required");
1101
+ }
1102
+ if (!this._name) {
1103
+ throw new Error("Contract name is required");
1104
+ }
1105
+ const metadata = {
1106
+ name: this._name,
1107
+ state: this._state
1108
+ };
1109
+ if (this._description !== void 0) {
1110
+ metadata.description = this._description;
1111
+ }
1112
+ if (this._tags !== void 0) {
1113
+ metadata.tags = this._tags;
1114
+ }
1115
+ return new SimpleContract({
1116
+ id: contractId(this._id),
1117
+ version: parseVersion(this._version) ?? INITIAL_VERSION,
1118
+ metadata,
1119
+ input: this._inputSchema,
1120
+ output: this._outputSchema
1121
+ });
1122
+ }
1123
+ };
1124
+ function defineContract() {
1125
+ return new ContractBuilder();
1126
+ }
1127
+
1128
+ // ../core/dist/contracts/passthrough.js
1129
+ var passthroughContract = defineContract().id("platform/passthrough").name("Platform Passthrough").description("Passthrough contract for platform capability declarations").state("stable").input(anySchema()).output(anySchema()).build();
1130
+
1131
+ // ../core/dist/oauth-scopes.js
1132
+ var FORBIDDEN_IN_SCOPE = /[\s"'[\]{},\\]/;
1133
+ function isScopeToken(token) {
1134
+ return typeof token === "string" && token.length > 0 && !FORBIDDEN_IN_SCOPE.test(token);
1135
+ }
1136
+ var EMPTY = { scopes: [], rejected: [], malformed: false };
1137
+ function readScopeList(value) {
1138
+ if (value === void 0 || value === null)
1139
+ return EMPTY;
1140
+ if (!Array.isArray(value)) {
1141
+ return { scopes: [], rejected: [safeShow(value)], malformed: true };
1142
+ }
1143
+ const scopes = [];
1144
+ const rejected = [];
1145
+ const seen = /* @__PURE__ */ new Set();
1146
+ for (const entry of value) {
1147
+ if (isScopeToken(entry)) {
1148
+ if (!seen.has(entry)) {
1149
+ seen.add(entry);
1150
+ scopes.push(entry);
1151
+ }
1152
+ } else {
1153
+ rejected.push(safeShow(entry));
1154
+ }
1155
+ }
1156
+ return { scopes, rejected, malformed: false };
1157
+ }
1158
+ function safeShow(value) {
1159
+ try {
1160
+ return typeof value === "string" ? value : String(value);
1161
+ } catch {
1162
+ return Object.prototype.toString.call(value);
1163
+ }
1164
+ }
1165
+ var FieldBuilder = class {
1166
+ _type = "string";
1167
+ _required = false;
1168
+ _defaultValue;
1169
+ _label = "";
1170
+ _description;
1171
+ _sensitive;
1172
+ _options;
1173
+ _constraints;
1174
+ string() {
1175
+ this._type = "string";
1176
+ return this;
1177
+ }
1178
+ number() {
1179
+ this._type = "number";
1180
+ return this;
1181
+ }
1182
+ boolean() {
1183
+ this._type = "boolean";
1184
+ return this;
1185
+ }
1186
+ select(options) {
1187
+ this._type = "select";
1188
+ this._options = options.map((o) => typeof o === "string" ? { value: o, label: o } : o);
1189
+ return this;
1190
+ }
1191
+ multiSelect(options) {
1192
+ this._type = "multi-select";
1193
+ this._options = options.map((o) => typeof o === "string" ? { value: o, label: o } : o);
1194
+ return this;
1195
+ }
1196
+ url() {
1197
+ this._type = "url";
1198
+ return this;
1199
+ }
1200
+ email() {
1201
+ this._type = "email";
1202
+ return this;
1203
+ }
1204
+ json() {
1205
+ this._type = "json";
1206
+ return this;
1207
+ }
1208
+ required() {
1209
+ this._required = true;
1210
+ return this;
1211
+ }
1212
+ default(value) {
1213
+ this._defaultValue = value;
1214
+ return this;
1215
+ }
1216
+ label(s) {
1217
+ this._label = s;
1218
+ return this;
1219
+ }
1220
+ description(s) {
1221
+ this._description = s;
1222
+ return this;
1223
+ }
1224
+ sensitive() {
1225
+ this._sensitive = true;
1226
+ return this;
1227
+ }
1228
+ min(n) {
1229
+ this._constraints = { ...this._constraints, min: n };
1230
+ return this;
1231
+ }
1232
+ max(n) {
1233
+ this._constraints = { ...this._constraints, max: n };
1234
+ return this;
1235
+ }
1236
+ pattern(s, msg) {
1237
+ this._constraints = { ...this._constraints, pattern: s };
1238
+ if (msg) {
1239
+ this._constraints = { ...this._constraints, patternMessage: msg };
1240
+ }
1241
+ return this;
1242
+ }
1243
+ /** @internal */
1244
+ _build(key, group, order) {
1245
+ const def = {
1246
+ key,
1247
+ type: this._type,
1248
+ required: this._required,
1249
+ label: this._label || key,
1250
+ ...this._defaultValue !== void 0 ? { defaultValue: this._defaultValue } : {},
1251
+ ...this._description !== void 0 ? { description: this._description } : {},
1252
+ ...group !== void 0 ? { group } : {},
1253
+ ...order !== 0 ? { order } : {},
1254
+ ...this._sensitive === true ? { sensitive: true } : {},
1255
+ ...this._options !== void 0 ? { options: this._options } : {},
1256
+ ...this._constraints !== void 0 ? { constraints: this._constraints } : {}
1257
+ };
1258
+ return def;
1259
+ }
1260
+ };
1261
+ var ConfigSchemaBuilder = class {
1262
+ _fields = [];
1263
+ field(key, factory) {
1264
+ this._fields.push({ key, factory });
1265
+ return this;
1266
+ }
1267
+ group(name, groupFn) {
1268
+ const gb = new ConfigSchemaGroupBuilder(name);
1269
+ groupFn(gb);
1270
+ this._fields.push(...gb._getFields());
1271
+ return this;
1272
+ }
1273
+ build() {
1274
+ const fields = this._fields.map((pf, idx) => {
1275
+ const fb = new FieldBuilder();
1276
+ pf.factory(fb);
1277
+ return fb._build(pf.key, pf.group, idx);
1278
+ });
1279
+ return new SimpleConfigSchema(fields);
1280
+ }
1281
+ };
1282
+ var ConfigSchemaGroupBuilder = class {
1283
+ _fields = [];
1284
+ _name;
1285
+ constructor(name) {
1286
+ this._name = name;
1287
+ }
1288
+ field(key, factory) {
1289
+ this._fields.push({ key, factory, group: this._name });
1290
+ return this;
1291
+ }
1292
+ /** @internal */
1293
+ _getFields() {
1294
+ return this._fields;
1295
+ }
1296
+ };
1297
+ var SimpleConfigSchema = class {
1298
+ fields;
1299
+ constructor(fields) {
1300
+ this.fields = fields;
1301
+ }
1302
+ validate(data) {
1303
+ const errors = [];
1304
+ const record = typeof data === "object" && data !== null ? data : {};
1305
+ for (const field of this.fields) {
1306
+ const value = record[field.key];
1307
+ if (value === void 0 || value === null || value === "") {
1308
+ if (field.required && field.defaultValue === void 0) {
1309
+ errors.push(validationError([field.key], `${field.label} is required`, "required"));
1310
+ }
1311
+ continue;
1312
+ }
1313
+ const typeError = this.validateType(field, value);
1314
+ if (typeError) {
1315
+ errors.push(validationError([field.key], typeError, "type"));
1316
+ continue;
1317
+ }
1318
+ if (field.constraints) {
1319
+ const constraintError = this.validateConstraints(field, value);
1320
+ if (constraintError) {
1321
+ errors.push(validationError([field.key], constraintError, "constraint"));
1322
+ }
1323
+ }
1324
+ }
1325
+ if (errors.length > 0) {
1326
+ return validationErr(errors);
1327
+ }
1328
+ return validationOk(record);
1329
+ }
1330
+ applyDefaults(partial) {
1331
+ const result = { ...partial };
1332
+ for (const field of this.fields) {
1333
+ if (result[field.key] === void 0 && field.defaultValue !== void 0) {
1334
+ result[field.key] = field.defaultValue;
1335
+ }
1336
+ }
1337
+ return result;
1338
+ }
1339
+ validateType(field, value) {
1340
+ switch (field.type) {
1341
+ case "string":
1342
+ case "url":
1343
+ case "email":
1344
+ case "json":
1345
+ if (typeof value !== "string") {
1346
+ return `${field.label} must be a string`;
1347
+ }
1348
+ break;
1349
+ case "number":
1350
+ if (typeof value !== "number") {
1351
+ return `${field.label} must be a number`;
1352
+ }
1353
+ break;
1354
+ case "boolean":
1355
+ if (typeof value !== "boolean") {
1356
+ return `${field.label} must be a boolean`;
1357
+ }
1358
+ break;
1359
+ case "select":
1360
+ if (typeof value !== "string") {
1361
+ return `${field.label} must be a string`;
1362
+ }
1363
+ if (field.options && !field.options.some((o) => o.value === value)) {
1364
+ return `${field.label} must be one of: ${field.options.map((o) => o.value).join(", ")}`;
1365
+ }
1366
+ break;
1367
+ case "multi-select":
1368
+ if (!Array.isArray(value)) {
1369
+ return `${field.label} must be an array`;
1370
+ }
1371
+ if (field.options) {
1372
+ const valid = new Set(field.options.map((o) => o.value));
1373
+ for (const v of value) {
1374
+ if (typeof v !== "string" || !valid.has(v)) {
1375
+ return `${field.label} contains invalid option: ${String(v)}`;
1376
+ }
1377
+ }
1378
+ }
1379
+ break;
1380
+ }
1381
+ return null;
1382
+ }
1383
+ validateConstraints(field, value) {
1384
+ const c = field.constraints;
1385
+ if (!c)
1386
+ return null;
1387
+ if (typeof value === "number") {
1388
+ if (c.min !== void 0 && value < c.min) {
1389
+ return `${field.label} must be at least ${String(c.min)}`;
1390
+ }
1391
+ if (c.max !== void 0 && value > c.max) {
1392
+ return `${field.label} must be at most ${String(c.max)}`;
1393
+ }
1394
+ }
1395
+ if (typeof value === "string" && c.pattern) {
1396
+ if (!new RegExp(c.pattern).test(value)) {
1397
+ return c.patternMessage ?? `${field.label} does not match the required pattern`;
1398
+ }
1399
+ }
1400
+ return null;
1401
+ }
1402
+ };
1403
+ function defineConfigSchema() {
1404
+ return new ConfigSchemaBuilder();
1405
+ }
1406
+
1407
+ // ../core/dist/state.js
1408
+ var SimpleStateStore = class {
1409
+ state;
1410
+ version = 0;
1411
+ listeners = /* @__PURE__ */ new Set();
1412
+ constructor(initialState) {
1413
+ this.state = { ...initialState };
1414
+ }
1415
+ getState() {
1416
+ return { ...this.state };
1417
+ }
1418
+ setState(newState) {
1419
+ const oldState = this.state;
1420
+ this.state = { ...newState };
1421
+ this.version++;
1422
+ this.notifyListeners(this.state, oldState);
1423
+ }
1424
+ updateState(partial) {
1425
+ const oldState = this.state;
1426
+ this.state = { ...this.state, ...partial };
1427
+ this.version++;
1428
+ this.notifyListeners(this.state, oldState);
1429
+ }
1430
+ subscribe(listener) {
1431
+ this.listeners.add(listener);
1432
+ return () => {
1433
+ this.listeners.delete(listener);
1434
+ };
1435
+ }
1436
+ snapshot() {
1437
+ return {
1438
+ state: this.getState(),
1439
+ timestamp: Date.now(),
1440
+ version: this.version
1441
+ };
1442
+ }
1443
+ notifyListeners(newState, oldState) {
1444
+ for (const listener of this.listeners) {
1445
+ try {
1446
+ listener(newState, oldState);
1447
+ } catch {
1448
+ }
1449
+ }
1450
+ }
1451
+ };
1452
+ function createStateStore(initialState) {
1453
+ return new SimpleStateStore(initialState);
1454
+ }
1455
+ function computed(store, selector) {
1456
+ return () => selector(store.getState());
1457
+ }
1458
+ function subscribeToSlice(store, selector, listener) {
1459
+ let previousValue = selector(store.getState());
1460
+ return store.subscribe((newState, oldState) => {
1461
+ const newValue = selector(newState);
1462
+ const oldValue = selector(oldState);
1463
+ if (newValue !== oldValue) {
1464
+ listener(newValue, previousValue);
1465
+ previousValue = newValue;
1466
+ }
1467
+ });
1468
+ }
1469
+ var SimpleStateMachine = class {
1470
+ state;
1471
+ transitions;
1472
+ listeners = /* @__PURE__ */ new Set();
1473
+ constructor(config) {
1474
+ this.state = config.initial;
1475
+ this.transitions = config.transitions;
1476
+ }
1477
+ getState() {
1478
+ return this.state;
1479
+ }
1480
+ can(event) {
1481
+ const transition = this.findTransition(event);
1482
+ if (!transition)
1483
+ return false;
1484
+ if (transition.guard && !transition.guard())
1485
+ return false;
1486
+ return true;
1487
+ }
1488
+ dispatch(event) {
1489
+ const transition = this.findTransition(event);
1490
+ if (!transition)
1491
+ return false;
1492
+ if (transition.guard && !transition.guard())
1493
+ return false;
1494
+ const oldState = this.state;
1495
+ this.state = transition.to;
1496
+ if (transition.action) {
1497
+ transition.action();
1498
+ }
1499
+ this.notifyListeners(this.state, oldState);
1500
+ return true;
1501
+ }
1502
+ subscribe(listener) {
1503
+ this.listeners.add(listener);
1504
+ return () => {
1505
+ this.listeners.delete(listener);
1506
+ };
1507
+ }
1508
+ findTransition(event) {
1509
+ return this.transitions.find((t) => t.from === this.state && t.event === event);
1510
+ }
1511
+ notifyListeners(newState, oldState) {
1512
+ for (const listener of this.listeners) {
1513
+ try {
1514
+ listener(newState, oldState);
1515
+ } catch {
1516
+ }
1517
+ }
1518
+ }
1519
+ };
1520
+ function createStateMachine(config) {
1521
+ return new SimpleStateMachine(config);
1522
+ }
1523
+
1524
+ // ../core/dist/blocks/types.js
1525
+ var MAX_NESTING_DEPTH = 10;
1526
+ var BLOCK_CATEGORIES = [
1527
+ "layout",
1528
+ "panel",
1529
+ "text",
1530
+ "data",
1531
+ "control",
1532
+ "media",
1533
+ "form",
1534
+ // Last in display order: status and notification chrome, not content.
1535
+ "feedback"
1536
+ ];
1537
+ var BREAKPOINTS = [
1538
+ { name: "xs", minWidth: 0, columns: 4, label: "Mobile" },
1539
+ { name: "sm", minWidth: 640, columns: 8, label: "Mobile Landscape" },
1540
+ { name: "md", minWidth: 768, columns: 8, label: "Tablet" },
1541
+ { name: "lg", minWidth: 1024, columns: 12, label: "Desktop" },
1542
+ { name: "xl", minWidth: 1280, columns: 12, label: "Large Desktop" },
1543
+ { name: "2xl", minWidth: 1536, columns: 12, label: "Extra Large" }
1544
+ ];
1545
+ var BREAKPOINT_ORDER = [
1546
+ "xs",
1547
+ "sm",
1548
+ "md",
1549
+ "lg",
1550
+ "xl",
1551
+ "2xl"
1552
+ ];
1553
+ var DEFAULT_BLOCK_LAYOUT = {
1554
+ span: { xs: 4, sm: 8, md: 8, lg: 12 }
1555
+ };
1556
+ var VIEWPORT_PRESETS = {
1557
+ xs: { width: 375, height: "auto" },
1558
+ sm: { width: 640, height: "auto" },
1559
+ md: { width: 768, height: "auto" },
1560
+ lg: { width: 1024, height: "auto" },
1561
+ xl: { width: 1280, height: "auto" },
1562
+ "2xl": { width: 1536, height: "auto" }
1563
+ };
1564
+ var responsiveNumberSchema = z.object({
1565
+ xs: z.number().int().min(0).optional(),
1566
+ sm: z.number().int().min(0).optional(),
1567
+ md: z.number().int().min(0).optional(),
1568
+ lg: z.number().int().min(0).optional(),
1569
+ xl: z.number().int().min(0).optional(),
1570
+ "2xl": z.number().int().min(0).optional()
1571
+ }).strict();
1572
+ var responsiveBooleanSchema = z.object({
1573
+ xs: z.boolean().optional(),
1574
+ sm: z.boolean().optional(),
1575
+ md: z.boolean().optional(),
1576
+ lg: z.boolean().optional(),
1577
+ xl: z.boolean().optional(),
1578
+ "2xl": z.boolean().optional()
1579
+ }).strict();
1580
+ var breakpointNameSchema = z.enum(["xs", "sm", "md", "lg", "xl", "2xl"]);
1581
+ var widthScopeSchema = z.enum(["container", "viewport"]);
1582
+ var responsiveWidthScopeSchema = z.object({
1583
+ xs: widthScopeSchema.optional(),
1584
+ sm: widthScopeSchema.optional(),
1585
+ md: widthScopeSchema.optional(),
1586
+ lg: widthScopeSchema.optional(),
1587
+ xl: widthScopeSchema.optional(),
1588
+ "2xl": widthScopeSchema.optional()
1589
+ }).strict();
1590
+ var blockLayoutSchema = z.object({
1591
+ span: responsiveNumberSchema,
1592
+ offset: responsiveNumberSchema.optional(),
1593
+ order: responsiveNumberSchema.optional(),
1594
+ hidden: responsiveBooleanSchema.optional(),
1595
+ hideOn: z.array(breakpointNameSchema).optional(),
1596
+ showOn: z.array(breakpointNameSchema).optional(),
1597
+ widthScope: responsiveWidthScopeSchema.optional()
1598
+ });
1599
+ function resolveResponsiveValue(responsive, breakpoint) {
1600
+ if (!responsive)
1601
+ return void 0;
1602
+ const targetIndex = BREAKPOINT_ORDER.indexOf(breakpoint);
1603
+ for (let i = targetIndex; i >= 0; i--) {
1604
+ const bp = BREAKPOINT_ORDER[i];
1605
+ if (!bp)
1606
+ continue;
1607
+ if (responsive[bp] !== void 0) {
1608
+ return responsive[bp];
1609
+ }
1610
+ }
1611
+ return void 0;
1612
+ }
1613
+ function resolveSpanAtBreakpoint(layout, breakpoint) {
1614
+ const span = resolveResponsiveValue(layout.span, breakpoint);
1615
+ if (span !== void 0)
1616
+ return span;
1617
+ const bpDef = BREAKPOINTS.find((bp) => bp.name === breakpoint);
1618
+ return bpDef?.columns ?? 12;
1619
+ }
1620
+ function getColumnsAtBreakpoint(breakpoint) {
1621
+ const bpDef = BREAKPOINTS.find((bp) => bp.name === breakpoint);
1622
+ return bpDef?.columns ?? 12;
1623
+ }
1624
+ function getBreakpointForWidth(width) {
1625
+ for (let i = BREAKPOINTS.length - 1; i >= 0; i--) {
1626
+ const bp = BREAKPOINTS[i];
1627
+ if (bp && width >= bp.minWidth) {
1628
+ return bp.name;
1629
+ }
1630
+ }
1631
+ return "xs";
1632
+ }
1633
+
1634
+ // ../core/dist/blocks/host-imports.js
1635
+ var BLOCK_HOST_IMPORTS = [
1636
+ {
1637
+ specifier: "react",
1638
+ kind: "global",
1639
+ global: "__pwfabric_react",
1640
+ seeding: "every-host",
1641
+ shim: "react.mjs",
1642
+ reason: `One dispatcher. A second React instance makes every hook in a block throw "Cannot read properties of null (reading 'useState')".`
1643
+ },
1644
+ {
1645
+ specifier: "react/jsx-runtime",
1646
+ kind: "global",
1647
+ global: "__pwfabric_jsx_runtime",
1648
+ seeding: "every-host",
1649
+ shim: "react-jsx-runtime.mjs",
1650
+ reason: "The automatic JSX transform emits imports from here; it must be the same React. NOTE the global is `__pwfabric_jsx_runtime`, not `\u2026_react_jsx_runtime`; the shim and the seeders read this name."
1651
+ },
1652
+ {
1653
+ specifier: "react-dom",
1654
+ kind: "global",
1655
+ global: "__pwfabric_react_dom",
1656
+ seeding: "unseeded",
1657
+ shim: "react-dom.mjs",
1658
+ reason: "Blocks that portal or measure reach for react-dom; same-instance rule as React."
1659
+ },
1660
+ {
1661
+ specifier: "@pwfabric/runtime",
1662
+ kind: "global",
1663
+ global: "__pwfabric_runtime",
1664
+ seeding: "every-host",
1665
+ shim: "runtime.mjs",
1666
+ reason: "Surface event bus, surface id and connections contexts. A block reading a second context emits into nothing."
1667
+ },
1668
+ {
1669
+ specifier: "@pwfabric/runtime/data",
1670
+ kind: "global",
1671
+ global: "__pwfabric_runtime",
1672
+ seeding: "every-host",
1673
+ shim: "runtime.mjs",
1674
+ reason: "A runtime subpath the package root re-exports WHOLESALE, so the root shim serves it exactly \u2014 the foundation pack persistence capability imports `createDataService` from here. An import map resolves exact specifiers only: without this entry the import would compile with a HOST_SUBPATH_IMPORT warning and then fail to resolve in the browser. Only subpaths whose every export the root also exports may join; the runtime package has a test that says so."
1675
+ },
1676
+ {
1677
+ specifier: "@pwfabric/runtime/capability",
1678
+ kind: "global",
1679
+ global: "__pwfabric_runtime",
1680
+ seeding: "every-host",
1681
+ shim: "runtime.mjs",
1682
+ reason: "A runtime subpath the package root re-exports WHOLESALE, so the root shim serves it exactly \u2014 capability atoms import their definition helpers from here. An import map resolves exact specifiers only: without this entry the import would compile with a HOST_SUBPATH_IMPORT warning and then fail to resolve in the browser. Only subpaths whose every export the root also exports may join; the runtime package has a test that says so."
1683
+ },
1684
+ {
1685
+ specifier: "@pwfabric/runtime/adapters",
1686
+ kind: "global",
1687
+ global: "__pwfabric_runtime",
1688
+ seeding: "every-host",
1689
+ shim: "runtime.mjs",
1690
+ reason: "A runtime subpath the package root re-exports WHOLESALE, so the root shim serves it exactly \u2014 image adapters; a block that renders a responsive image reaches for them here. An import map resolves exact specifiers only: without this entry the import would compile with a HOST_SUBPATH_IMPORT warning and then fail to resolve in the browser. Only subpaths whose every export the root also exports may join; the runtime package has a test that says so."
1691
+ },
1692
+ {
1693
+ specifier: "@pwfabric/contracts",
1694
+ kind: "global",
1695
+ global: "__pwfabric_contracts",
1696
+ seeding: "every-host",
1697
+ shim: "contracts.mjs",
1698
+ reason: "Contract VALUES (enums, constants) must be the host\u2019s, not a second copy."
1699
+ },
1700
+ {
1701
+ specifier: "@pwfabric/core",
1702
+ kind: "global",
1703
+ global: "__pwfabric_core",
1704
+ seeding: "unseeded",
1705
+ shim: "core.mjs",
1706
+ reason: "Block layout helpers and breakpoint constants blocks resolve at render time."
1707
+ },
1708
+ {
1709
+ specifier: "@pwfabric/authoring",
1710
+ kind: "global",
1711
+ global: "__pwfabric_sdk",
1712
+ seeding: "app-host",
1713
+ shim: "sdk@v1.mjs",
1714
+ reason: "What the scaffolding emits and a third-party author reads first. A host that does not map it breaks every block that follows the documented path."
1715
+ },
1716
+ {
1717
+ specifier: "zod",
1718
+ kind: "global",
1719
+ global: "__pwfabric_zod",
1720
+ seeding: "every-host",
1721
+ shim: "zod.mjs",
1722
+ reason: "Every block with a prop schema imports it as a value \u2014 81 pack source files take `z`. Shared, not inlined: `zod.mjs` re-exports the host instance, and introspection depends on it being the real zod so `instanceof` holds while walking a schema."
1723
+ }
1724
+ ];
1725
+ function blockBundleExternals() {
1726
+ return BLOCK_HOST_IMPORTS.map((i) => i.specifier);
1727
+ }
1728
+ function blockImportMap(shimBase) {
1729
+ const imports = {};
1730
+ for (const entry of BLOCK_HOST_IMPORTS) {
1731
+ imports[entry.specifier] = `${shimBase}/${entry.shim}`;
1732
+ }
1733
+ return { imports };
1734
+ }
1735
+ function blockShimFiles() {
1736
+ return [...new Set(BLOCK_HOST_IMPORTS.map((i) => i.shim))].sort();
1737
+ }
1738
+ function blockHostGlobals(host = "app-host") {
1739
+ const wanted = host === "standalone" ? ["every-host"] : ["every-host", "app-host"];
1740
+ return [
1741
+ ...new Set(BLOCK_HOST_IMPORTS.flatMap((i) => i.global && i.seeding && wanted.includes(i.seeding) ? [i.global] : []))
1742
+ ].sort();
1743
+ }
1744
+ function unseededHostGlobals() {
1745
+ return BLOCK_HOST_IMPORTS.filter((i) => i.seeding === "unseeded");
1746
+ }
1747
+ function specifiersForShim(shim) {
1748
+ return BLOCK_HOST_IMPORTS.filter((i) => i.shim === shim).map((i) => i.specifier);
1749
+ }
1750
+ function toRuntimeBlock(node) {
1751
+ const storedLayout = node.layout;
1752
+ const mergedLayout = storedLayout ? {
1753
+ ...storedLayout,
1754
+ span: { ...DEFAULT_BLOCK_LAYOUT.span, ...storedLayout.span }
1755
+ } : DEFAULT_BLOCK_LAYOUT;
1756
+ const base = {
1757
+ id: node.id,
1758
+ type: node.type,
1759
+ props: node.props ?? {},
1760
+ layout: mergedLayout,
1761
+ ...node.style ? { style: node.style } : {}
1762
+ };
1763
+ if (node.children && node.children.length > 0) {
1764
+ return { ...base, children: node.children.map(toRuntimeBlock) };
1765
+ }
1766
+ return base;
1767
+ }
1768
+ function grantsToDescriptors(grants) {
1769
+ if (grants.length === 0) return [];
1770
+ return grants.map((grant) => ({
1771
+ blockType: grant.blockType,
1772
+ moduleUrl: grant.moduleUrl,
1773
+ integrity: grant.integrity,
1774
+ publisher: "workspace",
1775
+ publisherVerified: false,
1776
+ definition: {
1777
+ name: grant.artifactName,
1778
+ category: "marketplace",
1779
+ defaultProps: {},
1780
+ canHaveChildren: false
1781
+ }
1782
+ }));
1783
+ }
1784
+ function buildSurfaceUrl(apiBaseUrl, ref) {
1785
+ const base = apiBaseUrl.replace(/\/+$/, "");
1786
+ if ("surfaceId" in ref) {
1787
+ return `${base}/api/surfaces/${encodeURIComponent(ref.surfaceId)}/published`;
1788
+ }
1789
+ return `${base}/api/surfaces/by-slug/${encodeURIComponent(ref.tenantSlug)}/${encodeURIComponent(
1790
+ ref.surfaceSlug
1791
+ )}`;
1792
+ }
1793
+ function unwrap(json) {
1794
+ const obj = json;
1795
+ if (obj && obj.error) {
1796
+ throw new Error(`[pwfabric-embed] surface fetch error: ${obj.error.code ?? "UNKNOWN"}`);
1797
+ }
1798
+ if (obj && obj.data) return obj.data;
1799
+ return json;
1800
+ }
1801
+ async function loadThin(ref, options) {
1802
+ const doFetch = options.fetchImpl ?? fetch;
1803
+ const url = buildSurfaceUrl(options.apiBaseUrl, ref);
1804
+ const headers = { accept: "application/json" };
1805
+ const token = options.auth?.accessToken;
1806
+ if (token) headers.authorization = `Bearer ${token}`;
1807
+ const init = { method: "GET", headers };
1808
+ if (options.auth?.includeCredentials) init.credentials = "include";
1809
+ const res = await doFetch(url, init);
1810
+ if (!res.ok) {
1811
+ throw new Error(`[pwfabric-embed] surface fetch failed: ${res.status} ${res.statusText}`);
1812
+ }
1813
+ const data = unwrap(await res.json());
1814
+ const def = data.definition ?? {};
1815
+ let blocks = [];
1816
+ if (def.rootBlock) {
1817
+ blocks = (def.rootBlock.children ?? []).map(toRuntimeBlock);
1818
+ } else if (def.blocks) {
1819
+ blocks = def.blocks.map(toRuntimeBlock);
1820
+ }
1821
+ const capabilities = (def.capabilities ?? []).map((c) => ({
1822
+ capability: c.capability,
1823
+ required: c.required ?? false,
1824
+ ...c.config !== void 0 ? { config: c.config } : {}
1825
+ }));
1826
+ if (token && Array.isArray(def.dataSources)) {
1827
+ const authed = def.dataSources.map((ds) => {
1828
+ const d = ds;
1829
+ return d.kind === "rest" ? { ...d, headers: { ...d.headers, Authorization: `Bearer ${token}` } } : d;
1830
+ });
1831
+ const existing = capabilities.find((c) => isCapability(c, "platform/persistence"));
1832
+ if (existing) {
1833
+ existing.config = {
1834
+ ...existing.config ?? {},
1835
+ dataSources: authed,
1836
+ ...def.state ? { initialState: def.state } : {}
1837
+ };
1838
+ } else {
1839
+ capabilities.push({
1840
+ capability: "platform/persistence",
1841
+ required: false,
1842
+ config: { dataSources: authed, ...def.state ? { initialState: def.state } : {} }
1843
+ });
1844
+ }
1845
+ }
1846
+ const appearance = def.theme || def.styleVariables ? {
1847
+ config: {
1848
+ ...def.theme ? { theme: def.theme } : {},
1849
+ ...def.styleVariables ? { styleVariables: def.styleVariables } : {}
1850
+ }
1851
+ } : void 0;
1852
+ const surface = {
1853
+ blocks,
1854
+ ...appearance ? { appearance } : {},
1855
+ ...capabilities.length > 0 ? { capabilities } : {},
1856
+ id: data.surfaceId
1857
+ };
1858
+ return {
1859
+ surface,
1860
+ dynamicBlocks: grantsToDescriptors(data.renderGrants ?? []),
1861
+ surfaceId: data.surfaceId,
1862
+ worldId: data.worldId,
1863
+ ...data.layout ? { layout: data.layout } : {}
1864
+ };
1865
+ }
1866
+
1867
+ // src/build-fat-html.ts
1868
+ var LS = 8232;
1869
+ var PS = 8233;
1870
+ var LINE_SEPS = new RegExp(`[${String.fromCharCode(LS)}${String.fromCharCode(PS)}]`, "g");
1871
+ function safeJson(value) {
1872
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(LINE_SEPS, (ch) => "\\u" + ch.charCodeAt(0).toString(16).padStart(4, "0"));
1873
+ }
1874
+ function escapeHtml(s) {
1875
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1876
+ }
1877
+ function buildFatHtml(options) {
1878
+ const { surface, embedJs } = options;
1879
+ const blocks = options.blocks ?? [];
1880
+ const appearance = options.appearance ?? surface.appearance;
1881
+ const title = options.title ?? "Surface";
1882
+ const lang = options.lang ?? "en";
1883
+ const surfaceJson = safeJson(surface);
1884
+ const blocksJson = safeJson(blocks);
1885
+ const appearanceJson = safeJson(appearance ?? null);
1886
+ return `<!DOCTYPE html>
1887
+ <html lang="${lang}">
1888
+ <head>
1889
+ <meta charset="utf-8" />
1890
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1891
+ <title>${escapeHtml(title)}</title>
1892
+ <style>html,body{margin:0;padding:0}#pw-root{min-height:100vh}</style>
1893
+ </head>
1894
+ <body>
1895
+ <div id="pw-root"></div>
1896
+ <script type="application/pw-surface+json">${surfaceJson}<\/script>
1897
+ <script type="application/pw-blocks+json">${blocksJson}<\/script>
1898
+ <script type="application/pw-appearance+json">${appearanceJson}<\/script>
1899
+ <script>${embedJs}<\/script>
1900
+ <script>
1901
+ (function(){
1902
+ var surface = JSON.parse(document.querySelector('script[type="application/pw-surface+json"]').textContent);
1903
+ var blocks = JSON.parse(document.querySelector('script[type="application/pw-blocks+json"]').textContent);
1904
+ var appearance = JSON.parse(document.querySelector('script[type="application/pw-appearance+json"]').textContent);
1905
+ PWFabric.render('#pw-root', { surface: surface }, { mode: 'fat', blocks: blocks, appearance: appearance });
1906
+ })();
1907
+ <\/script>
1908
+ </body>
1909
+ </html>`;
1910
+ }
1911
+
1912
+ // src/index.ts
1913
+ function isInlineSurface(source) {
1914
+ return "surface" in source;
1915
+ }
1916
+ function detectMode(source, options) {
1917
+ if (options?.mode) return options.mode;
1918
+ return isInlineSurface(source) ? "fat" : "thin";
1919
+ }
1920
+ function passthrough(options) {
1921
+ const o = options ?? {};
1922
+ return {
1923
+ ...o.theme !== void 0 ? { theme: o.theme } : {},
1924
+ ...o.viewport !== void 0 ? { viewport: o.viewport } : {},
1925
+ ...o.basePath !== void 0 ? { basePath: o.basePath } : {},
1926
+ ...o.imageAdapter !== void 0 ? { imageAdapter: o.imageAdapter } : {},
1927
+ ...o.interactionMode !== void 0 ? { interactionMode: o.interactionMode } : {},
1928
+ ...o.onEvent !== void 0 ? { onEvent: o.onEvent } : {},
1929
+ ...o.gap !== void 0 ? { gap: o.gap } : {},
1930
+ ...o.padding !== void 0 ? { padding: o.padding } : {},
1931
+ ...o.components !== void 0 ? { components: o.components } : {},
1932
+ ...o.loadingStrategy !== void 0 ? { loadingStrategy: o.loadingStrategy } : {},
1933
+ ...o.dataCache !== void 0 ? { dataCache: o.dataCache } : {},
1934
+ ...o.placeholderMissingBlocks !== void 0 ? { placeholderMissingBlocks: o.placeholderMissingBlocks } : {}
1935
+ };
1936
+ }
1937
+ async function render(target, source, options) {
1938
+ const o = options ?? {};
1939
+ try {
1940
+ const mode = detectMode(source, options);
1941
+ if (mode === "fat") {
1942
+ if (!isInlineSurface(source)) {
1943
+ throw new Error("[pwfabric-embed] fat mode requires an inline { surface }");
1944
+ }
1945
+ const fatOpts = {
1946
+ surface: source.surface,
1947
+ ...o.blocks ? { blocks: o.blocks } : {},
1948
+ ...o.appearance ? { appearance: o.appearance } : {},
1949
+ ...o.hydrate ? { hydrate: true } : {},
1950
+ ...o.capabilities ? { capabilities: o.capabilities } : {},
1951
+ ...o.entityFacade ? { entityFacade: o.entityFacade } : {},
1952
+ ...o.connections ? { connections: o.connections } : {},
1953
+ ...o.dataServiceConfig ? { dataServiceConfig: o.dataServiceConfig } : {},
1954
+ ...passthrough(options)
1955
+ };
1956
+ const handle2 = renderFat(target, fatOpts);
1957
+ o.onReady?.(handle2);
1958
+ return handle2;
1959
+ }
1960
+ if (isInlineSurface(source)) {
1961
+ throw new Error("[pwfabric-embed] thin mode requires a { surfaceId } or slug reference");
1962
+ }
1963
+ if (!o.apiBaseUrl) {
1964
+ throw new Error("[pwfabric-embed] thin mode requires `apiBaseUrl`");
1965
+ }
1966
+ const ref = "surfaceId" in source ? { surfaceId: source.surfaceId } : { tenantSlug: source.tenantSlug, surfaceSlug: source.surfaceSlug };
1967
+ const loaded = await loadThin(ref, {
1968
+ apiBaseUrl: o.apiBaseUrl,
1969
+ ...o.auth ? { auth: o.auth } : {},
1970
+ ...o.fetchImpl ? { fetchImpl: o.fetchImpl } : {}
1971
+ });
1972
+ const core = {
1973
+ surface: loaded.surface,
1974
+ ...loaded.dynamicBlocks.length > 0 ? { dynamicBlocks: loaded.dynamicBlocks } : {},
1975
+ ...o.capabilities ? { capabilities: o.capabilities } : {},
1976
+ ...o.entityFacade ? { entityFacade: o.entityFacade } : {},
1977
+ ...loaded.layout?.gap !== void 0 ? { gap: loaded.layout.gap } : {},
1978
+ ...loaded.layout?.padding !== void 0 ? { padding: loaded.layout.padding } : {},
1979
+ ...passthrough(options)
1980
+ };
1981
+ const handle = mountSurface(target, core);
1982
+ o.onReady?.(handle);
1983
+ return handle;
1984
+ } catch (err2) {
1985
+ if (o.onError) {
1986
+ o.onError(err2);
1987
+ }
1988
+ throw err2;
1989
+ }
1990
+ }
1991
+ function readInlineJson(root, type) {
1992
+ const el = root.querySelector(`script[type="application/${type}+json"]`);
1993
+ if (!el?.textContent) return void 0;
1994
+ try {
1995
+ return JSON.parse(el.textContent);
1996
+ } catch {
1997
+ return void 0;
1998
+ }
1999
+ }
2000
+ function hydrateElement(el) {
2001
+ const ds = el.dataset;
2002
+ const surfaceAttr = ds.pwSurface;
2003
+ const declaredMode = ds.pwMode;
2004
+ const scope = el.querySelector('script[type^="application/pw-"]') ? el : el.parentNode ?? el;
2005
+ const inlineSurface = readInlineJson(scope, "pw-surface");
2006
+ const isFat = declaredMode === "fat" || !declaredMode && (surfaceAttr === "inline" || !!inlineSurface);
2007
+ const common = {
2008
+ ...ds.pwTheme ? { theme: ds.pwTheme } : {}
2009
+ };
2010
+ if (isFat) {
2011
+ if (!inlineSurface) {
2012
+ console.warn('[pwfabric-embed] data-pw-surface="inline" but no inline surface JSON found');
2013
+ return;
2014
+ }
2015
+ const blocks = readInlineJson(scope, "pw-blocks");
2016
+ const appearance = readInlineJson(scope, "pw-appearance");
2017
+ void render(el, { surface: inlineSurface }, {
2018
+ ...common,
2019
+ mode: "fat",
2020
+ ...blocks ? { blocks } : {},
2021
+ ...appearance ? { appearance } : {}
2022
+ });
2023
+ return;
2024
+ }
2025
+ const apiBaseUrl = ds.pwApi;
2026
+ if (!apiBaseUrl) {
2027
+ console.warn("[pwfabric-embed] data-pw-surface thin mode requires data-pw-api");
2028
+ return;
2029
+ }
2030
+ const auth = ds.pwToken ? { accessToken: ds.pwToken } : void 0;
2031
+ const source = ds.pwTenant && ds.pwSlug ? { tenantSlug: ds.pwTenant, surfaceSlug: ds.pwSlug } : { surfaceId: surfaceAttr ?? "" };
2032
+ void render(el, source, {
2033
+ ...common,
2034
+ mode: "thin",
2035
+ apiBaseUrl,
2036
+ ...auth ? { auth } : {}
2037
+ });
2038
+ }
2039
+ function autoload(root = document) {
2040
+ const els = root.querySelectorAll("[data-pw-surface]");
2041
+ els.forEach((el) => {
2042
+ if (el.dataset.pwHydrated === "true") return;
2043
+ el.dataset.pwHydrated = "true";
2044
+ hydrateElement(el);
2045
+ });
2046
+ }
2047
+ if (typeof document !== "undefined") {
2048
+ if (document.readyState === "loading") {
2049
+ document.addEventListener("DOMContentLoaded", () => autoload());
2050
+ } else {
2051
+ queueMicrotask(() => autoload());
2052
+ }
2053
+ }
2054
+ var PWFabric = {
2055
+ render,
2056
+ renderFat,
2057
+ loadThin,
2058
+ autoload
2059
+ };
2060
+ var src_default = PWFabric;
2061
+
2062
+ export { PWFabric, RebuildNeededBlock, autoload, buildFatHtml, createOfflineEntityFacade, createOfflineNavigationProvider, createSurfaceElement, src_default as default, fatCoreOptions, grantsToDescriptors, loadThin, missingBlockTypes, mountSurface, needsDataBoundRenderer, render, renderFat, resolveTarget, staticPersistenceCapability };
2063
+ //# sourceMappingURL=index.js.map
2064
+ //# sourceMappingURL=index.js.map