@weaverse/hydrogen 5.7.1 → 5.8.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.d.ts CHANGED
@@ -4,7 +4,8 @@ export { PositionInputValue, WeaverseImage, WeaverseVideo, isBrowser, isIframe,
4
4
  import { PageType, InspectorGroup, SchemaType, ComponentPresets, SchemaValidationResult } from '@weaverse/schema';
5
5
  export * from '@weaverse/schema';
6
6
  export { BasicInput, HeadingInput, InputType, InspectorGroup, PageType, SchemaValidationIssue, SchemaValidationResult } from '@weaverse/schema';
7
- import { createWithCache, I18nBase, HydrogenContext, HydrogenEnv } from '@shopify/hydrogen';
7
+ import { createWithCache, CachingStrategy, I18nBase, HydrogenContext, HydrogenEnv } from '@shopify/hydrogen';
8
+ export { CachingStrategy } from '@shopify/hydrogen';
8
9
  import { LoaderFunctionArgs, AppLoadContext } from '@shopify/remix-oxygen';
9
10
  import * as React$1 from 'react';
10
11
  import { ComponentType, JSX, ForwardRefExoticComponent } from 'react';
@@ -74,31 +75,104 @@ declare class WeaverseClient {
74
75
  env: WeaverseClientArgs['env'];
75
76
  cache: WeaverseClientArgs['cache'];
76
77
  waitUntil: WeaverseClientArgs['waitUntil'];
78
+ private readonly parsedUrl;
79
+ private readonly componentsByType;
80
+ private readonly fetchTimeoutMs;
77
81
  constructor(args: WeaverseClientArgs);
82
+ /**
83
+ * Initialize Hydrogen cache with proper configuration.
84
+ * Logs warning if waitUntil is missing.
85
+ */
86
+ private initializeCache;
87
+ /**
88
+ * Initialize configs with projectId resolution and fail-fast validation.
89
+ * Throws WeaverseError if projectId cannot be resolved.
90
+ */
91
+ private initializeConfigs;
92
+ /**
93
+ * Build component lookup map for O(1) access by type.
94
+ * Significantly improves performance for large component lists.
95
+ */
96
+ private buildComponentLookupMap;
97
+ /**
98
+ * Extract comprehensive error information from unknown error type.
99
+ * Preserves error context, codes, and stack traces for debugging.
100
+ *
101
+ * @param error - Unknown error to extract information from
102
+ * @returns Structured error information with message, code, stack, and context
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * try {
107
+ * // ... operation
108
+ * } catch (error) {
109
+ * const errorInfo = this.extractErrorInfo(error)
110
+ * console.error('Operation failed:', errorInfo.message, errorInfo.context)
111
+ * }
112
+ * ```
113
+ */
114
+ private extractErrorInfo;
115
+ /**
116
+ * Extract error message only (for backward compatibility).
117
+ * Use extractErrorInfo() for more detailed error information.
118
+ *
119
+ * @deprecated Use extractErrorInfo() instead to preserve error context
120
+ */
121
+ private extractErrorMessage;
122
+ /**
123
+ * Validates projectId format (alphanumeric, hyphens, underscores only).
124
+ * Returns detailed validation result with error message.
125
+ *
126
+ * @param projectId - Project identifier to validate
127
+ * @returns Validation result with error message if invalid
128
+ */
129
+ private validateProjectId;
130
+ /**
131
+ * Resolves projectId with multi-project architecture support.
132
+ * Uses priority chain to determine the correct project ID.
133
+ *
134
+ * @param projectId - Project identifier (string, function, or undefined)
135
+ * @param request - HTTP request for context access
136
+ * @param env - Hydrogen environment with variables
137
+ * @param baseConfigs - Pre-fetched base configs to avoid duplicate calls
138
+ * @returns Resolved project ID string (empty string if none found)
139
+ */
140
+ private resolveProjectIdSync;
141
+ /**
142
+ * Priority 1: Resolve projectId from URL query parameters.
143
+ * Used for design mode and preview mode overrides.
144
+ */
145
+ private resolveFromQueryParams;
146
+ /**
147
+ * Priority 2: Resolve projectId from function parameter.
148
+ * Detects and rejects async functions with helpful error.
149
+ */
150
+ private resolveFromFunction;
151
+ /**
152
+ * Priority 3: Resolve projectId from explicit string parameter.
153
+ */
154
+ private resolveFromString;
155
+ /**
156
+ * Priority 4: Resolve projectId from environment variables.
157
+ */
158
+ private resolveFromEnvironment;
159
+ /**
160
+ * Helper method for direct fetching in design mode.
161
+ * Returns same format as withCache.fetch for consistency.
162
+ * Includes 10-second timeout to prevent hanging requests.
163
+ */
78
164
  private readonly directFetch;
79
165
  private isLocalhost;
80
166
  private getApiUrl;
81
167
  fetchWithCache: <T = unknown>(url: string, options?: RequestInit & {
82
- strategy?: AllCacheOptions;
168
+ strategy?: CachingStrategy;
83
169
  }) => Promise<T>;
84
- loadThemeSettings: (strategy?: AllCacheOptions) => Promise<ThemeSettingsResponse>;
170
+ loadThemeSettings: (strategy?: CachingStrategy) => Promise<ThemeSettingsResponse>;
85
171
  generateFallbackPage: (message: string) => HydrogenPageData;
86
- loadPage: (params?: {
87
- type?: PageType;
88
- locale?: string;
89
- handle?: string;
90
- strategy?: AllCacheOptions;
91
- }) => Promise<WeaverseLoaderData | null>;
172
+ loadPage: (params?: LoadPageParams) => Promise<WeaverseLoaderData | null>;
92
173
  execComponentLoader: (item: HydrogenComponentData) => Promise<HydrogenComponentData>;
93
174
  }
94
175
 
95
- type AllCacheOptions = {
96
- mode?: 'must-revalidate' | 'no-cache' | 'no-store' | 'private' | 'public' | string;
97
- maxAge?: number;
98
- staleWhileRevalidate?: number;
99
- sMaxAge?: number;
100
- staleIfError?: number;
101
- };
102
176
  type ComponentLoaderArgs<T = any, _E = any> = {
103
177
  data: T;
104
178
  weaverse: WeaverseClient;
@@ -214,6 +288,11 @@ type HydrogenPageAssignment = {
214
288
  type: PageType;
215
289
  handle: string;
216
290
  locale: string;
291
+ meta?: {
292
+ inherited: boolean;
293
+ sourceProjectId: string;
294
+ depth: number;
295
+ };
217
296
  };
218
297
  type WeaverseLoaderData = {
219
298
  configs: Omit<WeaverseProjectConfigs, 'publicEnv'> & {
@@ -221,7 +300,7 @@ type WeaverseLoaderData = {
221
300
  };
222
301
  page: HydrogenPageData;
223
302
  project: HydrogenProjectType;
224
- pageAssignment: HydrogenPageAssignment;
303
+ pageAssignment?: HydrogenPageAssignment;
225
304
  };
226
305
  interface HydrogenPageData extends WeaverseProjectDataType {
227
306
  id: string;
@@ -271,11 +350,131 @@ type FetchProjectPayload = {
271
350
  error?: string;
272
351
  [key: string]: any;
273
352
  };
353
+ /**
354
+ * Project identifier value - can be static string or dynamic function.
355
+ *
356
+ * **Static String**: Direct project ID reference
357
+ * ```ts
358
+ * 'project-abc-123'
359
+ * ```
360
+ *
361
+ * **Synchronous Function**: Returns project ID based on request context
362
+ * ```ts
363
+ * () => {
364
+ * const host = new URL(request.url).hostname
365
+ * return PROJECT_MAP[host] || 'default-project'
366
+ * }
367
+ * ```
368
+ *
369
+ * **Asynchronous Function**: Async project resolution (must be awaited before passing)
370
+ * ```ts
371
+ * async () => {
372
+ * return await database.getProjectId(userId)
373
+ * }
374
+ * ```
375
+ */
376
+ type ProjectIdValue = string | (() => string) | (() => Promise<string>);
377
+ /**
378
+ * Type guard for detecting function-based projectId.
379
+ *
380
+ * Used internally by WeaverseClient constructor to determine
381
+ * if projectId needs evaluation or can be used directly.
382
+ */
383
+ declare function isProjectIdFunction(projectId: ProjectIdValue | undefined): projectId is (() => string) | (() => Promise<string>);
384
+ /**
385
+ * Extended WeaverseClient constructor arguments supporting multi-project architecture.
386
+ *
387
+ * @example Static project (existing pattern - backward compatible)
388
+ * ```ts
389
+ * const weaverse = new WeaverseClient({
390
+ * ...hydrogenContext,
391
+ * projectId: 'project-default-123'
392
+ * })
393
+ * ```
394
+ *
395
+ * @example Dynamic project selection (new capability)
396
+ * ```ts
397
+ * const weaverse = new WeaverseClient({
398
+ * ...hydrogenContext,
399
+ * projectId: () => {
400
+ * const origin = new URL(request.url).origin
401
+ * if (origin === 'https://mystore.se') return process.env.WEAVERSE_PROJECT_SWEDEN!
402
+ * if (origin === 'https://mystore.fr') return process.env.WEAVERSE_PROJECT_FRANCE!
403
+ * return process.env.WEAVERSE_PROJECT_ID!
404
+ * }
405
+ * })
406
+ * ```
407
+ *
408
+ * **Priority Chain** (highest to lowest):
409
+ * 1. URL query parameter: `?weaverseProjectId=...` (design mode, preview mode)
410
+ * 2. Function result (if function provided)
411
+ * 3. Explicit string value (if string provided)
412
+ * 4. Environment variable: `WEAVERSE_PROJECT_ID` (Hydrogen env or process.env)
413
+ * 5. Empty string (triggers validation error in methods)
414
+ *
415
+ * **Function Requirements**:
416
+ * - Must return non-empty string
417
+ * - Can access request via closure for routing decisions
418
+ * - Evaluated once per WeaverseClient instance (request-scoped)
419
+ * - Async functions must be awaited before passing to constructor
420
+ * - Should handle edge cases (missing headers, invalid domains, etc.)
421
+ *
422
+ * **Request Context Access**:
423
+ * Functions access request via closure from constructor arguments.
424
+ */
274
425
  type WeaverseClientArgs = HydrogenContext & {
426
+ /**
427
+ * React components registered with Weaverse CMS.
428
+ * Each component must have a schema defining its properties and settings.
429
+ */
275
430
  components: HydrogenComponent[];
431
+ /**
432
+ * Theme schema defining global theme settings (colors, fonts, layouts).
433
+ * Used to generate default theme configuration and validate theme data.
434
+ */
276
435
  themeSchema: HydrogenThemeSchema;
436
+ /**
437
+ * Incoming HTTP request object from React Router loader.
438
+ * Provides access to URL, headers, cookies for dynamic routing decisions.
439
+ */
277
440
  request: Request;
441
+ /**
442
+ * Hydrogen cache instance for content caching.
443
+ *Supports multi-tenant caching with project-specific cache keys.
444
+ */
278
445
  cache: Cache;
446
+ /**
447
+ * Project identifier for loading content from Weaverse CMS.
448
+ *
449
+ * **Value Types**:
450
+ * - Static string: 'project-123' (existing usage)
451
+ * - Synchronous function: () => determineProject(request)
452
+ * - Asynchronous function: async () => await getProject(request) (must be awaited)
453
+ *
454
+ * **Backward Compatibility**:
455
+ * - Optional parameter (defaults to environment variable)
456
+ * - Existing code without projectId continues to work unchanged
457
+ *
458
+ * **Cache Isolation**:
459
+ * ProjectId is included in cache keys to prevent cross-project content pollution.
460
+ * Each project's content is cached separately, ensuring multi-tenant isolation.
461
+ */
462
+ projectId?: ProjectIdValue;
463
+ /**
464
+ * Fetch timeout in milliseconds for API requests.
465
+ * Defaults to 10000ms (10 seconds) if not specified.
466
+ * Useful for adjusting based on network conditions or deployment environment.
467
+ *
468
+ * @default 10000
469
+ * @example
470
+ * ```typescript
471
+ * new WeaverseClient({
472
+ * // ... other args
473
+ * fetchTimeoutMs: 5000 // 5 second timeout
474
+ * })
475
+ * ```
476
+ */
477
+ fetchTimeoutMs?: number;
279
478
  };
280
479
  type WeaverseProduct = WeaverseResourcePickerData;
281
480
  type WeaverseCollection = WeaverseResourcePickerData;
@@ -293,6 +492,8 @@ type ThemeSettingsResponse = {
293
492
  theme?: HydrogenThemeSettings;
294
493
  schema?: HydrogenThemeSchema;
295
494
  publicEnv?: PublicEnv;
495
+ _error?: string;
496
+ _loadFailed?: boolean;
296
497
  };
297
498
  type DirectFetchResponse<T = unknown> = {
298
499
  data?: T;
@@ -305,6 +506,14 @@ declare class WeaverseError extends Error {
305
506
  readonly context?: Record<string, unknown>;
306
507
  constructor(message: string, code?: string, statusCode?: number, context?: Record<string, unknown>);
307
508
  }
509
+ /**
510
+ * Validation result type for project ID validation.
511
+ * Returns validation status with optional error message.
512
+ */
513
+ type ProjectIdValidationResult = {
514
+ valid: boolean;
515
+ error?: string;
516
+ };
308
517
  /**
309
518
  * Type guards for response validation
310
519
  */
@@ -319,7 +528,20 @@ declare function isThemeSettingsResponse(data: unknown): data is ThemeSettingsRe
319
528
  */
320
529
  type HydrogenSchemaValidationResult = SchemaValidationResult<HydrogenComponentSchema>;
321
530
  /**
322
- * Type guard to check if a schema is valid
531
+ * Type guard to check if a schema is valid.
532
+ * Leverages validation from @weaverse/schema package which provides
533
+ * comprehensive Zod-based validation with the ElementSchema.
534
+ *
535
+ * @param schema - Unknown value to validate
536
+ * @returns True if schema is a valid HydrogenComponentSchema
537
+ *
538
+ * @example
539
+ * ```typescript
540
+ * if (isValidHydrogenSchema(userInput)) {
541
+ * // userInput is now typed as HydrogenComponentSchema
542
+ * console.log(userInput.type)
543
+ * }
544
+ * ```
323
545
  */
324
546
  declare function isValidHydrogenSchema(schema: unknown): schema is HydrogenComponentSchema;
325
547
  /**
@@ -370,6 +592,101 @@ declare module '@shopify/hydrogen' {
370
592
  PUBLIC_SHOPIFY_INBOX_SHOP_ID: string;
371
593
  }
372
594
  }
595
+ /**
596
+ * Parameters for loadPage method supporting route-level project override.
597
+ *
598
+ * @example Basic usage (uses client-level project)
599
+ * ```ts
600
+ * const weaverseData = await weaverse.loadPage({
601
+ * type: 'PRODUCT',
602
+ * handle: params.productHandle
603
+ * })
604
+ * ```
605
+ *
606
+ * @example Route-level project override
607
+ * ```ts
608
+ * export async function loader({ params, context }: LoaderFunctionArgs) {
609
+ * const { weaverse } = context
610
+ *
611
+ * // Use special campaign project for this route only
612
+ * const weaverseData = await weaverse.loadPage({
613
+ * type: 'PRODUCT',
614
+ * handle: params.productHandle,
615
+ * projectId: process.env.WEAVERSE_PROJECT_CAMPAIGN // Override
616
+ * })
617
+ *
618
+ * return { weaverseData }
619
+ * }
620
+ * ```
621
+ */
622
+ type LoadPageParams = {
623
+ /**
624
+ * Page type to load from Weaverse CMS.
625
+ *
626
+ * Determines which template to use for rendering the page.
627
+ * Falls back to 'INDEX' if not specified or if page type doesn't exist.
628
+ *
629
+ * @default 'INDEX'
630
+ */
631
+ type?: PageType;
632
+ /**
633
+ * Locale for internationalization.
634
+ *
635
+ * Format: IETF BCP 47 language tag (e.g., 'en-US', 'fr-FR', 'de-DE')
636
+ * Used to load locale-specific content and translations.
637
+ */
638
+ locale?: string;
639
+ /**
640
+ * Page handle for dynamic pages.
641
+ *
642
+ * Identifies specific resource within page type:
643
+ * - Product handle: 'red-sneakers'
644
+ * - Collection handle: 'summer-sale'
645
+ * - Page handle: 'about-us'
646
+ * - Article handle: 'how-to-style-sneakers'
647
+ */
648
+ handle?: string;
649
+ /**
650
+ * Cache strategy override for this specific page load.
651
+ *
652
+ * Overrides default cache strategy for special use cases:
653
+ * - Fresh content for checkout pages (no cache)
654
+ * - Long-lived cache for static pages (1 hour+)
655
+ * - Short-lived cache for frequently updated content (5 minutes)
656
+ */
657
+ strategy?: CachingStrategy;
658
+ /**
659
+ * Optional project override for this specific page load.
660
+ *
661
+ * **Precedence**: Route-level projectId takes precedence over client-level projectId.
662
+ *
663
+ * **Use Cases**:
664
+ * - Campaign landing pages with custom content
665
+ * - VIP customer experiences with dedicated projects
666
+ * - A/B testing specific pages without changing global config
667
+ * - Seasonal promotions with limited-time content
668
+ *
669
+ * **Validation**:
670
+ * - Must be non-empty string
671
+ * - Validated before API call
672
+ * - Falls back to client-level projectId if undefined
673
+ * - Does NOT support function (string only)
674
+ *
675
+ * **Cache Isolation**:
676
+ * Override projectId is included in cache key, ensuring separate caches
677
+ * for different projects even on the same route.
678
+ *
679
+ * @example Campaign page override
680
+ * ```ts
681
+ * const campaignData = await weaverse.loadPage({
682
+ * type: 'PAGE',
683
+ * handle: 'summer-sale',
684
+ * projectId: process.env.WEAVERSE_PROJECT_CAMPAIGN
685
+ * })
686
+ * ```
687
+ */
688
+ projectId?: string;
689
+ };
373
690
 
374
691
  declare let defaultComponents: HydrogenComponent[];
375
692
 
@@ -390,8 +707,37 @@ declare function useWeaverseDataContext(): WeaverseDataContext;
390
707
  */
391
708
  declare function createWeaverseDataContext(matches: UIMatch<unknown, unknown>[]): WeaverseDataContext;
392
709
 
393
- declare function getRequestQueries<T = Record<string, string | boolean>>(request: Request): T;
710
+ /**
711
+ * Extract and parse query parameters from a request URL.
712
+ * Supports optional allowlist for security-sensitive applications.
713
+ *
714
+ * @param request - The incoming request
715
+ * @param options - Optional configuration
716
+ * @param options.allowedKeys - If provided, only these keys will be extracted
717
+ * @returns Parsed query parameters with type coercion for booleans
718
+ *
719
+ * @example
720
+ * ```typescript
721
+ * // Extract all params
722
+ * const queries = getRequestQueries(request)
723
+ *
724
+ * // Extract only allowed params (security-sensitive)
725
+ * const queries = getRequestQueries(request, {
726
+ * allowedKeys: ['weaverseProjectId', 'weaverseHost']
727
+ * })
728
+ * ```
729
+ */
730
+ declare function getRequestQueries<T = Record<string, string | boolean>>(request: Request, options?: {
731
+ allowedKeys?: string[];
732
+ }): T;
394
733
  declare function getWeaverseConfigs(request: Request, env: HydrogenEnv): WeaverseProjectConfigs;
734
+ /**
735
+ * Generate default data from component or theme schema.
736
+ * Results are memoized using WeakMap for performance.
737
+ *
738
+ * @param schema - Component or theme schema
739
+ * @returns Default data object extracted from schema inputs
740
+ */
395
741
  declare function generateDataFromSchema(schema: HydrogenComponentSchema | HydrogenThemeSchema): Record<string, any>;
396
742
  declare function getPreviewData(type: string, components: HydrogenComponent[], weaverseHost: string): WeaverseLoaderData;
397
743
 
@@ -428,4 +774,4 @@ declare const IMAGES_PLACEHOLDERS: {
428
774
  product_18: string;
429
775
  };
430
776
 
431
- export { type AllCacheOptions, type CacheResponseValidator, type ComponentLoaderArgs, type CreateHydrogenSchemaOptions, type DirectFetchResponse, type FetchProjectPayload, type FetchProjectRequestBody, type HydrogenComponent, type HydrogenComponentData, type HydrogenComponentPresets, type HydrogenComponentProps, type HydrogenComponentSchema, type HydrogenElement, type HydrogenPageAssignment, type HydrogenPageData, type HydrogenProjectType, type HydrogenSchemaValidationResult, type HydrogenThemeSchema, type HydrogenThemeSettings, IMAGES_PLACEHOLDERS, type PublicEnv, type RouteLoaderArgs, type ThemeSettingsResponse, type WeaverseArticle, type WeaverseBlog, WeaverseClient, type WeaverseClientArgs, type WeaverseCollection, type WeaverseDataContext, WeaverseError, WeaverseHydrogen, WeaverseHydrogenItem, type WeaverseHydrogenParams, WeaverseHydrogenRoot, type WeaverseI18n, type WeaverseInternal, type WeaverseLoaderData, type WeaverseLoaderRequestInfo, type WeaverseMetaObject, type WeaverseProduct, type WeaverseProjectConfigs, type WeaverseStudioQueries, type WithCacheFetchResponse, createWeaverseDataContext, defaultComponents, generateDataFromSchema, getPreviewData, getRequestQueries, getSelectedProductOptions, getWeaverseConfigs, hasError, isFetchProjectPayload, isThemeSettingsResponse, isValidHydrogenSchema, isWithCacheFetchResponse, registerComponent, useThemeSettings, useWeaverseDataContext, withWeaverse };
777
+ export { type CacheResponseValidator, type ComponentLoaderArgs, type CreateHydrogenSchemaOptions, type DirectFetchResponse, type FetchProjectPayload, type FetchProjectRequestBody, type HydrogenComponent, type HydrogenComponentData, type HydrogenComponentPresets, type HydrogenComponentProps, type HydrogenComponentSchema, type HydrogenElement, type HydrogenPageAssignment, type HydrogenPageData, type HydrogenProjectType, type HydrogenSchemaValidationResult, type HydrogenThemeSchema, type HydrogenThemeSettings, IMAGES_PLACEHOLDERS, type LoadPageParams, type ProjectIdValidationResult, type ProjectIdValue, type PublicEnv, type RouteLoaderArgs, type ThemeSettingsResponse, type WeaverseArticle, type WeaverseBlog, WeaverseClient, type WeaverseClientArgs, type WeaverseCollection, type WeaverseDataContext, WeaverseError, WeaverseHydrogen, WeaverseHydrogenItem, type WeaverseHydrogenParams, WeaverseHydrogenRoot, type WeaverseI18n, type WeaverseInternal, type WeaverseLoaderData, type WeaverseLoaderRequestInfo, type WeaverseMetaObject, type WeaverseProduct, type WeaverseProjectConfigs, type WeaverseStudioQueries, type WithCacheFetchResponse, createWeaverseDataContext, defaultComponents, generateDataFromSchema, getPreviewData, getRequestQueries, getSelectedProductOptions, getWeaverseConfigs, hasError, isFetchProjectPayload, isProjectIdFunction, isThemeSettingsResponse, isValidHydrogenSchema, isWithCacheFetchResponse, registerComponent, useThemeSettings, useWeaverseDataContext, withWeaverse };