@cmssy/core 5.0.0

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,1696 @@
1
+ import { EncryptJWT, jwtDecrypt } from 'jose';
2
+ export { evaluateFieldConditionGroup } from '@cmssy/types';
3
+ import { createHmac, timingSafeEqual } from 'crypto';
4
+
5
+ // src/session.ts
6
+ var CMSSY_SESSION_COOKIE = "cmssy_session";
7
+ var SESSION_MAX_AGE_SECONDS = 30 * 24 * 60 * 60;
8
+ var MIN_SESSION_SECRET_LENGTH = 32;
9
+ var ACCESS_EXPIRY_SKEW_MS = 3e4;
10
+ async function deriveSessionKey(secret) {
11
+ if (typeof secret !== "string" || secret.length < MIN_SESSION_SECRET_LENGTH) {
12
+ throw new Error(
13
+ `cmssy auth sessionSecret must be at least ${MIN_SESSION_SECRET_LENGTH} characters`
14
+ );
15
+ }
16
+ const digest = await crypto.subtle.digest(
17
+ "SHA-256",
18
+ new TextEncoder().encode(secret)
19
+ );
20
+ return new Uint8Array(digest);
21
+ }
22
+ async function sealSession(payload, secret, audience) {
23
+ const key = await deriveSessionKey(secret);
24
+ const jwt = new EncryptJWT({ ...payload }).setProtectedHeader({ alg: "dir", enc: "A256GCM" }).setIssuedAt().setExpirationTime(`${SESSION_MAX_AGE_SECONDS}s`);
25
+ if (audience) jwt.setAudience(audience);
26
+ return jwt.encrypt(key);
27
+ }
28
+ async function openSession(token, secret, audience) {
29
+ const key = await deriveSessionKey(secret);
30
+ try {
31
+ const { payload } = await jwtDecrypt(token, key, {
32
+ keyManagementAlgorithms: ["dir"],
33
+ contentEncryptionAlgorithms: ["A256GCM"],
34
+ ...audience ? { audience } : {}
35
+ });
36
+ const { accessToken, refreshToken, accessExpiresAt, user } = payload;
37
+ if (typeof accessToken !== "string" || typeof refreshToken !== "string" || !Number.isFinite(accessExpiresAt) || !user || typeof user !== "object" || typeof user.recordId !== "string" || typeof user.email !== "string") {
38
+ return null;
39
+ }
40
+ return {
41
+ accessToken,
42
+ refreshToken,
43
+ accessExpiresAt,
44
+ user: {
45
+ recordId: user.recordId,
46
+ email: user.email
47
+ }
48
+ };
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+ function isAccessExpired(payload, now = Date.now()) {
54
+ return payload.accessExpiresAt <= now + ACCESS_EXPIRY_SKEW_MS;
55
+ }
56
+ function sessionCookieOptions() {
57
+ return {
58
+ httpOnly: true,
59
+ secure: process.env.NODE_ENV !== "development",
60
+ sameSite: "lax",
61
+ path: "/",
62
+ maxAge: SESSION_MAX_AGE_SECONDS
63
+ };
64
+ }
65
+
66
+ // src/config.ts
67
+ var DEFAULT_CMSSY_EDITOR_ORIGINS = [
68
+ "https://cmssy.io",
69
+ "https://www.cmssy.io"
70
+ ];
71
+ function parseEditorOriginEnv(raw) {
72
+ if (!raw) return void 0;
73
+ const parts = raw.split(",").map((o) => o.trim()).filter((o) => o.length > 0);
74
+ if (parts.length === 0) return void 0;
75
+ return parts.length === 1 ? parts[0] : parts;
76
+ }
77
+ function isDevelopment() {
78
+ return typeof process !== "undefined" && process.env.NODE_ENV === "development";
79
+ }
80
+ function resolveEditorOrigin(editorOrigin) {
81
+ const value = editorOrigin ?? (typeof process !== "undefined" ? parseEditorOriginEnv(process.env.CMSSY_EDITOR_ORIGIN) : void 0);
82
+ if (value === void 0) {
83
+ return isDevelopment() ? "*" : DEFAULT_CMSSY_EDITOR_ORIGINS;
84
+ }
85
+ if (Array.isArray(value)) {
86
+ const cleaned = value.filter((o) => o && o.trim().length > 0);
87
+ return cleaned.length > 0 ? cleaned : DEFAULT_CMSSY_EDITOR_ORIGINS;
88
+ }
89
+ return value.trim().length > 0 ? value : DEFAULT_CMSSY_EDITOR_ORIGINS;
90
+ }
91
+ var REQUIRED_CONFIG_ENV = [
92
+ ["org", "CMSSY_ORG_SLUG"],
93
+ ["workspaceSlug", "CMSSY_WORKSPACE_SLUG"],
94
+ ["draftSecret", "CMSSY_DRAFT_SECRET"]
95
+ ];
96
+ function defineCmssyConfig(config) {
97
+ const resolved = { ...config };
98
+ const missing = [];
99
+ for (const [key, env] of REQUIRED_CONFIG_ENV) {
100
+ const value = config[key];
101
+ const trimmed = typeof value === "string" ? value.trim() : "";
102
+ if (trimmed) {
103
+ resolved[key] = trimmed;
104
+ } else {
105
+ missing.push(`${env} (config.${key})`);
106
+ }
107
+ }
108
+ if (missing.length > 0) {
109
+ if (typeof window !== "undefined") {
110
+ throw new Error(
111
+ "cmssy: the config was evaluated in the browser, so it cannot see the server's environment variables.\n\nThis is an import problem, not a config problem: client-side code imported a VALUE from a module that reads the cmssy config - directly, or through a helper sitting next to one.\n\nFix it by importing types only (they are erased at build time), or by moving the value into a module that does not touch the config."
112
+ );
113
+ }
114
+ throw new Error(
115
+ `cmssy: missing required configuration:
116
+ - ${missing.join(
117
+ "\n - "
118
+ )}
119
+ Set the listed environment variables (e.g. in .env.local) and restart the dev server.`
120
+ );
121
+ }
122
+ return resolved;
123
+ }
124
+ function assertAuthConfig(config) {
125
+ const auth = config.auth;
126
+ if (!auth || typeof auth.modelSlug !== "string" || !auth.modelSlug) {
127
+ throw new Error("cmssy: config.auth.modelSlug is required for auth routes");
128
+ }
129
+ if (typeof auth.sessionSecret !== "string" || auth.sessionSecret.length < MIN_SESSION_SECRET_LENGTH) {
130
+ throw new Error(
131
+ `cmssy: config.auth.sessionSecret must be at least ${MIN_SESSION_SECRET_LENGTH} characters`
132
+ );
133
+ }
134
+ return auth;
135
+ }
136
+
137
+ // src/data/http.ts
138
+ var CmssyRequestError = class extends Error {
139
+ status;
140
+ constructor(message, status) {
141
+ super(message);
142
+ this.name = "CmssyRequestError";
143
+ this.status = status;
144
+ }
145
+ };
146
+ var DEFAULT_RETRY_STATUSES = [429, 503];
147
+ function retryAfterMs(response) {
148
+ const raw = response.headers?.get("retry-after");
149
+ if (!raw) return null;
150
+ const seconds = Number(raw);
151
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
152
+ const date = Date.parse(raw);
153
+ if (Number.isFinite(date)) return Math.max(0, date - Date.now());
154
+ return null;
155
+ }
156
+ function sleep(ms, signal) {
157
+ return new Promise((resolve, reject) => {
158
+ if (signal?.aborted) {
159
+ reject(new Error("cmssy: request aborted"));
160
+ return;
161
+ }
162
+ const timer = setTimeout(() => {
163
+ signal?.removeEventListener("abort", onAbort);
164
+ resolve();
165
+ }, ms);
166
+ function onAbort() {
167
+ clearTimeout(timer);
168
+ reject(new Error("cmssy: request aborted"));
169
+ }
170
+ signal?.addEventListener("abort", onAbort, { once: true });
171
+ });
172
+ }
173
+ async function fetchWithRetry(doFetch, url, init, retry) {
174
+ if (retry === false || retry === void 0) {
175
+ return doFetch(url, init);
176
+ }
177
+ const maxRetries = retry.maxRetries ?? 3;
178
+ const baseDelayMs = retry.baseDelayMs ?? 300;
179
+ const maxDelayMs = retry.maxDelayMs ?? 3e3;
180
+ const retryStatuses = retry.retryStatuses ?? DEFAULT_RETRY_STATUSES;
181
+ let response = await doFetch(url, init);
182
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
183
+ if (response.ok || !retryStatuses.includes(response.status)) {
184
+ return response;
185
+ }
186
+ const backoff = baseDelayMs * 2 ** attempt;
187
+ const wait = Math.min(retryAfterMs(response) ?? backoff, maxDelayMs);
188
+ await sleep(wait, init.signal);
189
+ response = await doFetch(url, init);
190
+ }
191
+ return response;
192
+ }
193
+ async function postGraphql(url, query, variables, options) {
194
+ const doFetch = options.fetch ?? globalThis.fetch;
195
+ if (typeof doFetch !== "function") {
196
+ throw new Error(
197
+ "cmssy: no fetch implementation available - pass options.fetch"
198
+ );
199
+ }
200
+ const response = await fetchWithRetry(
201
+ doFetch,
202
+ url,
203
+ {
204
+ method: "POST",
205
+ headers: { "content-type": "application/json", ...options.headers },
206
+ body: JSON.stringify({ query, variables }),
207
+ signal: options.signal
208
+ },
209
+ options.retry
210
+ );
211
+ if (!response.ok) {
212
+ let detail = "";
213
+ try {
214
+ const body = await response.json();
215
+ if (body.errors && body.errors.length > 0) {
216
+ detail = ` - ${body.errors.map((error) => error.message ?? "GraphQL error").join("; ")}`;
217
+ }
218
+ } catch {
219
+ detail = "";
220
+ }
221
+ throw new CmssyRequestError(
222
+ `cmssy: ${options.label} failed (${response.status})${detail}`,
223
+ response.status
224
+ );
225
+ }
226
+ let json;
227
+ try {
228
+ json = await response.json();
229
+ } catch {
230
+ throw new Error(`cmssy: invalid JSON response from the ${options.label}`);
231
+ }
232
+ if (json.errors && json.errors.length > 0) {
233
+ const message = json.errors.map((error) => error.message ?? "GraphQL error").join("; ");
234
+ throw new Error(`cmssy: ${options.label} error - ${message}`);
235
+ }
236
+ return json.data;
237
+ }
238
+
239
+ // src/content/content-client.ts
240
+ var DEFAULT_CMSSY_API_URL = "https://api.cmssy.io/graphql";
241
+ function resolveApiUrl(apiUrl) {
242
+ const explicit = apiUrl?.trim();
243
+ if (explicit) return explicit;
244
+ const env = globalThis.process?.env;
245
+ const fromEnv = env?.CMSSY_API_URL?.trim() ?? "";
246
+ return fromEnv.length > 0 ? fromEnv : DEFAULT_CMSSY_API_URL;
247
+ }
248
+ function resolvePublicUrl(config) {
249
+ const base = resolveApiUrl(config.apiUrl).replace(/\/graphql\/?$/, "");
250
+ return `${base}/public/${config.org}/${config.workspaceSlug}/graphql`;
251
+ }
252
+ var PUBLIC_PAGE_QUERY = `query PublicPage($workspaceSlug: String!, $slug: String!, $previewSecret: String) {
253
+ public {
254
+ page {
255
+ get(workspaceSlug: $workspaceSlug, slug: $slug, previewSecret: $previewSecret) {
256
+ id
257
+ blocks { id type content style advanced }
258
+ publishedBlocks { id type content style advanced }
259
+ }
260
+ }
261
+ }
262
+ }`;
263
+ var PUBLIC_PAGE_DEV_QUERY = `query PublicPage($workspaceSlug: String!, $slug: String!, $previewSecret: String, $devPreview: Boolean) {
264
+ public {
265
+ page {
266
+ get(workspaceSlug: $workspaceSlug, slug: $slug, previewSecret: $previewSecret, devPreview: $devPreview) {
267
+ id
268
+ blocks { id type content style advanced }
269
+ publishedBlocks { id type content style advanced }
270
+ }
271
+ }
272
+ }
273
+ }`;
274
+ var PUBLIC_PAGE_BY_ID_QUERY = `query PublicPageById($workspaceSlug: String!, $pageId: ID!) {
275
+ public {
276
+ page {
277
+ getById(workspaceSlug: $workspaceSlug, pageId: $pageId) {
278
+ id
279
+ publishedBlocks { id type content style advanced }
280
+ }
281
+ }
282
+ }
283
+ }`;
284
+ var PUBLIC_PAGES_QUERY = `query PublicPages($workspaceSlug: String!) {
285
+ public {
286
+ page {
287
+ list(workspaceSlug: $workspaceSlug) {
288
+ id
289
+ slug
290
+ updatedAt
291
+ publishedAt
292
+ }
293
+ }
294
+ }
295
+ }`;
296
+ var PUBLIC_PAGE_META_QUERY = `query PublicPageMeta($workspaceSlug: String!, $slug: String!) {
297
+ public {
298
+ page {
299
+ get(workspaceSlug: $workspaceSlug, slug: $slug) {
300
+ id
301
+ seoTitle
302
+ seoDescription
303
+ seoKeywords
304
+ displayName
305
+ }
306
+ }
307
+ }
308
+ }`;
309
+ var PUBLIC_PAGE_LAYOUTS_QUERY = `query PublicPageLayouts($workspaceSlug: String!, $pageSlug: String!, $previewSecret: String) {
310
+ public {
311
+ page {
312
+ layouts(workspaceSlug: $workspaceSlug, pageSlug: $pageSlug, previewSecret: $previewSecret) {
313
+ position
314
+ blocks { id type content style advanced order isActive }
315
+ settings { desktopWidth mobileBehavior }
316
+ }
317
+ }
318
+ }
319
+ }`;
320
+ function normalizeSlug(path) {
321
+ if (Array.isArray(path)) {
322
+ const joined = path.filter(Boolean).join("/");
323
+ return joined ? `/${joined}` : "/";
324
+ }
325
+ if (!path || path === "/") return "/";
326
+ return path.startsWith("/") ? path : `/${path}`;
327
+ }
328
+ async function fetchPage(config, path, options = {}) {
329
+ const slug = normalizeSlug(path);
330
+ const trimmedSecret = options.previewSecret?.trim();
331
+ const previewSecret = trimmedSecret ? trimmedSecret : null;
332
+ const devToken = options.devToken?.trim();
333
+ const devPreview = Boolean(options.devPreview && devToken);
334
+ const headers2 = {};
335
+ if (devPreview && devToken) {
336
+ headers2["authorization"] = `Bearer ${devToken}`;
337
+ if (options.workspaceId) {
338
+ headers2["x-workspace-id"] = options.workspaceId;
339
+ }
340
+ }
341
+ const data = await postGraphql(
342
+ resolvePublicUrl(config),
343
+ devPreview ? PUBLIC_PAGE_DEV_QUERY : PUBLIC_PAGE_QUERY,
344
+ {
345
+ workspaceSlug: config.workspaceSlug,
346
+ slug,
347
+ previewSecret,
348
+ ...devPreview ? { devPreview: true } : {}
349
+ },
350
+ {
351
+ fetch: options.fetch,
352
+ signal: options.signal,
353
+ headers: headers2,
354
+ retry: options.retry ?? {},
355
+ label: "page fetch"
356
+ }
357
+ );
358
+ const page = data?.public?.page?.get;
359
+ if (!page) return null;
360
+ const draft = previewSecret !== null || devPreview;
361
+ const blocks = (draft ? page.blocks : page.publishedBlocks) ?? [];
362
+ return { id: page.id, blocks };
363
+ }
364
+ async function fetchPageById(config, pageId, options = {}) {
365
+ const data = await postGraphql(
366
+ resolvePublicUrl(config),
367
+ PUBLIC_PAGE_BY_ID_QUERY,
368
+ { workspaceSlug: config.workspaceSlug, pageId },
369
+ {
370
+ fetch: options.fetch,
371
+ signal: options.signal,
372
+ retry: options.retry ?? {},
373
+ label: "page-by-id fetch"
374
+ }
375
+ );
376
+ const page = data?.public?.page?.getById;
377
+ if (!page) return null;
378
+ return { id: page.id, blocks: page.publishedBlocks ?? [] };
379
+ }
380
+ async function fetchPages(config, options = {}) {
381
+ const data = await postGraphql(
382
+ resolvePublicUrl(config),
383
+ PUBLIC_PAGES_QUERY,
384
+ { workspaceSlug: config.workspaceSlug },
385
+ {
386
+ fetch: options.fetch,
387
+ signal: options.signal,
388
+ retry: options.retry ?? {},
389
+ label: "pages fetch"
390
+ }
391
+ );
392
+ return data?.public?.page?.list ?? [];
393
+ }
394
+ async function fetchPageMeta(config, path, options = {}) {
395
+ const slug = normalizeSlug(path);
396
+ const data = await postGraphql(
397
+ resolvePublicUrl(config),
398
+ PUBLIC_PAGE_META_QUERY,
399
+ { workspaceSlug: config.workspaceSlug, slug },
400
+ {
401
+ fetch: options.fetch,
402
+ signal: options.signal,
403
+ retry: options.retry ?? {},
404
+ label: "page meta fetch"
405
+ }
406
+ );
407
+ return data?.public?.page?.get ?? null;
408
+ }
409
+ async function fetchLayouts(config, path, options = {}) {
410
+ const pageSlug = normalizeSlug(path);
411
+ const trimmedSecret = options.previewSecret?.trim();
412
+ const previewSecret = trimmedSecret ? trimmedSecret : null;
413
+ const data = await postGraphql(
414
+ resolvePublicUrl(config),
415
+ PUBLIC_PAGE_LAYOUTS_QUERY,
416
+ { workspaceSlug: config.workspaceSlug, pageSlug, previewSecret },
417
+ {
418
+ fetch: options.fetch,
419
+ signal: options.signal,
420
+ retry: options.retry ?? {},
421
+ label: "layouts fetch"
422
+ }
423
+ );
424
+ return data?.public?.page?.layouts ?? [];
425
+ }
426
+
427
+ // src/content/get-block-content.ts
428
+ function isPlainObject(value) {
429
+ return typeof value === "object" && value !== null && !Array.isArray(value);
430
+ }
431
+ function looksLikeLocaleKey(key) {
432
+ return /^[a-z]{2}(-[A-Za-z]{2})?$/.test(key);
433
+ }
434
+ function getBlockContentForLanguage(content, locale, defaultLocale = "en", availableLocales) {
435
+ if (!isPlainObject(content)) return {};
436
+ const isLocale = availableLocales ? (key) => availableLocales.includes(key) : looksLikeLocaleKey;
437
+ const localeEntries = Object.entries(content).filter(
438
+ ([key, value]) => isLocale(key) && isPlainObject(value)
439
+ );
440
+ if (localeEntries.length === 0) return { ...content };
441
+ const localeMap = Object.fromEntries(localeEntries);
442
+ const nonTranslatable = {};
443
+ for (const [key, value] of Object.entries(content)) {
444
+ if (!(isLocale(key) && isPlainObject(value))) nonTranslatable[key] = value;
445
+ }
446
+ const fallbackKey = Object.keys(localeMap)[0];
447
+ const chosen = localeMap[locale] ?? localeMap[defaultLocale] ?? localeMap[fallbackKey];
448
+ return { ...nonTranslatable, ...chosen };
449
+ }
450
+ function asBucket(value) {
451
+ return isPlainObject(value) ? value : {};
452
+ }
453
+
454
+ // src/data/graphql-request.ts
455
+ async function graphqlRequest(config, query, variables, options = {}, label = "request") {
456
+ const url = options.public ? resolvePublicUrl(config) : resolveApiUrl(config.apiUrl);
457
+ return postGraphql(url, query, variables, {
458
+ fetch: options.fetch,
459
+ signal: options.signal,
460
+ headers: options.headers,
461
+ retry: options.retry,
462
+ label
463
+ });
464
+ }
465
+
466
+ // src/data/queries.ts
467
+ var SITE_CONFIG_QUERY = `query PublicSiteConfig($workspaceSlug: String!) {
468
+ public {
469
+ siteConfig(workspaceSlug: $workspaceSlug) {
470
+ id
471
+ workspaceId
472
+ siteName
473
+ defaultLanguage
474
+ enabledLanguages
475
+ enabledFeatures
476
+ notFoundPageId
477
+ previewUrl
478
+ branding {
479
+ brandName
480
+ logoUrl
481
+ faviconUrl
482
+ ogImageUrl
483
+ }
484
+ }
485
+ }
486
+ }`;
487
+ var MODEL_DEFINITIONS_QUERY = `query PublicModelDefinitions($workspaceId: String!) {
488
+ public {
489
+ model {
490
+ definitions(workspaceId: $workspaceId) {
491
+ id name slug description icon color displayField recordCount
492
+ }
493
+ }
494
+ }
495
+ }`;
496
+ var MODEL_RECORDS_QUERY = `query PublicModelRecords($workspaceId: String!, $modelSlug: String!, $filter: JSON, $sort: String, $locale: String, $limit: Int, $offset: Int, $populate: [String!]) {
497
+ public {
498
+ model {
499
+ records(workspaceId: $workspaceId, modelSlug: $modelSlug, filter: $filter, sort: $sort, locale: $locale, limit: $limit, offset: $offset, populate: $populate) {
500
+ items { id modelId data status createdAt updatedAt }
501
+ total
502
+ hasMore
503
+ }
504
+ }
505
+ }
506
+ }`;
507
+ var FORM_QUERY = `query PublicForm($formId: ID!) {
508
+ public {
509
+ form {
510
+ get(formId: $formId) {
511
+ id
512
+ name
513
+ slug
514
+ description
515
+ fields {
516
+ id name fieldType label placeholder helpText
517
+ defaultValue width order showWhen requiredWhen
518
+ options { value label disabled }
519
+ validation { required minLength maxLength minValue maxValue pattern customMessage }
520
+ }
521
+ settings {
522
+ actionType submitButtonLabel successMessage errorMessage
523
+ redirectUrl requireLogin enableCaptcha
524
+ }
525
+ }
526
+ }
527
+ }
528
+ }`;
529
+ var SUBMIT_FORM_MUTATION = `mutation SubmitForm($formId: ID!, $input: SubmitFormInput!) {
530
+ public {
531
+ form {
532
+ submit(formId: $formId, input: $input) {
533
+ success message submissionId redirectUrl accessToken customer
534
+ }
535
+ }
536
+ }
537
+ }`;
538
+
539
+ // src/data/settings-client.ts
540
+ async function fetchSiteConfig(config, options = {}) {
541
+ const data = await graphqlRequest(
542
+ config,
543
+ SITE_CONFIG_QUERY,
544
+ { workspaceSlug: config.workspaceSlug },
545
+ { ...options, public: true, retry: options.retry ?? {} },
546
+ "site config query"
547
+ );
548
+ return data.public?.siteConfig ?? null;
549
+ }
550
+ async function resolveWorkspaceId(config, options = {}) {
551
+ const siteConfig = await fetchSiteConfig(config, options);
552
+ if (!siteConfig?.workspaceId) {
553
+ throw new Error(
554
+ `cmssy: could not resolve workspaceId for "${config.workspaceSlug}"`
555
+ );
556
+ }
557
+ return siteConfig.workspaceId;
558
+ }
559
+ var workspaceIdCache = /* @__PURE__ */ new Map();
560
+ function cachedWorkspaceId(config) {
561
+ const key = `${resolveApiUrl(config.apiUrl)}::${config.workspaceSlug}`;
562
+ const existing = workspaceIdCache.get(key);
563
+ if (existing) return existing;
564
+ const fresh = resolveWorkspaceId(config).catch((err) => {
565
+ workspaceIdCache.delete(key);
566
+ throw err;
567
+ });
568
+ workspaceIdCache.set(key, fresh);
569
+ return fresh;
570
+ }
571
+ function clearWorkspaceIdCache() {
572
+ workspaceIdCache.clear();
573
+ }
574
+
575
+ // src/data/client.ts
576
+ function createCmssyClient(input) {
577
+ const config = {
578
+ ...input,
579
+ apiUrl: resolveApiUrl(input.apiUrl)
580
+ };
581
+ let cachedWorkspaceId2;
582
+ let inFlight;
583
+ function resolveWorkspaceId2(options) {
584
+ if (cachedWorkspaceId2) return Promise.resolve(cachedWorkspaceId2);
585
+ if (!inFlight) {
586
+ inFlight = resolveWorkspaceId(config, options).then((id) => {
587
+ cachedWorkspaceId2 = id;
588
+ return id;
589
+ }).finally(() => {
590
+ inFlight = void 0;
591
+ });
592
+ }
593
+ return inFlight;
594
+ }
595
+ return {
596
+ config,
597
+ resolveWorkspaceId: resolveWorkspaceId2,
598
+ query(document2, variables = {}, options) {
599
+ return graphqlRequest(
600
+ config,
601
+ document2,
602
+ variables,
603
+ options,
604
+ "graphql operation"
605
+ );
606
+ },
607
+ async queryScoped(document2, variables = {}, options = {}) {
608
+ const { workspaceId: provided, headers: headers2, ...rest } = options;
609
+ const workspaceId = provided ?? await resolveWorkspaceId2({ ...rest, headers: headers2 });
610
+ const hasWorkspaceId = variables.workspaceId !== void 0 && variables.workspaceId !== null;
611
+ const scopedVariables = /\$workspaceId\b/.test(document2) && !hasWorkspaceId ? { ...variables, workspaceId } : variables;
612
+ return graphqlRequest(
613
+ config,
614
+ document2,
615
+ scopedVariables,
616
+ { ...rest, headers: { ...headers2, "x-workspace-id": workspaceId } },
617
+ "graphql operation"
618
+ );
619
+ }
620
+ };
621
+ }
622
+
623
+ // src/data/resolve-forms.ts
624
+ function collectFormIds(blocks, locale, defaultLocale) {
625
+ const ids = /* @__PURE__ */ new Set();
626
+ for (const block of blocks) {
627
+ const content = getBlockContentForLanguage(
628
+ block.content,
629
+ locale,
630
+ defaultLocale
631
+ );
632
+ const formId = content.formId;
633
+ if (typeof formId === "string" && formId.trim()) ids.add(formId);
634
+ }
635
+ return [...ids];
636
+ }
637
+ async function resolveForms(config, blocks, locale, defaultLocale, options) {
638
+ const ids = collectFormIds(blocks, locale, defaultLocale);
639
+ if (ids.length === 0) return {};
640
+ const client = createCmssyClient(config);
641
+ const entries = await Promise.all(
642
+ ids.map(async (id) => {
643
+ try {
644
+ const data = await client.queryScoped(FORM_QUERY, { formId: id }, options);
645
+ return [id, data.public.form.get];
646
+ } catch (err) {
647
+ if (typeof console !== "undefined") {
648
+ console.warn(`[cmssy] failed to resolve form ${id}`, err);
649
+ }
650
+ return [id, null];
651
+ }
652
+ })
653
+ );
654
+ const forms = {};
655
+ for (const [id, def] of entries) {
656
+ if (def) forms[id] = def;
657
+ }
658
+ return forms;
659
+ }
660
+
661
+ // src/data/site-locales.ts
662
+ var TTL_MS = 6e4;
663
+ var MAX_ENTRIES = 64;
664
+ var cache = /* @__PURE__ */ new Map();
665
+ async function resolveSiteLocales(config, options) {
666
+ const key = `${resolveApiUrl(config.apiUrl)}::${config.org}::${config.workspaceSlug}`;
667
+ const cached = cache.get(key);
668
+ if (cached && cached.expires > Date.now()) return cached.value;
669
+ cache.delete(key);
670
+ let value;
671
+ try {
672
+ const data = await graphqlRequest(
673
+ config,
674
+ SITE_CONFIG_QUERY,
675
+ { workspaceSlug: config.workspaceSlug },
676
+ { ...options, public: true, retry: options?.retry ?? {} },
677
+ "site config"
678
+ );
679
+ const siteConfig = data.public?.siteConfig ?? null;
680
+ const defaultLocale = siteConfig?.defaultLanguage || "en";
681
+ const enabled = siteConfig?.enabledLanguages ?? [];
682
+ value = {
683
+ defaultLocale,
684
+ locales: enabled.length > 0 ? enabled : [defaultLocale]
685
+ };
686
+ } catch {
687
+ value = { defaultLocale: "en", locales: ["en"] };
688
+ }
689
+ if (cache.size >= MAX_ENTRIES) cache.clear();
690
+ cache.set(key, { value, expires: Date.now() + TTL_MS });
691
+ return value;
692
+ }
693
+ function splitLocaleFromPath(path, siteLocales) {
694
+ const first = path?.[0];
695
+ if (first && first !== siteLocales.defaultLocale && siteLocales.locales.includes(first)) {
696
+ return { locale: first, path: path.slice(1) };
697
+ }
698
+ return { locale: siteLocales.defaultLocale, path };
699
+ }
700
+
701
+ // src/data/localize-href.ts
702
+ var PROTOCOL_OR_RELATIVE = /^([a-z][a-z0-9+.-]*:|\/\/)/i;
703
+ function isExternalHref(href) {
704
+ const value = href.trim();
705
+ if (!value) return true;
706
+ if (value.startsWith("#")) return true;
707
+ return PROTOCOL_OR_RELATIVE.test(value);
708
+ }
709
+ function stripLeadingLocale(path, locale) {
710
+ const segments = path.split("/");
711
+ const first = segments[1];
712
+ if (first && first !== locale.default && locale.enabled.includes(first)) {
713
+ segments.splice(1, 1);
714
+ const rest = segments.join("/");
715
+ return rest === "" ? "/" : rest;
716
+ }
717
+ return path;
718
+ }
719
+ function addLocalePrefix(path, target, locale) {
720
+ if (target === locale.default) return path;
721
+ if (path === "/") return `/${target}`;
722
+ return `/${target}${path}`;
723
+ }
724
+ function localizeHref(href, locale) {
725
+ const value = href.trim();
726
+ if (isExternalHref(value)) return href;
727
+ const boundary = value.search(/[?#]/);
728
+ const path = boundary === -1 ? value : value.slice(0, boundary);
729
+ const suffix = boundary === -1 ? "" : value.slice(boundary);
730
+ if (!path.startsWith("/")) return href;
731
+ const bare = stripLeadingLocale(path, locale);
732
+ return `${addLocalePrefix(bare, locale.current, locale)}${suffix}`;
733
+ }
734
+ function buildLocaleSwitchHref(target, pathname, locale) {
735
+ const path = pathname && pathname.startsWith("/") ? pathname : "/";
736
+ const bare = stripLeadingLocale(path, locale);
737
+ return addLocalePrefix(bare, target, locale);
738
+ }
739
+ var ANCHOR_HREF = /(<a\b(?:"[^"]*"|'[^']*'|[^>])*?\shref=)(["'])(.*?)\2/gi;
740
+ function localizeHtmlLinks(html, locale) {
741
+ return html.replace(
742
+ ANCHOR_HREF,
743
+ (_match, prefix, quote, url) => `${prefix}${quote}${localizeHref(url, locale)}${quote}`
744
+ );
745
+ }
746
+
747
+ // src/locale.ts
748
+ var CMSSY_LOCALE_HEADER = "x-cmssy-locale";
749
+ async function localeForPathname(config, pathname) {
750
+ const siteLocales = await resolveSiteLocales(config);
751
+ const segments = pathname.split("/").filter(Boolean);
752
+ return splitLocaleFromPath(segments, siteLocales).locale;
753
+ }
754
+ async function splitCmssyLocale(config, path) {
755
+ const siteLocales = await resolveSiteLocales(config);
756
+ return splitLocaleFromPath(path, siteLocales);
757
+ }
758
+ async function localeForPath(config, path) {
759
+ const siteLocales = await resolveSiteLocales(config);
760
+ const segments = Array.isArray(path) ? path.filter(Boolean) : path.split("/").filter(Boolean);
761
+ return splitLocaleFromPath(segments, siteLocales).locale;
762
+ }
763
+
764
+ // src/block-context.ts
765
+ function buildBlockContext(locale, defaultLocale, enabledLocales, isPreview, forms, extra) {
766
+ return {
767
+ locale: {
768
+ current: locale,
769
+ default: defaultLocale,
770
+ enabled: enabledLocales && enabledLocales.length > 0 ? enabledLocales : Array.from(/* @__PURE__ */ new Set([defaultLocale, locale]))
771
+ },
772
+ isPreview: isPreview ?? false,
773
+ forms,
774
+ ...extra?.auth ? { auth: extra.auth } : {},
775
+ ...extra?.workspace ? { workspace: extra.workspace } : {}
776
+ };
777
+ }
778
+
779
+ // src/fields.ts
780
+ function control(type) {
781
+ return (opts = {}) => ({
782
+ type,
783
+ label: opts.label ?? "",
784
+ ...opts
785
+ });
786
+ }
787
+ var fields = {
788
+ text: control("text"),
789
+ textarea: control("textarea"),
790
+ richText: control("richText"),
791
+ markdown: control("markdown"),
792
+ number: control("number"),
793
+ date: control("date"),
794
+ datetime: control("datetime"),
795
+ boolean: control("boolean"),
796
+ color: control("color"),
797
+ media: control("media"),
798
+ link: control("link"),
799
+ url: control("url"),
800
+ email: control("email"),
801
+ select: control("select"),
802
+ multiselect: control("multiselect"),
803
+ radio: control("radio"),
804
+ repeater: control("repeater"),
805
+ table: control("table"),
806
+ json: control("json"),
807
+ form: control("form"),
808
+ pageSelector: control("pageSelector")
809
+ };
810
+
811
+ // src/bridge/protocol.ts
812
+ var PROTOCOL_VERSION = 2;
813
+ function isProtocolCompatible(version) {
814
+ return version === PROTOCOL_VERSION;
815
+ }
816
+
817
+ // src/bridge/messages.ts
818
+ function normalizeOrigin(origin) {
819
+ const trimmed = origin.trim();
820
+ if (trimmed === "*") return "*";
821
+ try {
822
+ return new URL(trimmed).origin;
823
+ } catch {
824
+ return trimmed;
825
+ }
826
+ }
827
+ function postToEditor(target, editorOrigin, message) {
828
+ target.postMessage(message, normalizeOrigin(editorOrigin));
829
+ }
830
+ function isOriginAllowed(origin, allowed) {
831
+ const list = Array.isArray(allowed) ? allowed : [allowed];
832
+ const actual = normalizeOrigin(origin);
833
+ return list.some((candidate) => {
834
+ const expected = normalizeOrigin(candidate);
835
+ return expected === "*" || expected === actual;
836
+ });
837
+ }
838
+ function resolveInitialTarget(editorOrigin) {
839
+ const list = (Array.isArray(editorOrigin) ? editorOrigin : [editorOrigin]).map((origin) => normalizeOrigin(origin));
840
+ if (list.includes("*")) return "*";
841
+ if (list.length === 1) return list[0];
842
+ const referrerOrigin = typeof document !== "undefined" && document.referrer ? normalizeOrigin(document.referrer) : "";
843
+ return list.find((origin) => origin === referrerOrigin) ?? list[0];
844
+ }
845
+ function isObject(value) {
846
+ return typeof value === "object" && value !== null && !Array.isArray(value);
847
+ }
848
+ function parseEditorMessage(data, origin, expectedOrigin) {
849
+ if (!isOriginAllowed(origin, expectedOrigin)) return null;
850
+ if (!isObject(data)) return null;
851
+ switch (data.type) {
852
+ case "cmssy:select":
853
+ return typeof data.blockId === "string" && data.protocolVersion === PROTOCOL_VERSION ? {
854
+ type: "cmssy:select",
855
+ protocolVersion: PROTOCOL_VERSION,
856
+ blockId: data.blockId
857
+ } : null;
858
+ case "cmssy:patch":
859
+ return typeof data.blockId === "string" && isObject(data.content) && data.protocolVersion === PROTOCOL_VERSION ? {
860
+ type: "cmssy:patch",
861
+ blockId: data.blockId,
862
+ content: data.content,
863
+ protocolVersion: PROTOCOL_VERSION,
864
+ ...isObject(data.style) ? { style: data.style } : {},
865
+ ...isObject(data.advanced) ? { advanced: data.advanced } : {},
866
+ ...typeof data.layoutPosition === "string" ? { layoutPosition: data.layoutPosition } : {}
867
+ } : null;
868
+ case "cmssy:parent-ready":
869
+ return data.protocolVersion === PROTOCOL_VERSION ? { type: "cmssy:parent-ready", protocolVersion: PROTOCOL_VERSION } : null;
870
+ case "cmssy:insert":
871
+ return typeof data.blockId === "string" && typeof data.blockType === "string" && isObject(data.content) && typeof data.index === "number" && data.protocolVersion === PROTOCOL_VERSION ? {
872
+ type: "cmssy:insert",
873
+ protocolVersion: PROTOCOL_VERSION,
874
+ blockId: data.blockId,
875
+ blockType: data.blockType,
876
+ content: data.content,
877
+ ...isObject(data.style) ? { style: data.style } : {},
878
+ ...isObject(data.advanced) ? { advanced: data.advanced } : {},
879
+ index: data.index
880
+ } : null;
881
+ case "cmssy:reorder":
882
+ return Array.isArray(data.blockIds) && data.blockIds.every((id) => typeof id === "string") && data.protocolVersion === PROTOCOL_VERSION ? {
883
+ type: "cmssy:reorder",
884
+ protocolVersion: PROTOCOL_VERSION,
885
+ blockIds: data.blockIds
886
+ } : null;
887
+ case "cmssy:remove":
888
+ return typeof data.blockId === "string" && data.protocolVersion === PROTOCOL_VERSION ? {
889
+ type: "cmssy:remove",
890
+ protocolVersion: PROTOCOL_VERSION,
891
+ blockId: data.blockId
892
+ } : null;
893
+ case "cmssy:drag-over":
894
+ return typeof data.y === "number" && data.protocolVersion === PROTOCOL_VERSION ? {
895
+ type: "cmssy:drag-over",
896
+ protocolVersion: PROTOCOL_VERSION,
897
+ y: data.y
898
+ } : null;
899
+ case "cmssy:drag-end":
900
+ return data.protocolVersion === PROTOCOL_VERSION ? { type: "cmssy:drag-end", protocolVersion: PROTOCOL_VERSION } : null;
901
+ default:
902
+ return null;
903
+ }
904
+ }
905
+
906
+ // src/secret-match.ts
907
+ var MAX_SECRET_LENGTH = 256;
908
+ async function cmssySecretsMatch(a, b) {
909
+ if (a.length > MAX_SECRET_LENGTH || b.length > MAX_SECRET_LENGTH) {
910
+ return false;
911
+ }
912
+ const encoder = new TextEncoder();
913
+ const [ha, hb] = await Promise.all([
914
+ crypto.subtle.digest("SHA-256", encoder.encode(a)),
915
+ crypto.subtle.digest("SHA-256", encoder.encode(b))
916
+ ]);
917
+ const va = new Uint8Array(ha);
918
+ const vb = new Uint8Array(hb);
919
+ let diff = 0;
920
+ for (let i = 0; i < va.length; i += 1) {
921
+ diff |= (va[i] ?? 0) ^ (vb[i] ?? 0);
922
+ }
923
+ return diff === 0;
924
+ }
925
+
926
+ // src/edit-request.ts
927
+ var CMSSY_EDIT_HEADER = "x-cmssy-edit";
928
+ var CMSSY_EDIT_QUERY_PARAM = "cmssyEdit";
929
+ var CMSSY_SECRET_QUERY_PARAM = "cmssySecret";
930
+ async function isVerifiedEditUrl(url, config) {
931
+ if (!url.searchParams.getAll(CMSSY_EDIT_QUERY_PARAM).includes("1")) {
932
+ return false;
933
+ }
934
+ const provided = url.searchParams.get(CMSSY_SECRET_QUERY_PARAM);
935
+ if (!provided || !config.draftSecret) return false;
936
+ return cmssySecretsMatch(provided, config.draftSecret);
937
+ }
938
+
939
+ // src/csp.ts
940
+ function toCspOrigin(origin) {
941
+ if (origin === "*") return "*";
942
+ let parsed;
943
+ try {
944
+ parsed = new URL(origin);
945
+ } catch {
946
+ throw new Error(`cmssy: invalid editorOrigin "${origin}"`);
947
+ }
948
+ if (parsed.origin === "null") {
949
+ throw new Error(`cmssy: editorOrigin "${origin}" has no usable origin`);
950
+ }
951
+ return parsed.origin;
952
+ }
953
+ function frameAncestors(editorOrigin) {
954
+ const resolved = resolveEditorOrigin(editorOrigin);
955
+ const origins = Array.isArray(resolved) ? resolved : [resolved];
956
+ if (origins.length === 0) {
957
+ throw new Error(
958
+ "cmssy: editorOrigin must contain at least one valid origin"
959
+ );
960
+ }
961
+ const normalized = origins.map((origin) => toCspOrigin(origin.trim()));
962
+ return `frame-ancestors ${normalized.join(" ")}`;
963
+ }
964
+ function cmssyCspHeaders(options) {
965
+ return {
966
+ "Content-Security-Policy": frameAncestors(options.editorOrigin)
967
+ };
968
+ }
969
+ function mergeFrameAncestors(existing, directive) {
970
+ if (!existing) return directive;
971
+ const kept = existing.split(";").map((part) => part.trim()).filter((part) => part.length > 0 && !/^frame-ancestors\b/i.test(part));
972
+ kept.push(directive);
973
+ return kept.join("; ");
974
+ }
975
+ function applyCmssyCsp(response, options) {
976
+ const merged = mergeFrameAncestors(
977
+ response.headers.get("Content-Security-Policy"),
978
+ frameAncestors(options.editorOrigin)
979
+ );
980
+ response.headers.set("Content-Security-Policy", merged);
981
+ response.headers.delete("X-Frame-Options");
982
+ return response;
983
+ }
984
+
985
+ // src/seo-paths.ts
986
+ function resolveSeoLocales(config, siteConfig) {
987
+ const defaultLocale = config.defaultLocale ?? siteConfig?.defaultLanguage ?? "en";
988
+ const locales = config.enabledLocales && config.enabledLocales.length > 0 ? config.enabledLocales : siteConfig?.enabledLanguages && siteConfig.enabledLanguages.length > 0 ? siteConfig.enabledLanguages : [defaultLocale];
989
+ return { defaultLocale, locales };
990
+ }
991
+ function normalizeSlug2(slug) {
992
+ if (slug === "/" || slug === "") return "/";
993
+ return slug.startsWith("/") ? slug : `/${slug}`;
994
+ }
995
+ function localizedPath(slug, locale, defaultLocale) {
996
+ const normalized = normalizeSlug2(slug);
997
+ const base = normalized === "/" ? "" : normalized;
998
+ return locale === defaultLocale ? base || "/" : `/${locale}${base}`;
999
+ }
1000
+
1001
+ // src/auth-client.ts
1002
+ var LOGIN_MUTATION = `mutation SiteMemberLogin($input: SiteMemberLoginInput!) {
1003
+ siteMember {
1004
+ login(input: $input) {
1005
+ success message accessToken refreshToken accessTokenExpiresIn
1006
+ }
1007
+ }
1008
+ }`;
1009
+ var REGISTER_MUTATION = `mutation SiteMemberRegister($input: SiteMemberRegisterInput!) {
1010
+ siteMember {
1011
+ register(input: $input) { success message }
1012
+ }
1013
+ }`;
1014
+ var REFRESH_MUTATION = `mutation SiteMemberRefresh($refreshToken: String!) {
1015
+ siteMember {
1016
+ refresh(refreshToken: $refreshToken) {
1017
+ success message accessToken refreshToken accessTokenExpiresIn
1018
+ }
1019
+ }
1020
+ }`;
1021
+ var LOGOUT_MUTATION = `mutation SiteMemberLogout($refreshToken: String!) {
1022
+ siteMember {
1023
+ logout(refreshToken: $refreshToken) { success message }
1024
+ }
1025
+ }`;
1026
+ var LOGOUT_EVERYWHERE_MUTATION = `mutation SiteMemberLogoutEverywhere {
1027
+ siteMember {
1028
+ logoutEverywhere { success message }
1029
+ }
1030
+ }`;
1031
+ var FORGOT_MUTATION = `mutation SiteMemberForgotPassword($modelSlug: String!, $identity: String!) {
1032
+ siteMember {
1033
+ forgotPassword(modelSlug: $modelSlug, identity: $identity) { success message }
1034
+ }
1035
+ }`;
1036
+ var RESET_MUTATION = `mutation SiteMemberResetPassword($token: String!, $newPassword: String!) {
1037
+ siteMember {
1038
+ resetPassword(token: $token, newPassword: $newPassword) { success message }
1039
+ }
1040
+ }`;
1041
+ var VERIFY_MUTATION = `mutation SiteMemberVerifyEmail($token: String!) {
1042
+ siteMember {
1043
+ verifyEmail(token: $token) { success message }
1044
+ }
1045
+ }`;
1046
+ async function authRequest(config, query, variables, label, accessToken) {
1047
+ const workspaceId = await cachedWorkspaceId(config);
1048
+ return graphqlRequest(
1049
+ config,
1050
+ query,
1051
+ variables,
1052
+ {
1053
+ headers: {
1054
+ "x-workspace-id": workspaceId,
1055
+ ...accessToken ? { authorization: `Bearer ${accessToken}` } : {}
1056
+ }
1057
+ },
1058
+ label
1059
+ );
1060
+ }
1061
+ function decodeAccessClaims(accessToken) {
1062
+ const parts = accessToken.split(".");
1063
+ if (parts.length !== 3) return null;
1064
+ try {
1065
+ const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
1066
+ const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
1067
+ const json = JSON.parse(new TextDecoder().decode(bytes));
1068
+ if (typeof json.recordId !== "string" || typeof json.email !== "string" || json.type !== "site_member") {
1069
+ return null;
1070
+ }
1071
+ return { recordId: json.recordId, email: json.email };
1072
+ } catch {
1073
+ return null;
1074
+ }
1075
+ }
1076
+ function toSessionPayload(result) {
1077
+ if (!result.success || !result.accessToken || !result.refreshToken || !result.accessTokenExpiresIn) {
1078
+ return null;
1079
+ }
1080
+ const user = decodeAccessClaims(result.accessToken);
1081
+ if (!user) return null;
1082
+ return {
1083
+ accessToken: result.accessToken,
1084
+ refreshToken: result.refreshToken,
1085
+ accessExpiresAt: Date.now() + result.accessTokenExpiresIn * 1e3,
1086
+ user
1087
+ };
1088
+ }
1089
+ async function backendSignIn(config, modelSlug, identity, password) {
1090
+ const data = await authRequest(
1091
+ config,
1092
+ LOGIN_MUTATION,
1093
+ {
1094
+ input: { modelSlug, identity, password }
1095
+ },
1096
+ "site member login"
1097
+ );
1098
+ return data.siteMember.login;
1099
+ }
1100
+ async function backendRegister(config, modelSlug, identity, password, fields2) {
1101
+ const data = await authRequest(
1102
+ config,
1103
+ REGISTER_MUTATION,
1104
+ {
1105
+ input: { modelSlug, identity, password, fields: fields2 }
1106
+ },
1107
+ "site member register"
1108
+ );
1109
+ return data.siteMember.register;
1110
+ }
1111
+ async function backendRefresh(config, refreshToken) {
1112
+ const data = await authRequest(
1113
+ config,
1114
+ REFRESH_MUTATION,
1115
+ { refreshToken },
1116
+ "site member refresh"
1117
+ );
1118
+ return data.siteMember.refresh;
1119
+ }
1120
+ async function backendSignOut(config, refreshToken) {
1121
+ try {
1122
+ await authRequest(
1123
+ config,
1124
+ LOGOUT_MUTATION,
1125
+ { refreshToken },
1126
+ "site member logout"
1127
+ );
1128
+ } catch {
1129
+ return;
1130
+ }
1131
+ }
1132
+ async function backendSignOutEverywhere(config, accessToken) {
1133
+ try {
1134
+ await authRequest(
1135
+ config,
1136
+ LOGOUT_EVERYWHERE_MUTATION,
1137
+ {},
1138
+ "site member logout everywhere",
1139
+ accessToken
1140
+ );
1141
+ } catch {
1142
+ return;
1143
+ }
1144
+ }
1145
+ async function backendForgotPassword(config, modelSlug, identity) {
1146
+ const data = await authRequest(
1147
+ config,
1148
+ FORGOT_MUTATION,
1149
+ { modelSlug, identity },
1150
+ "site member forgot password"
1151
+ );
1152
+ return data.siteMember.forgotPassword;
1153
+ }
1154
+ async function backendResetPassword(config, token, newPassword) {
1155
+ const data = await authRequest(
1156
+ config,
1157
+ RESET_MUTATION,
1158
+ { token, newPassword },
1159
+ "site member reset password"
1160
+ );
1161
+ return data.siteMember.resetPassword;
1162
+ }
1163
+ async function backendVerifyEmail(config, token) {
1164
+ const data = await authRequest(
1165
+ config,
1166
+ VERIFY_MUTATION,
1167
+ { token },
1168
+ "site member verify email"
1169
+ );
1170
+ return data.siteMember.verifyEmail;
1171
+ }
1172
+
1173
+ // src/cart-client.ts
1174
+ var CART_FIELDS = `
1175
+ id
1176
+ status
1177
+ itemCount
1178
+ subtotal
1179
+ currency
1180
+ discountedTotal
1181
+ tax
1182
+ totalGross
1183
+ pricesIncludeTax
1184
+ shippingTotal
1185
+ taxSummary { rateId name rate base amount }
1186
+ shippingMethod { id label price etaLabel }
1187
+ availableShippingMethods { id label price etaLabel }
1188
+ appliedDiscount { code type value computedAmount }
1189
+ items {
1190
+ id
1191
+ recordId
1192
+ quantity
1193
+ variantSelections
1194
+ unitPrice
1195
+ currentPrice
1196
+ priceMismatch
1197
+ snapshot { name price currency imageUrl sku tiers { minQty price } }
1198
+ }
1199
+ `;
1200
+ var CART_QUERY = `query Cart($workspaceId: ID!) { cart { get(workspaceId: $workspaceId) { ${CART_FIELDS} } } }`;
1201
+ var ADD_TO_CART = `mutation AddToCart($input: AddToCartInput!) { cart { addItem(input: $input) { ${CART_FIELDS} } } }`;
1202
+ var UPDATE_ITEM = `mutation UpdateCartItem($input: UpdateCartItemInput!) { cart { updateItem(input: $input) { ${CART_FIELDS} } } }`;
1203
+ var REMOVE_ITEM = `mutation RemoveCartItem($workspaceId: ID!, $itemId: ID!) { cart { removeItem(workspaceId: $workspaceId, itemId: $itemId) { ${CART_FIELDS} } } }`;
1204
+ var CLEAR_CART = `mutation ClearCart($workspaceId: ID!) { cart { clear(workspaceId: $workspaceId) { ${CART_FIELDS} } } }`;
1205
+ var APPLY_DISCOUNT = `mutation ApplyDiscount($workspaceId: ID!, $code: String!) { cart { applyDiscount(workspaceId: $workspaceId, code: $code) { ${CART_FIELDS} } } }`;
1206
+ var REMOVE_DISCOUNT = `mutation RemoveDiscount($workspaceId: ID!) { cart { removeDiscount(workspaceId: $workspaceId) { ${CART_FIELDS} } } }`;
1207
+ var SET_SHIPPING_METHOD = `mutation SetShippingMethod($workspaceId: ID!, $shippingMethodId: String) {
1208
+ cart { setShippingMethod(workspaceId: $workspaceId, shippingMethodId: $shippingMethodId) { ${CART_FIELDS} } }
1209
+ }`;
1210
+ var MERGE_CART = `mutation MergeCart($workspaceId: ID!) { cart { merge(workspaceId: $workspaceId) { ${CART_FIELDS} } } }`;
1211
+ var CHECKOUT = `mutation Checkout($input: CheckoutInput!) {
1212
+ cart {
1213
+ checkout(input: $input) {
1214
+ id
1215
+ orderNumber
1216
+ status
1217
+ subtotal
1218
+ discount
1219
+ appliedDiscount { code type value amount }
1220
+ tax
1221
+ total
1222
+ currency
1223
+ customerEmail
1224
+ accessToken
1225
+ poNumber
1226
+ customerNote
1227
+ shippingTotal
1228
+ pricesIncludeTax
1229
+ shippingMethod { id label price }
1230
+ shippingAddress { name company line1 line2 postalCode city region country phone vatId }
1231
+ taxSummary { rateId name rate base amount }
1232
+ items { name sku quantity price listPrice tierMinQty currency taxRate taxAmount }
1233
+ }
1234
+ }
1235
+ }`;
1236
+ var PRODUCT = `query Product($workspaceId: String!, $modelSlug: String!, $filter: JSON) {
1237
+ public {
1238
+ model {
1239
+ records(workspaceId: $workspaceId, modelSlug: $modelSlug, filter: $filter, limit: 1) {
1240
+ items {
1241
+ id
1242
+ data
1243
+ priceTiers { minQty price }
1244
+ variants { id sku price inventory tiers { minQty price } selectedOptions { name value } }
1245
+ }
1246
+ }
1247
+ }
1248
+ }
1249
+ }`;
1250
+ async function request(config, ctx, workspaceId, query, variables, label) {
1251
+ return graphqlRequest(
1252
+ config,
1253
+ query,
1254
+ variables,
1255
+ {
1256
+ headers: {
1257
+ "x-workspace-id": workspaceId,
1258
+ "x-cart-session": ctx.cartToken,
1259
+ ...ctx.accessToken ? { authorization: `Bearer ${ctx.accessToken}` } : {}
1260
+ }
1261
+ },
1262
+ label
1263
+ );
1264
+ }
1265
+ async function backendGetCart(config, ctx) {
1266
+ const workspaceId = await cachedWorkspaceId(config);
1267
+ const data = await request(
1268
+ config,
1269
+ ctx,
1270
+ workspaceId,
1271
+ CART_QUERY,
1272
+ { workspaceId },
1273
+ "cart query"
1274
+ );
1275
+ return data.cart.get;
1276
+ }
1277
+ async function backendAddToCart(config, ctx, input) {
1278
+ const workspaceId = await cachedWorkspaceId(config);
1279
+ const data = await request(
1280
+ config,
1281
+ ctx,
1282
+ workspaceId,
1283
+ ADD_TO_CART,
1284
+ { input: { workspaceId, ...input } },
1285
+ "add to cart"
1286
+ );
1287
+ return data.cart.addItem;
1288
+ }
1289
+ async function backendUpdateItem(config, ctx, input) {
1290
+ const workspaceId = await cachedWorkspaceId(config);
1291
+ const data = await request(
1292
+ config,
1293
+ ctx,
1294
+ workspaceId,
1295
+ UPDATE_ITEM,
1296
+ { input: { workspaceId, ...input } },
1297
+ "update cart item"
1298
+ );
1299
+ return data.cart.updateItem;
1300
+ }
1301
+ async function backendRemoveItem(config, ctx, itemId) {
1302
+ const workspaceId = await cachedWorkspaceId(config);
1303
+ const data = await request(
1304
+ config,
1305
+ ctx,
1306
+ workspaceId,
1307
+ REMOVE_ITEM,
1308
+ { workspaceId, itemId },
1309
+ "remove cart item"
1310
+ );
1311
+ return data.cart.removeItem;
1312
+ }
1313
+ async function backendClearCart(config, ctx) {
1314
+ const workspaceId = await cachedWorkspaceId(config);
1315
+ const data = await request(
1316
+ config,
1317
+ ctx,
1318
+ workspaceId,
1319
+ CLEAR_CART,
1320
+ { workspaceId },
1321
+ "clear cart"
1322
+ );
1323
+ return data.cart.clear;
1324
+ }
1325
+ async function backendApplyDiscount(config, ctx, code) {
1326
+ const workspaceId = await cachedWorkspaceId(config);
1327
+ const data = await request(
1328
+ config,
1329
+ ctx,
1330
+ workspaceId,
1331
+ APPLY_DISCOUNT,
1332
+ { workspaceId, code },
1333
+ "apply discount"
1334
+ );
1335
+ return data.cart.applyDiscount;
1336
+ }
1337
+ async function backendRemoveDiscount(config, ctx) {
1338
+ const workspaceId = await cachedWorkspaceId(config);
1339
+ const data = await request(
1340
+ config,
1341
+ ctx,
1342
+ workspaceId,
1343
+ REMOVE_DISCOUNT,
1344
+ { workspaceId },
1345
+ "remove discount"
1346
+ );
1347
+ return data.cart.removeDiscount;
1348
+ }
1349
+ async function backendSetShippingMethod(config, ctx, shippingMethodId) {
1350
+ const workspaceId = await cachedWorkspaceId(config);
1351
+ const data = await request(
1352
+ config,
1353
+ ctx,
1354
+ workspaceId,
1355
+ SET_SHIPPING_METHOD,
1356
+ { workspaceId, shippingMethodId },
1357
+ "set shipping method"
1358
+ );
1359
+ return data.cart.setShippingMethod;
1360
+ }
1361
+ async function backendMergeCart(config, ctx) {
1362
+ const workspaceId = await cachedWorkspaceId(config);
1363
+ const data = await request(
1364
+ config,
1365
+ ctx,
1366
+ workspaceId,
1367
+ MERGE_CART,
1368
+ { workspaceId },
1369
+ "merge cart"
1370
+ );
1371
+ return data.cart.merge;
1372
+ }
1373
+ async function backendCheckout(config, ctx, input) {
1374
+ const workspaceId = await cachedWorkspaceId(config);
1375
+ const data = await request(
1376
+ config,
1377
+ ctx,
1378
+ workspaceId,
1379
+ CHECKOUT,
1380
+ { input: { workspaceId, ...input } },
1381
+ "checkout"
1382
+ );
1383
+ return data.cart.checkout;
1384
+ }
1385
+ async function backendProduct(config, ctx, modelSlug, filter) {
1386
+ const workspaceId = await cachedWorkspaceId(config);
1387
+ const data = await request(
1388
+ config,
1389
+ ctx,
1390
+ workspaceId,
1391
+ PRODUCT,
1392
+ { workspaceId, modelSlug, filter },
1393
+ "product query"
1394
+ );
1395
+ return data.public.model.records.items[0] ?? null;
1396
+ }
1397
+
1398
+ // src/orders-client.ts
1399
+ var ORDER_FIELDS = `
1400
+ id
1401
+ status
1402
+ subtotal
1403
+ discount
1404
+ appliedDiscount { code type value amount }
1405
+ tax
1406
+ total
1407
+ pricesIncludeTax
1408
+ taxSummary { rateId name rate base amount }
1409
+ currency
1410
+ customerEmail
1411
+ refundedAmount
1412
+ paymentProvider
1413
+ paymentStatus
1414
+ fulfillmentStatus
1415
+ amountPaid
1416
+ balanceDue
1417
+ paymentReference
1418
+ trackingNumber
1419
+ trackingCarrier
1420
+ invoiceNumber
1421
+ invoiceUrl
1422
+ invoiceProvider
1423
+ paidAt
1424
+ fulfilledAt
1425
+ createdAt
1426
+ orderNumber
1427
+ poNumber
1428
+ customerNote
1429
+ shippingTotal
1430
+ shippingMethod { id label price }
1431
+ shippingAddress { name company line1 line2 postalCode city region country phone vatId }
1432
+ items { name price listPrice tierMinQty currency quantity sku }
1433
+ payments { amount reference provider at }
1434
+ `;
1435
+ var PUBLIC_ORDER_FIELDS = `
1436
+ id
1437
+ orderNumber
1438
+ status
1439
+ paymentStatus
1440
+ fulfillmentStatus
1441
+ subtotal
1442
+ discount
1443
+ appliedDiscount { code type value amount }
1444
+ tax
1445
+ total
1446
+ pricesIncludeTax
1447
+ taxSummary { rateId name rate base amount }
1448
+ currency
1449
+ customerEmail
1450
+ poNumber
1451
+ customerNote
1452
+ shippingTotal
1453
+ shippingMethod { id label price }
1454
+ shippingAddress { name company line1 line2 postalCode city region country phone vatId }
1455
+ amountPaid
1456
+ balanceDue
1457
+ refundedAmount
1458
+ trackingNumber
1459
+ trackingCarrier
1460
+ invoiceNumber
1461
+ invoiceUrl
1462
+ paidAt
1463
+ fulfilledAt
1464
+ createdAt
1465
+ items { name price listPrice tierMinQty currency quantity sku taxRate taxAmount }
1466
+ `;
1467
+ var MY_ORDERS = `query MyOrders($workspaceId: ID!, $skip: Int, $limit: Int) {
1468
+ account {
1469
+ orders(workspaceId: $workspaceId, skip: $skip, limit: $limit) {
1470
+ total
1471
+ hasMore
1472
+ items { ${ORDER_FIELDS} }
1473
+ }
1474
+ }
1475
+ }`;
1476
+ var MY_ORDER = `query MyOrder($workspaceId: ID!, $id: ID!) {
1477
+ account {
1478
+ order(workspaceId: $workspaceId, id: $id) { ${ORDER_FIELDS} }
1479
+ }
1480
+ }`;
1481
+ var PUBLIC_ORDER_BY_TOKEN = `query PublicOrder($workspaceId: ID!, $orderId: ID!, $accessToken: String!) {
1482
+ public {
1483
+ order {
1484
+ byToken(workspaceId: $workspaceId, orderId: $orderId, accessToken: $accessToken) {
1485
+ ${PUBLIC_ORDER_FIELDS}
1486
+ }
1487
+ }
1488
+ }
1489
+ }`;
1490
+ function headers(workspaceId, accessToken) {
1491
+ return {
1492
+ "x-workspace-id": workspaceId,
1493
+ authorization: `Bearer ${accessToken}`
1494
+ };
1495
+ }
1496
+ async function backendMyOrders(config, accessToken, options) {
1497
+ const workspaceId = await cachedWorkspaceId(config);
1498
+ const data = await graphqlRequest(
1499
+ config,
1500
+ MY_ORDERS,
1501
+ { workspaceId, skip: options.skip, limit: options.limit },
1502
+ { headers: headers(workspaceId, accessToken) },
1503
+ "my orders"
1504
+ );
1505
+ return data.account.orders;
1506
+ }
1507
+ async function backendMyOrder(config, accessToken, id) {
1508
+ const workspaceId = await cachedWorkspaceId(config);
1509
+ const data = await graphqlRequest(
1510
+ config,
1511
+ MY_ORDER,
1512
+ { workspaceId, id },
1513
+ { headers: headers(workspaceId, accessToken) },
1514
+ "my order"
1515
+ );
1516
+ return data.account.order;
1517
+ }
1518
+ async function backendOrderByToken(config, options) {
1519
+ const workspaceId = await cachedWorkspaceId(config);
1520
+ const data = await graphqlRequest(
1521
+ config,
1522
+ PUBLIC_ORDER_BY_TOKEN,
1523
+ {
1524
+ workspaceId,
1525
+ orderId: options.orderId,
1526
+ accessToken: options.accessToken
1527
+ },
1528
+ { headers: { "x-workspace-id": workspaceId } },
1529
+ "public order lookup"
1530
+ );
1531
+ return data.public.order.byToken;
1532
+ }
1533
+
1534
+ // src/commerce/product-client.ts
1535
+ var PRODUCTS_QUERY = `query Products($workspaceId: String!, $modelSlug: String!, $filter: JSON, $stockState: String, $locale: String, $limit: Int, $offset: Int, $sort: String) {
1536
+ public {
1537
+ model {
1538
+ records(workspaceId: $workspaceId, modelSlug: $modelSlug, filter: $filter, stockState: $stockState, locale: $locale, limit: $limit, offset: $offset, sort: $sort) {
1539
+ total
1540
+ hasMore
1541
+ items {
1542
+ id
1543
+ data
1544
+ priceTiers { minQty price }
1545
+ variants { id sku price inventory tiers { minQty price } selectedOptions { name value } }
1546
+ }
1547
+ }
1548
+ }
1549
+ }
1550
+ }`;
1551
+ async function fetchProducts(config, options) {
1552
+ const workspaceId = await resolveWorkspaceId(config);
1553
+ const locale = options.locale ?? null;
1554
+ const data = await graphqlRequest(
1555
+ config,
1556
+ PRODUCTS_QUERY,
1557
+ {
1558
+ workspaceId,
1559
+ modelSlug: options.modelSlug,
1560
+ filter: options.filter ?? {},
1561
+ stockState: options.stockState ?? null,
1562
+ locale,
1563
+ limit: options.limit ?? 50,
1564
+ offset: options.offset ?? 0,
1565
+ sort: options.sort ?? null
1566
+ },
1567
+ { headers: { "x-workspace-id": workspaceId } },
1568
+ "products query"
1569
+ );
1570
+ return data.public.model.records;
1571
+ }
1572
+ async function fetchProduct(config, options) {
1573
+ const page = await fetchProducts(config, {
1574
+ modelSlug: options.modelSlug,
1575
+ filter: { [options.slugField ?? "slug"]: options.slug },
1576
+ locale: options.locale,
1577
+ limit: 1
1578
+ });
1579
+ return page.items[0] ?? null;
1580
+ }
1581
+
1582
+ // src/commerce/order-client.ts
1583
+ async function fetchOrderByToken(config, options) {
1584
+ return backendOrderByToken(config, options);
1585
+ }
1586
+
1587
+ // src/commerce/money.ts
1588
+ var ZERO_DECIMAL = /* @__PURE__ */ new Set([
1589
+ "BIF",
1590
+ "CLP",
1591
+ "DJF",
1592
+ "GNF",
1593
+ "JPY",
1594
+ "KMF",
1595
+ "KRW",
1596
+ "MGA",
1597
+ "PYG",
1598
+ "RWF",
1599
+ "UGX",
1600
+ "VND",
1601
+ "VUV",
1602
+ "XAF",
1603
+ "XOF",
1604
+ "XPF"
1605
+ ]);
1606
+ var THREE_DECIMAL = /* @__PURE__ */ new Set([
1607
+ "BHD",
1608
+ "IQD",
1609
+ "JOD",
1610
+ "KWD",
1611
+ "LYD",
1612
+ "OMR",
1613
+ "TND"
1614
+ ]);
1615
+ function fractionDigits(currency) {
1616
+ const code = currency.toUpperCase();
1617
+ if (ZERO_DECIMAL.has(code)) return 0;
1618
+ if (THREE_DECIMAL.has(code)) return 3;
1619
+ return 2;
1620
+ }
1621
+ function fromMinorUnits(minor, currency) {
1622
+ return minor / 10 ** fractionDigits(currency);
1623
+ }
1624
+ function toMinorUnits(amount, currency) {
1625
+ return Math.round(amount * 10 ** fractionDigits(currency));
1626
+ }
1627
+ function formatPrice(minor, currency) {
1628
+ if (!Number.isFinite(minor)) return "";
1629
+ const code = currency ?? "USD";
1630
+ const amount = fromMinorUnits(minor, code);
1631
+ try {
1632
+ return new Intl.NumberFormat(void 0, {
1633
+ style: "currency",
1634
+ currency: code
1635
+ }).format(amount);
1636
+ } catch {
1637
+ return `${amount.toFixed(fractionDigits(code))} ${code}`;
1638
+ }
1639
+ }
1640
+ var CmssyWebhookError = class extends Error {
1641
+ constructor(message) {
1642
+ super(message);
1643
+ this.name = "CmssyWebhookError";
1644
+ }
1645
+ };
1646
+ var DEFAULT_TOLERANCE_SECONDS = 300;
1647
+ function parseSignatureHeader(header) {
1648
+ let timestamp = null;
1649
+ let signature = null;
1650
+ for (const part of header.split(",")) {
1651
+ const idx = part.indexOf("=");
1652
+ if (idx === -1) continue;
1653
+ const key = part.slice(0, idx).trim();
1654
+ const value = part.slice(idx + 1).trim();
1655
+ if (key === "t") timestamp = Number(value);
1656
+ else if (key === "v1") signature = value;
1657
+ }
1658
+ if (timestamp === null || !Number.isFinite(timestamp) || !signature) {
1659
+ throw new CmssyWebhookError("Malformed X-Cmssy-Signature header");
1660
+ }
1661
+ return { timestamp, signature };
1662
+ }
1663
+ function timingSafeHexEqual(expectedHex, providedHex) {
1664
+ const expected = Buffer.from(expectedHex, "hex");
1665
+ const provided = Buffer.from(providedHex, "hex");
1666
+ if (expected.length !== provided.length) return false;
1667
+ return timingSafeEqual(expected, provided);
1668
+ }
1669
+ function verifyCmssyWebhook(options) {
1670
+ const { body, signatureHeader, secret } = options;
1671
+ if (!signatureHeader) {
1672
+ throw new CmssyWebhookError("Missing X-Cmssy-Signature header");
1673
+ }
1674
+ if (!secret) {
1675
+ throw new CmssyWebhookError("Missing webhook secret");
1676
+ }
1677
+ const { timestamp, signature } = parseSignatureHeader(signatureHeader);
1678
+ const toleranceMs = (options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS) * 1e3;
1679
+ const now = options.now ?? Date.now();
1680
+ if (Math.abs(now - timestamp) > toleranceMs) {
1681
+ throw new CmssyWebhookError("Webhook timestamp outside tolerance");
1682
+ }
1683
+ const expected = createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
1684
+ if (!timingSafeHexEqual(expected, signature)) {
1685
+ throw new CmssyWebhookError("Webhook signature mismatch");
1686
+ }
1687
+ let parsed;
1688
+ try {
1689
+ parsed = JSON.parse(body);
1690
+ } catch {
1691
+ throw new CmssyWebhookError("Webhook body is not valid JSON");
1692
+ }
1693
+ return parsed;
1694
+ }
1695
+
1696
+ export { CMSSY_EDIT_HEADER, CMSSY_EDIT_QUERY_PARAM, CMSSY_LOCALE_HEADER, CMSSY_SECRET_QUERY_PARAM, CMSSY_SESSION_COOKIE, CmssyRequestError, CmssyWebhookError, DEFAULT_CMSSY_API_URL, DEFAULT_CMSSY_EDITOR_ORIGINS, FORM_QUERY, MIN_SESSION_SECRET_LENGTH, MODEL_DEFINITIONS_QUERY, MODEL_RECORDS_QUERY, PRODUCTS_QUERY, PROTOCOL_VERSION, SESSION_MAX_AGE_SECONDS, SITE_CONFIG_QUERY, SUBMIT_FORM_MUTATION, applyCmssyCsp, asBucket, assertAuthConfig, backendAddToCart, backendApplyDiscount, backendCheckout, backendClearCart, backendForgotPassword, backendGetCart, backendMergeCart, backendMyOrder, backendMyOrders, backendOrderByToken, backendProduct, backendRefresh, backendRegister, backendRemoveDiscount, backendRemoveItem, backendResetPassword, backendSetShippingMethod, backendSignIn, backendSignOut, backendSignOutEverywhere, backendUpdateItem, backendVerifyEmail, buildBlockContext, buildLocaleSwitchHref, cachedWorkspaceId, clearWorkspaceIdCache, cmssyCspHeaders, cmssySecretsMatch, collectFormIds, createCmssyClient, decodeAccessClaims, defineCmssyConfig, fetchLayouts, fetchOrderByToken, fetchPage, fetchPageById, fetchPageMeta, fetchPages, fetchProduct, fetchProducts, fetchSiteConfig, fields, formatPrice, fractionDigits, fromMinorUnits, getBlockContentForLanguage, graphqlRequest, isAccessExpired, isDevelopment, isProtocolCompatible, isVerifiedEditUrl, localeForPath, localeForPathname, localizeHref, localizeHtmlLinks, localizedPath, normalizeOrigin, normalizeSlug, openSession, parseEditorMessage, postToEditor, resolveApiUrl, resolveEditorOrigin, resolveForms, resolveInitialTarget, resolvePublicUrl, resolveSeoLocales, resolveSiteLocales, resolveWorkspaceId, sealSession, sessionCookieOptions, splitCmssyLocale, splitLocaleFromPath, toCspOrigin, toMinorUnits, toSessionPayload, verifyCmssyWebhook };