lynkow 1.40.0 → 1.40.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/README.md +6 -0
- package/dist/index.d.mts +80 -1
- package/dist/index.d.ts +80 -1
- package/dist/index.js +20 -20
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +20 -20
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -69,6 +69,12 @@ interface ClientConfig {
|
|
|
69
69
|
// Optional: Enable SDK in-memory cache (default: false)
|
|
70
70
|
// Set to true for browser SPAs that benefit from localStorage caching
|
|
71
71
|
cache?: boolean
|
|
72
|
+
|
|
73
|
+
// Optional: Auto-retry transient failures on reads (default: true)
|
|
74
|
+
// Retries 429/503/network errors with exponential backoff, honoring the
|
|
75
|
+
// server's Retry-After header. Submissions (POST) are never retried.
|
|
76
|
+
// Set to false to disable, or tune with { retries, backoffMs, maxDelayMs }
|
|
77
|
+
retry?: RetryConfig | boolean
|
|
72
78
|
}
|
|
73
79
|
```
|
|
74
80
|
|
package/dist/index.d.mts
CHANGED
|
@@ -23,6 +23,13 @@ declare function createCache(config?: CacheConfig): {
|
|
|
23
23
|
};
|
|
24
24
|
type Cache = ReturnType<typeof createCache>;
|
|
25
25
|
|
|
26
|
+
/** Resolved (fully-defaulted) retry policy used by the fetch layer. */
|
|
27
|
+
interface ResolvedRetry {
|
|
28
|
+
retries: number;
|
|
29
|
+
backoffMs: number;
|
|
30
|
+
maxDelayMs: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
26
33
|
/**
|
|
27
34
|
* Normalized internal configuration
|
|
28
35
|
*/
|
|
@@ -35,6 +42,8 @@ interface InternalConfig {
|
|
|
35
42
|
fetchOptions: RequestInit;
|
|
36
43
|
/** Optional cache manager for caching responses */
|
|
37
44
|
cache?: Cache;
|
|
45
|
+
/** Optional retry policy for transient failures; normalized once in the service constructor. */
|
|
46
|
+
retry?: RetryConfig | boolean;
|
|
38
47
|
}
|
|
39
48
|
/**
|
|
40
49
|
* Base service that all specific services inherit from
|
|
@@ -42,6 +51,7 @@ interface InternalConfig {
|
|
|
42
51
|
declare abstract class BaseService {
|
|
43
52
|
protected config: InternalConfig;
|
|
44
53
|
protected cache?: Cache;
|
|
54
|
+
protected retry: ResolvedRetry;
|
|
45
55
|
constructor(config: InternalConfig);
|
|
46
56
|
/**
|
|
47
57
|
* Builds the full URL for an endpoint
|
|
@@ -1784,6 +1794,56 @@ interface SearchProfilePublic {
|
|
|
1784
1794
|
maxLimit: number;
|
|
1785
1795
|
}
|
|
1786
1796
|
|
|
1797
|
+
/**
|
|
1798
|
+
* Automatic retry policy for transient failures.
|
|
1799
|
+
*
|
|
1800
|
+
* The SDK retries a request when it fails in a way that is likely to succeed on
|
|
1801
|
+
* a second attempt, using exponential backoff and honoring the server's
|
|
1802
|
+
* `Retry-After` header when present. Retries are enabled by default, which keeps
|
|
1803
|
+
* large static-site builds (SSG/ISR prerender fires many requests at once) from
|
|
1804
|
+
* failing the whole build on a short-lived rate limit.
|
|
1805
|
+
*
|
|
1806
|
+
* Only reads are retried: `GET` requests and text endpoints (sitemap, robots,
|
|
1807
|
+
* llms.txt, markdown) are retried on HTTP 429, HTTP 503, and network errors.
|
|
1808
|
+
* Submissions (`POST`, e.g. form and review submits) are never retried, so a
|
|
1809
|
+
* request that may have been processed is not sent twice.
|
|
1810
|
+
*
|
|
1811
|
+
* Pass `retry: false` to disable retries entirely.
|
|
1812
|
+
*
|
|
1813
|
+
* @example
|
|
1814
|
+
* ```typescript
|
|
1815
|
+
* // Tune the retry policy
|
|
1816
|
+
* createClient({ siteId, retry: { retries: 5, backoffMs: 250, maxDelayMs: 10000 } })
|
|
1817
|
+
*
|
|
1818
|
+
* // Disable retries
|
|
1819
|
+
* createClient({ siteId, retry: false })
|
|
1820
|
+
* ```
|
|
1821
|
+
*/
|
|
1822
|
+
interface RetryConfig {
|
|
1823
|
+
/**
|
|
1824
|
+
* Maximum number of retry attempts after the initial request.
|
|
1825
|
+
* Set to `0` to disable retries (equivalent to `retry: false`).
|
|
1826
|
+
*
|
|
1827
|
+
* @default 3
|
|
1828
|
+
*/
|
|
1829
|
+
retries?: number;
|
|
1830
|
+
/**
|
|
1831
|
+
* Base delay in milliseconds for exponential backoff, used when the response
|
|
1832
|
+
* carries no `Retry-After` header. The nth retry (0-indexed) waits about
|
|
1833
|
+
* `backoffMs * 2^n` plus a small random jitter, capped by `maxDelayMs`.
|
|
1834
|
+
*
|
|
1835
|
+
* @default 500
|
|
1836
|
+
*/
|
|
1837
|
+
backoffMs?: number;
|
|
1838
|
+
/**
|
|
1839
|
+
* Upper bound in milliseconds for any single wait between attempts. Also caps
|
|
1840
|
+
* a large `Retry-After` value, so one rate-limited request can never stall a
|
|
1841
|
+
* build indefinitely.
|
|
1842
|
+
*
|
|
1843
|
+
* @default 20000
|
|
1844
|
+
*/
|
|
1845
|
+
maxDelayMs?: number;
|
|
1846
|
+
}
|
|
1787
1847
|
/**
|
|
1788
1848
|
* Configuration for creating a Lynkow client instance.
|
|
1789
1849
|
* Only `siteId` is required; all other options have sensible defaults.
|
|
@@ -1852,6 +1912,25 @@ interface LynkowConfig {
|
|
|
1852
1912
|
* ```
|
|
1853
1913
|
*/
|
|
1854
1914
|
fetchOptions?: RequestInit;
|
|
1915
|
+
/**
|
|
1916
|
+
* Automatic retry policy for transient failures (HTTP 429, HTTP 503, and
|
|
1917
|
+
* network errors on read requests). Enabled by default with sensible backoff
|
|
1918
|
+
* that honors the server's `Retry-After` header. Pass `false` to disable, or a
|
|
1919
|
+
* {@link RetryConfig} object to tune it. See {@link RetryConfig} for the full
|
|
1920
|
+
* behavior and defaults.
|
|
1921
|
+
*
|
|
1922
|
+
* @default true
|
|
1923
|
+
*
|
|
1924
|
+
* @example
|
|
1925
|
+
* ```typescript
|
|
1926
|
+
* // Disable retries
|
|
1927
|
+
* { retry: false }
|
|
1928
|
+
*
|
|
1929
|
+
* // Tune retries
|
|
1930
|
+
* { retry: { retries: 5, backoffMs: 250, maxDelayMs: 10000 } }
|
|
1931
|
+
* ```
|
|
1932
|
+
*/
|
|
1933
|
+
retry?: RetryConfig | boolean;
|
|
1855
1934
|
}
|
|
1856
1935
|
/**
|
|
1857
1936
|
* Lynkow Client interface -- the main SDK entry point.
|
|
@@ -6915,4 +6994,4 @@ declare function renderJsonLdGraph(nodes: object[] | null | undefined): string;
|
|
|
6915
6994
|
*/
|
|
6916
6995
|
declare function mergeIntoGraph(server: object[] | null | undefined, custom: object[] | null | undefined): object[];
|
|
6917
6996
|
|
|
6918
|
-
export { type Alternate, AnalyticsService, type ApiErrorDetail, type Author, type BaseRequestOptions, BlocksService, BrandingService, type CategoriesListResponse, CategoriesService, type Category, type CategoryDetail, type CategoryDetailResponse, type CategoryOptions, type CategoryResolveResponse, type CategoryTreeNode, type CategoryTreeResponse, type CategoryWithCount, type Client, type ClientConfig, type ConsentCategories, type ConsentLogResponse, ConsentService, type Content, type ContentBody, type ContentResolveResponse, type ContentSchema, type ContentSummary, type ContentsFilters, type ContentsListResponse, ContentsService, type CookieCategory, type CookieConfig, type CookiePreferences, type CookieTexts, CookiesService, type EnhancementsInitOptions, EnhancementsService, type ErrorCode, type EventData, type EventName, type Form, type FormCondition, type FormField, type FormFieldOption, type FormFieldPhoneOptions, type FormFieldType, type FormFieldValidation, type FormPage, type FormSchema, type FormSchemaSettings, type FormSettings, type FormSubmitData, type FormSubmitResponse, FormsService, type GlobalBlock, type GlobalBlockResponse, type ImageVariants, type JsonLdGraphConfig, type JsonLdNode, type JsonLdNodeSource, type LegalDocument, LegalService, type LynkowClient, type LynkowConfig, LynkowError, type LynkowEvents, MediaHelperService, type Page, type PageSeo, type PageSummary, type PagesListResponse, PagesService, type PageviewData, type PaginatedResponse, type PaginationMeta, type PaginationOptions, type Path, type PathsListResponse, PathsService, type Redirect, type ResolveResponse, type Review, type ReviewResponse, type ReviewSettings, type ReviewSubmitData, type ReviewSubmitResponse, type ReviewsFilters, type ReviewsListResponse, ReviewsService, type SchemaField, type SchemaFieldOption, type SchemaFieldType, type SchemaFieldValidation, type SearchConfig, type SearchHit, type SearchOptions, type SearchProfilePublic, type SearchResponse, SearchService, SeoService, type SiteConfig, type SiteConfigResponse, SiteService, type SortOptions, type SrcsetOptions, type SubmitOptions, type Tag, type TagsListFilters, type TagsListResponse, TagsService, type TipTapMark, type TipTapNode, type TransformOptions, browserOnly, browserOnlyAsync, createClient, createLynkowClient, detectSiteTheme, isBrowser, isCategoryResolve, isContentResolve, isLynkowError, isServer, mergeIntoGraph, onSiteThemeChange, renderJsonLdGraph };
|
|
6997
|
+
export { type Alternate, AnalyticsService, type ApiErrorDetail, type Author, type BaseRequestOptions, BlocksService, BrandingService, type CategoriesListResponse, CategoriesService, type Category, type CategoryDetail, type CategoryDetailResponse, type CategoryOptions, type CategoryResolveResponse, type CategoryTreeNode, type CategoryTreeResponse, type CategoryWithCount, type Client, type ClientConfig, type ConsentCategories, type ConsentLogResponse, ConsentService, type Content, type ContentBody, type ContentResolveResponse, type ContentSchema, type ContentSummary, type ContentsFilters, type ContentsListResponse, ContentsService, type CookieCategory, type CookieConfig, type CookiePreferences, type CookieTexts, CookiesService, type EnhancementsInitOptions, EnhancementsService, type ErrorCode, type EventData, type EventName, type Form, type FormCondition, type FormField, type FormFieldOption, type FormFieldPhoneOptions, type FormFieldType, type FormFieldValidation, type FormPage, type FormSchema, type FormSchemaSettings, type FormSettings, type FormSubmitData, type FormSubmitResponse, FormsService, type GlobalBlock, type GlobalBlockResponse, type ImageVariants, type JsonLdGraphConfig, type JsonLdNode, type JsonLdNodeSource, type LegalDocument, LegalService, type LynkowClient, type LynkowConfig, LynkowError, type LynkowEvents, MediaHelperService, type Page, type PageSeo, type PageSummary, type PagesListResponse, PagesService, type PageviewData, type PaginatedResponse, type PaginationMeta, type PaginationOptions, type Path, type PathsListResponse, PathsService, type Redirect, type ResolveResponse, type RetryConfig, type Review, type ReviewResponse, type ReviewSettings, type ReviewSubmitData, type ReviewSubmitResponse, type ReviewsFilters, type ReviewsListResponse, ReviewsService, type SchemaField, type SchemaFieldOption, type SchemaFieldType, type SchemaFieldValidation, type SearchConfig, type SearchHit, type SearchOptions, type SearchProfilePublic, type SearchResponse, SearchService, SeoService, type SiteConfig, type SiteConfigResponse, SiteService, type SortOptions, type SrcsetOptions, type SubmitOptions, type Tag, type TagsListFilters, type TagsListResponse, TagsService, type TipTapMark, type TipTapNode, type TransformOptions, browserOnly, browserOnlyAsync, createClient, createLynkowClient, detectSiteTheme, isBrowser, isCategoryResolve, isContentResolve, isLynkowError, isServer, mergeIntoGraph, onSiteThemeChange, renderJsonLdGraph };
|
package/dist/index.d.ts
CHANGED
|
@@ -23,6 +23,13 @@ declare function createCache(config?: CacheConfig): {
|
|
|
23
23
|
};
|
|
24
24
|
type Cache = ReturnType<typeof createCache>;
|
|
25
25
|
|
|
26
|
+
/** Resolved (fully-defaulted) retry policy used by the fetch layer. */
|
|
27
|
+
interface ResolvedRetry {
|
|
28
|
+
retries: number;
|
|
29
|
+
backoffMs: number;
|
|
30
|
+
maxDelayMs: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
26
33
|
/**
|
|
27
34
|
* Normalized internal configuration
|
|
28
35
|
*/
|
|
@@ -35,6 +42,8 @@ interface InternalConfig {
|
|
|
35
42
|
fetchOptions: RequestInit;
|
|
36
43
|
/** Optional cache manager for caching responses */
|
|
37
44
|
cache?: Cache;
|
|
45
|
+
/** Optional retry policy for transient failures; normalized once in the service constructor. */
|
|
46
|
+
retry?: RetryConfig | boolean;
|
|
38
47
|
}
|
|
39
48
|
/**
|
|
40
49
|
* Base service that all specific services inherit from
|
|
@@ -42,6 +51,7 @@ interface InternalConfig {
|
|
|
42
51
|
declare abstract class BaseService {
|
|
43
52
|
protected config: InternalConfig;
|
|
44
53
|
protected cache?: Cache;
|
|
54
|
+
protected retry: ResolvedRetry;
|
|
45
55
|
constructor(config: InternalConfig);
|
|
46
56
|
/**
|
|
47
57
|
* Builds the full URL for an endpoint
|
|
@@ -1784,6 +1794,56 @@ interface SearchProfilePublic {
|
|
|
1784
1794
|
maxLimit: number;
|
|
1785
1795
|
}
|
|
1786
1796
|
|
|
1797
|
+
/**
|
|
1798
|
+
* Automatic retry policy for transient failures.
|
|
1799
|
+
*
|
|
1800
|
+
* The SDK retries a request when it fails in a way that is likely to succeed on
|
|
1801
|
+
* a second attempt, using exponential backoff and honoring the server's
|
|
1802
|
+
* `Retry-After` header when present. Retries are enabled by default, which keeps
|
|
1803
|
+
* large static-site builds (SSG/ISR prerender fires many requests at once) from
|
|
1804
|
+
* failing the whole build on a short-lived rate limit.
|
|
1805
|
+
*
|
|
1806
|
+
* Only reads are retried: `GET` requests and text endpoints (sitemap, robots,
|
|
1807
|
+
* llms.txt, markdown) are retried on HTTP 429, HTTP 503, and network errors.
|
|
1808
|
+
* Submissions (`POST`, e.g. form and review submits) are never retried, so a
|
|
1809
|
+
* request that may have been processed is not sent twice.
|
|
1810
|
+
*
|
|
1811
|
+
* Pass `retry: false` to disable retries entirely.
|
|
1812
|
+
*
|
|
1813
|
+
* @example
|
|
1814
|
+
* ```typescript
|
|
1815
|
+
* // Tune the retry policy
|
|
1816
|
+
* createClient({ siteId, retry: { retries: 5, backoffMs: 250, maxDelayMs: 10000 } })
|
|
1817
|
+
*
|
|
1818
|
+
* // Disable retries
|
|
1819
|
+
* createClient({ siteId, retry: false })
|
|
1820
|
+
* ```
|
|
1821
|
+
*/
|
|
1822
|
+
interface RetryConfig {
|
|
1823
|
+
/**
|
|
1824
|
+
* Maximum number of retry attempts after the initial request.
|
|
1825
|
+
* Set to `0` to disable retries (equivalent to `retry: false`).
|
|
1826
|
+
*
|
|
1827
|
+
* @default 3
|
|
1828
|
+
*/
|
|
1829
|
+
retries?: number;
|
|
1830
|
+
/**
|
|
1831
|
+
* Base delay in milliseconds for exponential backoff, used when the response
|
|
1832
|
+
* carries no `Retry-After` header. The nth retry (0-indexed) waits about
|
|
1833
|
+
* `backoffMs * 2^n` plus a small random jitter, capped by `maxDelayMs`.
|
|
1834
|
+
*
|
|
1835
|
+
* @default 500
|
|
1836
|
+
*/
|
|
1837
|
+
backoffMs?: number;
|
|
1838
|
+
/**
|
|
1839
|
+
* Upper bound in milliseconds for any single wait between attempts. Also caps
|
|
1840
|
+
* a large `Retry-After` value, so one rate-limited request can never stall a
|
|
1841
|
+
* build indefinitely.
|
|
1842
|
+
*
|
|
1843
|
+
* @default 20000
|
|
1844
|
+
*/
|
|
1845
|
+
maxDelayMs?: number;
|
|
1846
|
+
}
|
|
1787
1847
|
/**
|
|
1788
1848
|
* Configuration for creating a Lynkow client instance.
|
|
1789
1849
|
* Only `siteId` is required; all other options have sensible defaults.
|
|
@@ -1852,6 +1912,25 @@ interface LynkowConfig {
|
|
|
1852
1912
|
* ```
|
|
1853
1913
|
*/
|
|
1854
1914
|
fetchOptions?: RequestInit;
|
|
1915
|
+
/**
|
|
1916
|
+
* Automatic retry policy for transient failures (HTTP 429, HTTP 503, and
|
|
1917
|
+
* network errors on read requests). Enabled by default with sensible backoff
|
|
1918
|
+
* that honors the server's `Retry-After` header. Pass `false` to disable, or a
|
|
1919
|
+
* {@link RetryConfig} object to tune it. See {@link RetryConfig} for the full
|
|
1920
|
+
* behavior and defaults.
|
|
1921
|
+
*
|
|
1922
|
+
* @default true
|
|
1923
|
+
*
|
|
1924
|
+
* @example
|
|
1925
|
+
* ```typescript
|
|
1926
|
+
* // Disable retries
|
|
1927
|
+
* { retry: false }
|
|
1928
|
+
*
|
|
1929
|
+
* // Tune retries
|
|
1930
|
+
* { retry: { retries: 5, backoffMs: 250, maxDelayMs: 10000 } }
|
|
1931
|
+
* ```
|
|
1932
|
+
*/
|
|
1933
|
+
retry?: RetryConfig | boolean;
|
|
1855
1934
|
}
|
|
1856
1935
|
/**
|
|
1857
1936
|
* Lynkow Client interface -- the main SDK entry point.
|
|
@@ -6915,4 +6994,4 @@ declare function renderJsonLdGraph(nodes: object[] | null | undefined): string;
|
|
|
6915
6994
|
*/
|
|
6916
6995
|
declare function mergeIntoGraph(server: object[] | null | undefined, custom: object[] | null | undefined): object[];
|
|
6917
6996
|
|
|
6918
|
-
export { type Alternate, AnalyticsService, type ApiErrorDetail, type Author, type BaseRequestOptions, BlocksService, BrandingService, type CategoriesListResponse, CategoriesService, type Category, type CategoryDetail, type CategoryDetailResponse, type CategoryOptions, type CategoryResolveResponse, type CategoryTreeNode, type CategoryTreeResponse, type CategoryWithCount, type Client, type ClientConfig, type ConsentCategories, type ConsentLogResponse, ConsentService, type Content, type ContentBody, type ContentResolveResponse, type ContentSchema, type ContentSummary, type ContentsFilters, type ContentsListResponse, ContentsService, type CookieCategory, type CookieConfig, type CookiePreferences, type CookieTexts, CookiesService, type EnhancementsInitOptions, EnhancementsService, type ErrorCode, type EventData, type EventName, type Form, type FormCondition, type FormField, type FormFieldOption, type FormFieldPhoneOptions, type FormFieldType, type FormFieldValidation, type FormPage, type FormSchema, type FormSchemaSettings, type FormSettings, type FormSubmitData, type FormSubmitResponse, FormsService, type GlobalBlock, type GlobalBlockResponse, type ImageVariants, type JsonLdGraphConfig, type JsonLdNode, type JsonLdNodeSource, type LegalDocument, LegalService, type LynkowClient, type LynkowConfig, LynkowError, type LynkowEvents, MediaHelperService, type Page, type PageSeo, type PageSummary, type PagesListResponse, PagesService, type PageviewData, type PaginatedResponse, type PaginationMeta, type PaginationOptions, type Path, type PathsListResponse, PathsService, type Redirect, type ResolveResponse, type Review, type ReviewResponse, type ReviewSettings, type ReviewSubmitData, type ReviewSubmitResponse, type ReviewsFilters, type ReviewsListResponse, ReviewsService, type SchemaField, type SchemaFieldOption, type SchemaFieldType, type SchemaFieldValidation, type SearchConfig, type SearchHit, type SearchOptions, type SearchProfilePublic, type SearchResponse, SearchService, SeoService, type SiteConfig, type SiteConfigResponse, SiteService, type SortOptions, type SrcsetOptions, type SubmitOptions, type Tag, type TagsListFilters, type TagsListResponse, TagsService, type TipTapMark, type TipTapNode, type TransformOptions, browserOnly, browserOnlyAsync, createClient, createLynkowClient, detectSiteTheme, isBrowser, isCategoryResolve, isContentResolve, isLynkowError, isServer, mergeIntoGraph, onSiteThemeChange, renderJsonLdGraph };
|
|
6997
|
+
export { type Alternate, AnalyticsService, type ApiErrorDetail, type Author, type BaseRequestOptions, BlocksService, BrandingService, type CategoriesListResponse, CategoriesService, type Category, type CategoryDetail, type CategoryDetailResponse, type CategoryOptions, type CategoryResolveResponse, type CategoryTreeNode, type CategoryTreeResponse, type CategoryWithCount, type Client, type ClientConfig, type ConsentCategories, type ConsentLogResponse, ConsentService, type Content, type ContentBody, type ContentResolveResponse, type ContentSchema, type ContentSummary, type ContentsFilters, type ContentsListResponse, ContentsService, type CookieCategory, type CookieConfig, type CookiePreferences, type CookieTexts, CookiesService, type EnhancementsInitOptions, EnhancementsService, type ErrorCode, type EventData, type EventName, type Form, type FormCondition, type FormField, type FormFieldOption, type FormFieldPhoneOptions, type FormFieldType, type FormFieldValidation, type FormPage, type FormSchema, type FormSchemaSettings, type FormSettings, type FormSubmitData, type FormSubmitResponse, FormsService, type GlobalBlock, type GlobalBlockResponse, type ImageVariants, type JsonLdGraphConfig, type JsonLdNode, type JsonLdNodeSource, type LegalDocument, LegalService, type LynkowClient, type LynkowConfig, LynkowError, type LynkowEvents, MediaHelperService, type Page, type PageSeo, type PageSummary, type PagesListResponse, PagesService, type PageviewData, type PaginatedResponse, type PaginationMeta, type PaginationOptions, type Path, type PathsListResponse, PathsService, type Redirect, type ResolveResponse, type RetryConfig, type Review, type ReviewResponse, type ReviewSettings, type ReviewSubmitData, type ReviewSubmitResponse, type ReviewsFilters, type ReviewsListResponse, ReviewsService, type SchemaField, type SchemaFieldOption, type SchemaFieldType, type SchemaFieldValidation, type SearchConfig, type SearchHit, type SearchOptions, type SearchProfilePublic, type SearchResponse, SearchService, SeoService, type SiteConfig, type SiteConfigResponse, SiteService, type SortOptions, type SrcsetOptions, type SubmitOptions, type Tag, type TagsListFilters, type TagsListResponse, TagsService, type TipTapMark, type TipTapNode, type TransformOptions, browserOnly, browserOnlyAsync, createClient, createLynkowClient, detectSiteTheme, isBrowser, isCategoryResolve, isContentResolve, isLynkowError, isServer, mergeIntoGraph, onSiteThemeChange, renderJsonLdGraph };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var v=class s extends Error{name="LynkowError";code;status;details;cause;constructor(e,t,n,o,r){super(e),this.code=t,this.status=n,this.details=o,this.cause=r,Error.captureStackTrace&&Error.captureStackTrace(this,s);}static async fromResponse(e){let t=e.status,n=`HTTP ${t}`,o;try{let i=await e.json();i.errors&&Array.isArray(i.errors)?(o=i.errors,n=i.errors[0]?.message||n):i.error?n=i.error:i.message&&(n=i.message);}catch{n=e.statusText||n;}let r=s.statusToCode(t);return new s(n,r,t,o)}static fromNetworkError(e){return e.name==="AbortError"?new s("Request timed out","TIMEOUT",void 0,void 0,e):e.name==="TypeError"?new s("Network error - please check your connection","NETWORK_ERROR",void 0,void 0,e):new s(e.message||"Unknown error","UNKNOWN",void 0,void 0,e)}static statusToCode(e){switch(e){case 400:return "VALIDATION_ERROR";case 401:return "UNAUTHORIZED";case 403:return "FORBIDDEN";case 404:return "NOT_FOUND";case 429:return "RATE_LIMITED";default:return "UNKNOWN"}}toJSON(){return {name:this.name,message:this.message,code:this.code,status:this.status,details:this.details}}};function Re(s){return s instanceof v}function xe(s){switch(s){case 400:return "BAD_REQUEST";case 401:return "UNAUTHORIZED";case 403:return "FORBIDDEN";case 404:return "NOT_FOUND";case 422:return "VALIDATION_ERROR";case 429:return "TOO_MANY_REQUESTS";case 503:return "SERVICE_UNAVAILABLE";default:return "INTERNAL_ERROR"}}async function G(s,e){let t;try{t=await fetch(s,e);}catch(a){throw new v("Network error: Unable to reach the server","NETWORK_ERROR",0,[{message:a instanceof Error?a.message:"Unknown error"}])}if(t.ok)return t.json();let n={};try{n=await t.json();}catch{}let o=xe(t.status),r=n.error||n.message||`HTTP error: ${t.status}`,i=n.errors||[{message:r}];throw new v(r,o,t.status,i)}function b(...s){let e={},t=new Map,n=(o,r)=>{let i=o.toLowerCase(),a=t.get(i);a!==void 0&&a!==o&&delete e[a],e[o]=r,t.set(i,o);};for(let o of s)if(o)if(o instanceof Headers)o.forEach((r,i)=>n(i,r));else if(Array.isArray(o))for(let[r,i]of o)n(r,i);else for(let[r,i]of Object.entries(o))n(r,i);return e}function ce(s){let e=new URLSearchParams;for(let[t,n]of Object.entries(s))n!=null&&n!==""&&e.append(t,String(n));return e.toString()}var d={SHORT:300*1e3,MEDIUM:600*1e3,LONG:1800*1e3},m=class{config;cache;constructor(e){this.config=e,this.cache=e.cache;}buildEndpointUrl(e,t){let n=`${this.config.baseUrl}/storefront/${encodeURIComponent(this.config.siteId)}${e}`;if(t&&Object.keys(t).length>0){let o=ce(t);return `${n}?${o}`}return n}async get(e,t,n){let o=n?.locale||this.config.locale,r=o?{...t,locale:o}:t,i=this.buildEndpointUrl(e,r),a=this.mergeFetchOptions(n?.fetchOptions);return G(i,{method:"GET",...a})}async getWithCache(e,t,n,o,r=d.SHORT){return this.cache?this.cache.getOrSet(e,()=>this.get(t,n,o),r):this.get(t,n,o)}invalidateCache(e){this.cache?.invalidate(e);}async post(e,t,n){let o=this.buildEndpointUrl(e),r=this.mergeFetchOptions(n?.fetchOptions);return G(o,{method:"POST",...r,headers:b({"Content-Type":"application/json"},r.headers),body:JSON.stringify(t)})}async getText(e,t){let n=this.buildEndpointUrl(e),o=this.mergeFetchOptions(t?.fetchOptions),r=await fetch(n,{method:"GET",...o});if(!r.ok)throw new Error(`HTTP error: ${r.status}`);return r.text()}mergeFetchOptions(e){return {...this.config.fetchOptions,...e,headers:b(this.config.publishableKey?{"X-Lynkow-Pk":this.config.publishableKey}:void 0,this.config.fetchOptions.headers,e?.headers)}}};var J="contents_",k=class extends m{async list(e,t){let n={};e?.page&&(n.page=e.page),(e?.limit??e?.perPage)&&(n.limit=e?.limit??e?.perPage),e?.category&&(n.category=e.category),e?.tag&&(n.tag=e.tag),e?.search&&(n.search=e.search),e?.sort&&(n.sort=e.sort),e?.order&&(n.order=e.order),e?.locale&&(n.locale=e.locale);let o=`${J}list_${JSON.stringify(e||{})}`;return this.getWithCache(o,"/contents",n,t,d.SHORT)}async getBySlug(e,t){let n=t?.locale||this.config.locale,o=`${J}slug_${e}_${n||"default"}`;return (await this.getWithCache(o,`/contents/slug/${encodeURIComponent(e)}`,void 0,t,d.SHORT)).data}clearCache(){this.invalidateCache(J);}};var j="categories_";function V(s){if(Array.isArray(s))return s.map(V);if(s!==null&&typeof s=="object"){let e=s,t={};for(let n of Object.keys(e).sort())t[n]=V(e[n]);return t}return s}var R=class extends m{async list(e){let t=e?.locale||this.config.locale,n=`${j}list_${t||"default"}`;return (await this.getWithCache(n,"/categories",void 0,e,d.SHORT)).data}async tree(e){let t=e?.locale||this.config.locale,n=`${j}tree_${t||"default"}`;return (await this.getWithCache(n,"/categories/tree",void 0,e,d.SHORT)).data}async getBySlug(e,t){let n={};t?.page&&(n.page=t.page),(t?.limit??t?.perPage)&&(n.limit=t?.limit??t?.perPage);let o=`${j}slug_${e}_${JSON.stringify(V(t||{}))}`;return (await this.getWithCache(o,`/categories/${encodeURIComponent(e)}`,n,t,d.SHORT)).data}clearCache(){this.invalidateCache(j);}};var le="tags_",x=class extends m{async list(e,t){let n={};e?.page&&(n.page=e.page),(e?.limit??e?.perPage)&&(n.limit=e?.limit??e?.perPage),e?.locale&&(n.locale=e.locale);let o=t?.locale||e?.locale||this.config.locale,r=`${le}list_${o||"default"}_${JSON.stringify(e||{})}`;return this.getWithCache(r,"/tags",n,t,d.SHORT)}clearCache(){this.invalidateCache(le);}};var D="pages_",E=class extends m{async list(e){let t=e?.locale||this.config.locale,n={};e?.tag&&(n.tag=e.tag);let o=`${D}list_${t||"default"}_${e?.tag||"all"}`;return this.getWithCache(o,"/pages",n,e,d.SHORT)}async getBySlug(e,t){let n=t?.locale||this.config.locale,o=`${D}slug_${e}_${n||"default"}`;return (await this.getWithCache(o,`/pages/${encodeURIComponent(e)}`,void 0,t,d.SHORT)).data}async getByPath(e,t){let n=t?.locale||this.config.locale,o=`${D}path_${e}_${n||"default"}`;return (await this.getWithCache(o,"/page-by-path",{path:e},t,d.SHORT)).data}async getJsonLd(e,t){let n=t?.locale||this.config.locale,o=`${D}jsonld_${e}_${n||"default"}`;return (await this.getWithCache(o,`/pages/${encodeURIComponent(e)}/json-ld`,void 0,t,d.SHORT)).data}clearCache(){this.invalidateCache(D);}};var X="globals_",S=class extends m{async siteConfig(e){let t=e?.locale||this.config.locale,n=`${X}siteconfig_${t||"default"}`;return this.getWithCache(n,"/site-config",void 0,e,d.MEDIUM)}async getBySlug(e,t){let n=t?.locale||this.config.locale,o=`${X}${e}_${n||"default"}`;return this.getWithCache(o,`/global/${encodeURIComponent(e)}`,void 0,t,d.MEDIUM)}async global(e,t){return this.getBySlug(e,t)}clearCache(){this.invalidateCache(X);}};function z(s){return {_hp:"",_ts:s}}var de="forms_",T=class extends m{sessionStartTime;constructor(e){super(e),this.sessionStartTime=Date.now();}async getBySlug(e){let t=`${de}${e}`;return (await this.getWithCache(t,`/forms/${encodeURIComponent(e)}`,void 0,void 0,d.MEDIUM)).data}async submit(e,t,n){let o=z(this.sessionStartTime),r={data:t,honeypot:o._hp,...o};return n?.recaptchaToken&&(r.recaptchaToken=n.recaptchaToken),(await this.post(`/forms/${encodeURIComponent(e)}/submissions`,r,n)).data}clearCache(){this.invalidateCache(de);}};var q="reviews_",L=class extends m{sessionStartTime;constructor(e){super(e),this.sessionStartTime=Date.now();}async list(e,t){let n={};e?.page&&(n.page=e.page),(e?.limit??e?.perPage)&&(n.limit=e?.limit??e?.perPage),e?.minRating&&(n.minRating=e.minRating),e?.maxRating&&(n.maxRating=e.maxRating),e?.sort&&(n.sort=e.sort),e?.order&&(n.order=e.order);let o=`${q}list_${JSON.stringify(e||{})}`;return this.getWithCache(o,"/reviews",n,t,d.SHORT)}async getBySlug(e){let t=`${q}slug_${e}`;return (await this.getWithCache(t,`/reviews/${encodeURIComponent(e)}`,void 0,void 0,d.SHORT)).data}async settings(){let e=`${q}settings`;return (await this.getWithCache(e,"/reviews/settings",void 0,void 0,d.MEDIUM)).data}async submit(e,t){let n=z(this.sessionStartTime),o={...e,...n};t?.recaptchaToken&&(o._recaptcha_token=t.recaptchaToken);let r=await this.post("/reviews",o,t);return this.invalidateCache(q),r.data}clearCache(){this.invalidateCache(q);}};var pe="site_",O=class extends m{async getConfig(){let e=`${pe}config`;return (await this.getWithCache(e,"/site",void 0,void 0,d.MEDIUM)).data}clearCache(){this.invalidateCache(pe);}};var Y="legal_",I=class extends m{async list(e){let t=e?.locale||this.config.locale,n=`${Y}list_${t||"default"}`;return (await this.getWithCache(n,"/pages",{tag:"legal"},e,d.SHORT)).data}async getBySlug(e,t){let n=t?.locale||this.config.locale,o=`${Y}slug_${e}_${n||"default"}`;return (await this.getWithCache(o,`/pages/${encodeURIComponent(e)}`,void 0,t,d.SHORT)).data}clearCache(){this.invalidateCache(Y);}};var me="cookies_",P=class extends m{async getConfig(){let e=`${me}config`;return (await this.getWithCache(e,"/cookie-consent/config",void 0,void 0,d.MEDIUM)).data}async logConsent(e,t){return this.post("/cookie-consent/logs",{preferences:e},t)}clearCache(){this.invalidateCache(me);}};var B=class extends m{async sitemap(e){return this.getText("/sitemap.xml",e)}async sitemapPart(e,t){return this.getText(`/sitemap-${e}.xml`,t)}async robots(e){return this.getText("/robots.txt",e)}async llmsTxt(e){let t=e?.locale,n=t?`/${t}/llms.txt`:"/llms.txt";return this.getText(n,e)}async llmsFullTxt(e){let t=e?.locale,n=t?`/${t}/llms-full.txt`:"/llms-full.txt";return this.getText(n,e)}async getMarkdown(e,t){let n=e.startsWith("/")?e:`/${e}`;return this.getText(`${n}.md`,t)}};var Q="paths_",$=class extends m{async list(e){let t=e?.locale||this.config.locale,n=`${Q}list_${t||"all"}`;return (await this.getWithCache(n,"/paths",void 0,e,d.SHORT)).data}async resolve(e,t){let n=t?.locale||this.config.locale,o=`${Q}resolve_${e}_${n||"default"}`;return (await this.getWithCache(o,"/resolve",{path:e},t,d.SHORT)).data}async matchRedirect(e,t){try{return (await this.get("/redirects/match",{path:e},t)).data}catch(n){if(n instanceof v&&n.status===404)return null;throw n}}clearCache(){this.invalidateCache(Q);}};var c=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Ee=!c;function Se(s,e){return c?s():e}async function Te(s,e){return c?s():e}var Z="lynkow-tracker",H=class{config;enabled=true;initialized=false;loading=false;loadPromise=null;constructor(e){this.config=e;}getTrackerUrl(){return `${this.config.baseUrl}/analytics/tracker.js`}loadTracker(){return !c||window.LynkowAnalytics?Promise.resolve():this.loadPromise?this.loadPromise:(this.loading=true,this.loadPromise=new Promise((e,t)=>{if(document.getElementById(Z)){let o=setInterval(()=>{window.LynkowAnalytics&&(clearInterval(o),this.loading=false,e());},50);setTimeout(()=>{clearInterval(o),this.loading=false,t(new Error("Tracker script load timeout"));},1e4);return}let n=document.createElement("script");n.id=Z,n.src=this.getTrackerUrl(),n.async=true,n.setAttribute("data-site-id",this.config.siteId),this.config.baseUrl&&n.setAttribute("data-api-url",this.config.baseUrl);try{let o=localStorage.getItem("_lkw_consent_mode");o&&n.setAttribute("data-consent-mode",o);}catch{}n.onload=()=>{this.loading=false,setTimeout(()=>{window.LynkowAnalytics?e():t(new Error("Tracker script loaded but LynkowAnalytics not found"));},0);},n.onerror=()=>{this.loading=false,t(new Error("Failed to load tracker script"));},document.head.appendChild(n);}),this.loadPromise)}async init(){if(!(!c||this.initialized))try{await this.loadTracker(),window.LynkowAnalytics&&!this.initialized&&(this.initialized=!0);}catch(e){console.error("[Lynkow] Failed to initialize analytics:",e);}}async trackEvent(e){!c||!this.enabled||(await this.init(),window.LynkowAnalytics&&window.LynkowAnalytics.track(e));}async trackPageview(e){!c||!this.enabled||(await this.init(),window.LynkowAnalytics&&window.LynkowAnalytics.track({type:"pageview",path:e?.path||window.location.pathname,title:e?.title||document.title,referrer:e?.referrer||document.referrer}));}enable(){this.enabled=true;}disable(){this.enabled=false;}isEnabled(){return this.enabled}isInitialized(){return this.initialized&&!!window.LynkowAnalytics}getTracker(){if(c)return window.LynkowAnalytics}destroy(){if(!c)return;document.getElementById(Z)?.remove(),this.initialized=false,this.loadPromise=null;}};function Le(s){let e=s.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);if(!e||(e[4]!==void 0?parseFloat(e[4]):1)===0)return null;let n=parseInt(e[1],10),o=parseInt(e[2],10),r=parseInt(e[3],10);return (.299*n+.587*o+.114*r)/255}function w(){if(!c)return "light";let s=document.documentElement,e=document.body;for(let t of [s,e])for(let n of ["data-theme","data-mode","data-color-scheme"]){let o=t.getAttribute(n)?.toLowerCase();if(o){if(o.includes("dark"))return "dark";if(o.includes("light"))return "light"}}if(s.classList.contains("dark")||e.classList.contains("dark"))return "dark";try{let t=getComputedStyle(s).colorScheme;if(t){let n=t.toLowerCase().trim();if(n.startsWith("dark"))return "dark";if(n.startsWith("light"))return "light"}}catch{}try{let t=getComputedStyle(e).backgroundColor,n=Le(t);if(n!==null)return n<.5?"dark":"light"}catch{}try{if(window.matchMedia("(prefers-color-scheme: dark)").matches)return "dark"}catch{}return "light"}function A(s){if(!c)return ()=>{};let e=w(),t=[],n=()=>{let i=w();i!==e&&(e=i,s(i));},o=new MutationObserver(n),r={attributes:true,attributeFilter:["data-theme","data-mode","data-color-scheme","class","style"]};o.observe(document.documentElement,r),o.observe(document.body,r),t.push(()=>o.disconnect());try{let i=window.matchMedia("(prefers-color-scheme: dark)"),a=()=>n();i.addEventListener("change",a),t.push(()=>i.removeEventListener("change",a));}catch{}return ()=>t.forEach(i=>i())}var W="_lkw_consent",Oe=365*24*60*60*1e3,ue="lkw-script-",ee={necessary:true,analytics:false,marketing:false,preferences:false},N=class{config;events;bannerElement=null;preferencesElement=null;configCache=null;injectedScriptIds=new Set;themeCleanup=null;constructor(e,t){this.config=e,this.events=t;}async getConfig(){if(this.configCache)return this.configCache;let e=`${this.config.baseUrl}/storefront/${encodeURIComponent(this.config.siteId)}/cookie-consent/config`,t=await fetch(e,{method:"GET",...this.config.fetchOptions,headers:b({"Content-Type":"application/json"},this.config.publishableKey?{"X-Lynkow-Pk":this.config.publishableKey}:void 0,this.config.fetchOptions.headers)});if(!t.ok)throw new Error(`Failed to fetch consent config: ${t.status}`);let n=await t.json();return this.configCache=n.data,this.configCache}async logConsent(e,t){let n=`${this.config.baseUrl}/storefront/${encodeURIComponent(this.config.siteId)}/cookie-consent/logs`;await fetch(n,{method:"POST",body:JSON.stringify({visitorId:this.getOrCreateVisitorId(),action:t||this.inferAction(e),consentGiven:e,pageUrl:c?window.location.href:void 0}),...this.config.fetchOptions,headers:b({"Content-Type":"application/json"},this.config.publishableKey?{"X-Lynkow-Pk":this.config.publishableKey}:void 0,this.config.fetchOptions.headers)}).catch(()=>{});}getOrCreateVisitorId(){if(!c)return "server";let e="_lkw_vid";try{let t=localStorage.getItem(e);return t||(t=crypto.randomUUID(),localStorage.setItem(e,t)),t}catch{return crypto.randomUUID()}}inferAction(e){let t=Object.entries(e).filter(([r])=>r!=="necessary"),n=t.every(([,r])=>r===true),o=t.every(([,r])=>r===false);return n?"accept_all":o?"reject_all":"customize"}getStoredConsent(){if(!c)return null;try{let e=localStorage.getItem(W);if(e){let t=JSON.parse(e);return t.choices?t.timestamp&&Date.now()-t.timestamp>Oe?(localStorage.removeItem(W),null):t.choices:t}}catch{}return null}saveConsent(e){if(c){try{localStorage.setItem(W,JSON.stringify({choices:e,timestamp:Date.now()}));}catch{}this.events.emit("consent-changed",e),document.dispatchEvent(new CustomEvent("lynkow:consent:update",{detail:e}));}}show(){c&&this.getConfig().then(e=>{if(!e.enabled)return;try{e.consentMode&&localStorage.setItem("_lkw_consent_mode",e.consentMode);}catch{}let t=this.getStoredConsent();if(t){this.activateScripts(t);return}if(this.bannerElement)return;this.injectBannerStylesOnce();let n=document.createElement("div");n.innerHTML=this.createBannerHTML(e),this.bannerElement=n.firstElementChild,document.body.appendChild(this.bannerElement),this.attachBannerEvents(),e.theme==="auto"&&!this.themeCleanup&&(this.themeCleanup=A(o=>{this.updateConsentTheme(o);}));});}hide(){c&&(this.bannerElement?.remove(),this.bannerElement=null,this.cleanupThemeObserverIfIdle());}showPreferences(){c&&(this.preferencesElement||this.getConfig().then(e=>{let t=this.getCategories(),n=document.createElement("div");n.innerHTML=this.createPreferencesHTML(e,t),this.preferencesElement=n.firstElementChild,document.body.appendChild(this.preferencesElement),this.attachPreferencesEvents(e),e.theme==="auto"&&!this.themeCleanup&&(this.themeCleanup=A(o=>{this.updateConsentTheme(o);}));}));}getCategories(){return c?this.getStoredConsent()||{...ee}:{...ee}}hasConsented(){return c?this.getStoredConsent()!==null:false}acceptAll(){if(!c)return;let e={necessary:true,analytics:true,marketing:true,preferences:true};this.saveConsent(e),this.logConsent(e,"accept_all"),this.activateScripts(e),this.hide();}rejectAll(){if(!c)return;let e={necessary:true,analytics:false,marketing:false,preferences:false};this.saveConsent(e),this.logConsent(e,"reject_all"),this.hide();}setCategories(e){if(!c)return;let n={...this.getCategories(),...e,necessary:true};this.saveConsent(n),this.logConsent(n,"customize"),this.activateScripts(n);}reset(){if(c){this.removeInjectedScripts();try{localStorage.removeItem(W);}catch{}this.events.emit("consent-changed",{...ee}),this.show();}}activateScripts(e){if(this.configCache?.thirdPartyScripts?.length)for(let[t,n]of Object.entries(e))n&&this.injectScriptsForCategory(t,this.configCache.thirdPartyScripts);}injectScriptsForCategory(e,t){for(let n of t){if(n.category!==e||this.injectedScriptIds.has(n.id))continue;this.injectedScriptIds.add(n.id);let o=document.createElement("div");o.innerHTML=n.script;let r=Array.from(o.children);for(let i=0;i<r.length;i++){let a=r[i],p=`${ue}${n.id}-${i}`;if(a.tagName==="SCRIPT"){let g=document.createElement("script");for(let u of Array.from(a.attributes))g.setAttribute(u.name,u.value);a.textContent&&(g.textContent=a.textContent),g.id=p,document.head.appendChild(g);}else a.id=p,document.body.appendChild(a);}}}removeInjectedScripts(){for(let e of this.injectedScriptIds){let t=0,n;for(;n=document.getElementById(`${ue}${e}-${t}`);)n.remove(),t++;}this.injectedScriptIds.clear();}cleanupThemeObserverIfIdle(){!this.bannerElement&&!this.preferencesElement&&(this.themeCleanup?.(),this.themeCleanup=null);}updateConsentTheme(e){let t=this.configCache?this.resolveColors(this.configCache,e):{bgColor:e==="dark"?"#18181b":"#ffffff",textColor:e==="dark"?"#f4f4f5":"#1a1a1a"},{bgColor:n,textColor:o}=t;if(this.bannerElement&&(this.bannerElement.style.background=n,this.bannerElement.style.color=o),this.preferencesElement){let r=this.preferencesElement.querySelector(":scope > div");r&&(r.style.background=n,r.style.color=o);}}resolveTheme(e){return e==="auto"?w():e==="dark"?"dark":"light"}resolveColors(e,t){if(e.themeStyles?.[t])return e.themeStyles[t];let n=t==="dark";return {primaryColor:e.primaryColor||"#0066cc",bgColor:n?"#18181b":"#ffffff",textColor:n?"#f4f4f5":"#1a1a1a"}}contrastColor(e){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return (.299*t+.587*n+.114*o)/255>.5?"#000000":"#ffffff"}injectBannerStylesOnce(){if(document.getElementById("lynkow-consent-styles"))return;let e=document.createElement("style");e.id="lynkow-consent-styles",e.textContent=`
|
|
1
|
+
'use strict';var v=class o extends Error{name="LynkowError";code;status;details;cause;constructor(e,t,n,r,s){super(e),this.code=t,this.status=n,this.details=r,this.cause=s,Error.captureStackTrace&&Error.captureStackTrace(this,o);}static async fromResponse(e){let t=e.status,n=`HTTP ${t}`,r;try{let i=await e.json();i.errors&&Array.isArray(i.errors)?(r=i.errors,n=i.errors[0]?.message||n):i.error?n=i.error:i.message&&(n=i.message);}catch{n=e.statusText||n;}let s=o.statusToCode(t);return new o(n,s,t,r)}static fromNetworkError(e){return e.name==="AbortError"?new o("Request timed out","TIMEOUT",void 0,void 0,e):e.name==="TypeError"?new o("Network error - please check your connection","NETWORK_ERROR",void 0,void 0,e):new o(e.message||"Unknown error","UNKNOWN",void 0,void 0,e)}static statusToCode(e){switch(e){case 400:return "VALIDATION_ERROR";case 401:return "UNAUTHORIZED";case 403:return "FORBIDDEN";case 404:return "NOT_FOUND";case 429:return "RATE_LIMITED";default:return "UNKNOWN"}}toJSON(){return {name:this.name,message:this.message,code:this.code,status:this.status,details:this.details}}};function Oe(o){return o instanceof v}function Ie(o){switch(o){case 400:return "BAD_REQUEST";case 401:return "UNAUTHORIZED";case 403:return "FORBIDDEN";case 404:return "NOT_FOUND";case 422:return "VALIDATION_ERROR";case 429:return "TOO_MANY_REQUESTS";case 503:return "SERVICE_UNAVAILABLE";default:return "INTERNAL_ERROR"}}var D={retries:3,backoffMs:500,maxDelayMs:2e4},Pe=new Set([429,503]);function Be(o,e){return o==null||!Number.isFinite(o)?e:Math.max(0,Math.trunc(o))}function de(o,e){return o==null||!Number.isFinite(o)||o<0?e:o}function ue(o){return o===false?{...D,retries:0}:o===true||o===void 0?{...D}:{retries:Be(o.retries,D.retries),backoffMs:de(o.backoffMs,D.backoffMs),maxDelayMs:de(o.maxDelayMs,D.maxDelayMs)}}function $e(o,e){return e.signal?.aborted?true:typeof o=="object"&&o!==null&&o.name==="AbortError"}function pe(o){return new Promise(e=>setTimeout(e,o))}function Ae(o){let e=o.headers?.get?.("retry-after");if(!e)return null;let t=Number(e);if(Number.isFinite(t))return Math.max(0,t*1e3);let n=Date.parse(e);return Number.isFinite(n)?Math.max(0,n-Date.now()):null}function me(o,e,t){if(o!=null)return Math.min(o,t.maxDelayMs);let n=t.backoffMs*2**e,r=n*.25*Math.random();return Math.min(n+r,t.maxDelayMs)}async function J(o,e,t={}){let n=t.retry,i=(t.idempotent??false)&&!!n&&n.retries>0?n.retries+1:1,a;for(let p=0;p<i;p++){let g=p===i-1,m;try{m=await fetch(o,e);}catch(l){if(!$e(l,e)&&!g){a=l,await pe(me(null,p,n));continue}throw new v("Network error: Unable to reach the server","NETWORK_ERROR",0,[{message:l instanceof Error?l.message:"Unknown error"}])}if(!g&&Pe.has(m.status)){let l=me(Ae(m),p,n);try{await m.body?.cancel();}catch{}await pe(l);continue}return m}throw new v("Network error: Unable to reach the server","NETWORK_ERROR",0,[{message:a instanceof Error?a.message:"Unknown error"}])}async function V(o,e,t){let n=await J(o,e,t);if(n.ok)return n.json();let r={};try{r=await n.json();}catch{}let s=Ie(n.status),i=r.error||r.message||`HTTP error: ${n.status}`,a=r.errors||[{message:i}];throw new v(i,s,n.status,a)}function b(...o){let e={},t=new Map,n=(r,s)=>{let i=r.toLowerCase(),a=t.get(i);a!==void 0&&a!==r&&delete e[a],e[r]=s,t.set(i,r);};for(let r of o)if(r)if(r instanceof Headers)r.forEach((s,i)=>n(i,s));else if(Array.isArray(r))for(let[s,i]of r)n(s,i);else for(let[s,i]of Object.entries(r))n(s,i);return e}function ge(o){let e=new URLSearchParams;for(let[t,n]of Object.entries(o))n!=null&&n!==""&&e.append(t,String(n));return e.toString()}var d={SHORT:300*1e3,MEDIUM:600*1e3,LONG:1800*1e3},u=class{config;cache;retry;constructor(e){this.config=e,this.cache=e.cache,this.retry=ue(e.retry);}buildEndpointUrl(e,t){let n=`${this.config.baseUrl}/storefront/${encodeURIComponent(this.config.siteId)}${e}`;if(t&&Object.keys(t).length>0){let r=ge(t);return `${n}?${r}`}return n}async get(e,t,n){let r=n?.locale||this.config.locale,s=r?{...t,locale:r}:t,i=this.buildEndpointUrl(e,s),a=this.mergeFetchOptions(n?.fetchOptions);return V(i,{method:"GET",...a},{retry:this.retry,idempotent:true})}async getWithCache(e,t,n,r,s=d.SHORT){return this.cache?this.cache.getOrSet(e,()=>this.get(t,n,r),s):this.get(t,n,r)}invalidateCache(e){this.cache?.invalidate(e);}async post(e,t,n){let r=this.buildEndpointUrl(e),s=this.mergeFetchOptions(n?.fetchOptions);return V(r,{method:"POST",...s,headers:b({"Content-Type":"application/json"},s.headers),body:JSON.stringify(t)},{retry:this.retry,idempotent:false})}async getText(e,t){let n=this.buildEndpointUrl(e),r=this.mergeFetchOptions(t?.fetchOptions),s=await J(n,{method:"GET",...r},{retry:this.retry,idempotent:true});if(!s.ok)throw new Error(`HTTP error: ${s.status}`);return s.text()}mergeFetchOptions(e){return {...this.config.fetchOptions,...e,headers:b(this.config.publishableKey?{"X-Lynkow-Pk":this.config.publishableKey}:void 0,this.config.fetchOptions.headers,e?.headers)}}};var X="contents_",k=class extends u{async list(e,t){let n={};e?.page&&(n.page=e.page),(e?.limit??e?.perPage)&&(n.limit=e?.limit??e?.perPage),e?.category&&(n.category=e.category),e?.tag&&(n.tag=e.tag),e?.search&&(n.search=e.search),e?.sort&&(n.sort=e.sort),e?.order&&(n.order=e.order),e?.locale&&(n.locale=e.locale);let r=`${X}list_${JSON.stringify(e||{})}`;return this.getWithCache(r,"/contents",n,t,d.SHORT)}async getBySlug(e,t){let n=t?.locale||this.config.locale,r=`${X}slug_${e}_${n||"default"}`;return (await this.getWithCache(r,`/contents/slug/${encodeURIComponent(e)}`,void 0,t,d.SHORT)).data}clearCache(){this.invalidateCache(X);}};var z="categories_";function Y(o){if(Array.isArray(o))return o.map(Y);if(o!==null&&typeof o=="object"){let e=o,t={};for(let n of Object.keys(e).sort())t[n]=Y(e[n]);return t}return o}var R=class extends u{async list(e){let t=e?.locale||this.config.locale,n=`${z}list_${t||"default"}`;return (await this.getWithCache(n,"/categories",void 0,e,d.SHORT)).data}async tree(e){let t=e?.locale||this.config.locale,n=`${z}tree_${t||"default"}`;return (await this.getWithCache(n,"/categories/tree",void 0,e,d.SHORT)).data}async getBySlug(e,t){let n={};t?.page&&(n.page=t.page),(t?.limit??t?.perPage)&&(n.limit=t?.limit??t?.perPage);let r=`${z}slug_${e}_${JSON.stringify(Y(t||{}))}`;return (await this.getWithCache(r,`/categories/${encodeURIComponent(e)}`,n,t,d.SHORT)).data}clearCache(){this.invalidateCache(z);}};var he="tags_",x=class extends u{async list(e,t){let n={};e?.page&&(n.page=e.page),(e?.limit??e?.perPage)&&(n.limit=e?.limit??e?.perPage),e?.locale&&(n.locale=e.locale);let r=t?.locale||e?.locale||this.config.locale,s=`${he}list_${r||"default"}_${JSON.stringify(e||{})}`;return this.getWithCache(s,"/tags",n,t,d.SHORT)}clearCache(){this.invalidateCache(he);}};var M="pages_",E=class extends u{async list(e){let t=e?.locale||this.config.locale,n={};e?.tag&&(n.tag=e.tag);let r=`${M}list_${t||"default"}_${e?.tag||"all"}`;return this.getWithCache(r,"/pages",n,e,d.SHORT)}async getBySlug(e,t){let n=t?.locale||this.config.locale,r=`${M}slug_${e}_${n||"default"}`;return (await this.getWithCache(r,`/pages/${encodeURIComponent(e)}`,void 0,t,d.SHORT)).data}async getByPath(e,t){let n=t?.locale||this.config.locale,r=`${M}path_${e}_${n||"default"}`;return (await this.getWithCache(r,"/page-by-path",{path:e},t,d.SHORT)).data}async getJsonLd(e,t){let n=t?.locale||this.config.locale,r=`${M}jsonld_${e}_${n||"default"}`;return (await this.getWithCache(r,`/pages/${encodeURIComponent(e)}/json-ld`,void 0,t,d.SHORT)).data}clearCache(){this.invalidateCache(M);}};var Q="globals_",S=class extends u{async siteConfig(e){let t=e?.locale||this.config.locale,n=`${Q}siteconfig_${t||"default"}`;return this.getWithCache(n,"/site-config",void 0,e,d.MEDIUM)}async getBySlug(e,t){let n=t?.locale||this.config.locale,r=`${Q}${e}_${n||"default"}`;return this.getWithCache(r,`/global/${encodeURIComponent(e)}`,void 0,t,d.MEDIUM)}async global(e,t){return this.getBySlug(e,t)}clearCache(){this.invalidateCache(Q);}};function W(o){return {_hp:"",_ts:o}}var fe="forms_",T=class extends u{sessionStartTime;constructor(e){super(e),this.sessionStartTime=Date.now();}async getBySlug(e){let t=`${fe}${e}`;return (await this.getWithCache(t,`/forms/${encodeURIComponent(e)}`,void 0,void 0,d.MEDIUM)).data}async submit(e,t,n){let r=W(this.sessionStartTime),s={data:t,honeypot:r._hp,...r};return n?.recaptchaToken&&(s.recaptchaToken=n.recaptchaToken),(await this.post(`/forms/${encodeURIComponent(e)}/submissions`,s,n)).data}clearCache(){this.invalidateCache(fe);}};var N="reviews_",L=class extends u{sessionStartTime;constructor(e){super(e),this.sessionStartTime=Date.now();}async list(e,t){let n={};e?.page&&(n.page=e.page),(e?.limit??e?.perPage)&&(n.limit=e?.limit??e?.perPage),e?.minRating&&(n.minRating=e.minRating),e?.maxRating&&(n.maxRating=e.maxRating),e?.sort&&(n.sort=e.sort),e?.order&&(n.order=e.order);let r=`${N}list_${JSON.stringify(e||{})}`;return this.getWithCache(r,"/reviews",n,t,d.SHORT)}async getBySlug(e){let t=`${N}slug_${e}`;return (await this.getWithCache(t,`/reviews/${encodeURIComponent(e)}`,void 0,void 0,d.SHORT)).data}async settings(){let e=`${N}settings`;return (await this.getWithCache(e,"/reviews/settings",void 0,void 0,d.MEDIUM)).data}async submit(e,t){let n=W(this.sessionStartTime),r={...e,...n};t?.recaptchaToken&&(r._recaptcha_token=t.recaptchaToken);let s=await this.post("/reviews",r,t);return this.invalidateCache(N),s.data}clearCache(){this.invalidateCache(N);}};var ye="site_",O=class extends u{async getConfig(){let e=`${ye}config`;return (await this.getWithCache(e,"/site",void 0,void 0,d.MEDIUM)).data}clearCache(){this.invalidateCache(ye);}};var Z="legal_",I=class extends u{async list(e){let t=e?.locale||this.config.locale,n=`${Z}list_${t||"default"}`;return (await this.getWithCache(n,"/pages",{tag:"legal"},e,d.SHORT)).data}async getBySlug(e,t){let n=t?.locale||this.config.locale,r=`${Z}slug_${e}_${n||"default"}`;return (await this.getWithCache(r,`/pages/${encodeURIComponent(e)}`,void 0,t,d.SHORT)).data}clearCache(){this.invalidateCache(Z);}};var ve="cookies_",P=class extends u{async getConfig(){let e=`${ve}config`;return (await this.getWithCache(e,"/cookie-consent/config",void 0,void 0,d.MEDIUM)).data}async logConsent(e,t){return this.post("/cookie-consent/logs",{preferences:e},t)}clearCache(){this.invalidateCache(ve);}};var B=class extends u{async sitemap(e){return this.getText("/sitemap.xml",e)}async sitemapPart(e,t){return this.getText(`/sitemap-${e}.xml`,t)}async robots(e){return this.getText("/robots.txt",e)}async llmsTxt(e){let t=e?.locale,n=t?`/${t}/llms.txt`:"/llms.txt";return this.getText(n,e)}async llmsFullTxt(e){let t=e?.locale,n=t?`/${t}/llms-full.txt`:"/llms-full.txt";return this.getText(n,e)}async getMarkdown(e,t){let n=e.startsWith("/")?e:`/${e}`;return this.getText(`${n}.md`,t)}};var ee="paths_",$=class extends u{async list(e){let t=e?.locale||this.config.locale,n=`${ee}list_${t||"all"}`;return (await this.getWithCache(n,"/paths",void 0,e,d.SHORT)).data}async resolve(e,t){let n=t?.locale||this.config.locale,r=`${ee}resolve_${e}_${n||"default"}`;return (await this.getWithCache(r,"/resolve",{path:e},t,d.SHORT)).data}async matchRedirect(e,t){try{return (await this.get("/redirects/match",{path:e},t)).data}catch(n){if(n instanceof v&&n.status===404)return null;throw n}}clearCache(){this.invalidateCache(ee);}};var c=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",_e=!c;function Fe(o,e){return c?o():e}async function De(o,e){return c?o():e}var te="lynkow-tracker",q=class{config;enabled=true;initialized=false;loading=false;loadPromise=null;constructor(e){this.config=e;}getTrackerUrl(){return `${this.config.baseUrl}/analytics/tracker.js`}loadTracker(){return !c||window.LynkowAnalytics?Promise.resolve():this.loadPromise?this.loadPromise:(this.loading=true,this.loadPromise=new Promise((e,t)=>{if(document.getElementById(te)){let r=setInterval(()=>{window.LynkowAnalytics&&(clearInterval(r),this.loading=false,e());},50);setTimeout(()=>{clearInterval(r),this.loading=false,t(new Error("Tracker script load timeout"));},1e4);return}let n=document.createElement("script");n.id=te,n.src=this.getTrackerUrl(),n.async=true,n.setAttribute("data-site-id",this.config.siteId),this.config.baseUrl&&n.setAttribute("data-api-url",this.config.baseUrl);try{let r=localStorage.getItem("_lkw_consent_mode");r&&n.setAttribute("data-consent-mode",r);}catch{}n.onload=()=>{this.loading=false,setTimeout(()=>{window.LynkowAnalytics?e():t(new Error("Tracker script loaded but LynkowAnalytics not found"));},0);},n.onerror=()=>{this.loading=false,t(new Error("Failed to load tracker script"));},document.head.appendChild(n);}),this.loadPromise)}async init(){if(!(!c||this.initialized))try{await this.loadTracker(),window.LynkowAnalytics&&!this.initialized&&(this.initialized=!0);}catch(e){console.error("[Lynkow] Failed to initialize analytics:",e);}}async trackEvent(e){!c||!this.enabled||(await this.init(),window.LynkowAnalytics&&window.LynkowAnalytics.track(e));}async trackPageview(e){!c||!this.enabled||(await this.init(),window.LynkowAnalytics&&window.LynkowAnalytics.track({type:"pageview",path:e?.path||window.location.pathname,title:e?.title||document.title,referrer:e?.referrer||document.referrer}));}enable(){this.enabled=true;}disable(){this.enabled=false;}isEnabled(){return this.enabled}isInitialized(){return this.initialized&&!!window.LynkowAnalytics}getTracker(){if(c)return window.LynkowAnalytics}destroy(){if(!c)return;document.getElementById(te)?.remove(),this.initialized=false,this.loadPromise=null;}};function Me(o){let e=o.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/);if(!e||(e[4]!==void 0?parseFloat(e[4]):1)===0)return null;let n=parseInt(e[1],10),r=parseInt(e[2],10),s=parseInt(e[3],10);return (.299*n+.587*r+.114*s)/255}function C(){if(!c)return "light";let o=document.documentElement,e=document.body;for(let t of [o,e])for(let n of ["data-theme","data-mode","data-color-scheme"]){let r=t.getAttribute(n)?.toLowerCase();if(r){if(r.includes("dark"))return "dark";if(r.includes("light"))return "light"}}if(o.classList.contains("dark")||e.classList.contains("dark"))return "dark";try{let t=getComputedStyle(o).colorScheme;if(t){let n=t.toLowerCase().trim();if(n.startsWith("dark"))return "dark";if(n.startsWith("light"))return "light"}}catch{}try{let t=getComputedStyle(e).backgroundColor,n=Me(t);if(n!==null)return n<.5?"dark":"light"}catch{}try{if(window.matchMedia("(prefers-color-scheme: dark)").matches)return "dark"}catch{}return "light"}function A(o){if(!c)return ()=>{};let e=C(),t=[],n=()=>{let i=C();i!==e&&(e=i,o(i));},r=new MutationObserver(n),s={attributes:true,attributeFilter:["data-theme","data-mode","data-color-scheme","class","style"]};r.observe(document.documentElement,s),r.observe(document.body,s),t.push(()=>r.disconnect());try{let i=window.matchMedia("(prefers-color-scheme: dark)"),a=()=>n();i.addEventListener("change",a),t.push(()=>i.removeEventListener("change",a));}catch{}return ()=>t.forEach(i=>i())}var G="_lkw_consent",Ne=365*24*60*60*1e3,we="lkw-script-",ne={necessary:true,analytics:false,marketing:false,preferences:false},H=class{config;events;bannerElement=null;preferencesElement=null;configCache=null;injectedScriptIds=new Set;themeCleanup=null;constructor(e,t){this.config=e,this.events=t;}async getConfig(){if(this.configCache)return this.configCache;let e=`${this.config.baseUrl}/storefront/${encodeURIComponent(this.config.siteId)}/cookie-consent/config`,t=await fetch(e,{method:"GET",...this.config.fetchOptions,headers:b({"Content-Type":"application/json"},this.config.publishableKey?{"X-Lynkow-Pk":this.config.publishableKey}:void 0,this.config.fetchOptions.headers)});if(!t.ok)throw new Error(`Failed to fetch consent config: ${t.status}`);let n=await t.json();return this.configCache=n.data,this.configCache}async logConsent(e,t){let n=`${this.config.baseUrl}/storefront/${encodeURIComponent(this.config.siteId)}/cookie-consent/logs`;await fetch(n,{method:"POST",body:JSON.stringify({visitorId:this.getOrCreateVisitorId(),action:t||this.inferAction(e),consentGiven:e,pageUrl:c?window.location.href:void 0}),...this.config.fetchOptions,headers:b({"Content-Type":"application/json"},this.config.publishableKey?{"X-Lynkow-Pk":this.config.publishableKey}:void 0,this.config.fetchOptions.headers)}).catch(()=>{});}getOrCreateVisitorId(){if(!c)return "server";let e="_lkw_vid";try{let t=localStorage.getItem(e);return t||(t=crypto.randomUUID(),localStorage.setItem(e,t)),t}catch{return crypto.randomUUID()}}inferAction(e){let t=Object.entries(e).filter(([s])=>s!=="necessary"),n=t.every(([,s])=>s===true),r=t.every(([,s])=>s===false);return n?"accept_all":r?"reject_all":"customize"}getStoredConsent(){if(!c)return null;try{let e=localStorage.getItem(G);if(e){let t=JSON.parse(e);return t.choices?t.timestamp&&Date.now()-t.timestamp>Ne?(localStorage.removeItem(G),null):t.choices:t}}catch{}return null}saveConsent(e){if(c){try{localStorage.setItem(G,JSON.stringify({choices:e,timestamp:Date.now()}));}catch{}this.events.emit("consent-changed",e),document.dispatchEvent(new CustomEvent("lynkow:consent:update",{detail:e}));}}show(){c&&this.getConfig().then(e=>{if(!e.enabled)return;try{e.consentMode&&localStorage.setItem("_lkw_consent_mode",e.consentMode);}catch{}let t=this.getStoredConsent();if(t){this.activateScripts(t);return}if(this.bannerElement)return;this.injectBannerStylesOnce();let n=document.createElement("div");n.innerHTML=this.createBannerHTML(e),this.bannerElement=n.firstElementChild,document.body.appendChild(this.bannerElement),this.attachBannerEvents(),e.theme==="auto"&&!this.themeCleanup&&(this.themeCleanup=A(r=>{this.updateConsentTheme(r);}));});}hide(){c&&(this.bannerElement?.remove(),this.bannerElement=null,this.cleanupThemeObserverIfIdle());}showPreferences(){c&&(this.preferencesElement||this.getConfig().then(e=>{let t=this.getCategories(),n=document.createElement("div");n.innerHTML=this.createPreferencesHTML(e,t),this.preferencesElement=n.firstElementChild,document.body.appendChild(this.preferencesElement),this.attachPreferencesEvents(e),e.theme==="auto"&&!this.themeCleanup&&(this.themeCleanup=A(r=>{this.updateConsentTheme(r);}));}));}getCategories(){return c?this.getStoredConsent()||{...ne}:{...ne}}hasConsented(){return c?this.getStoredConsent()!==null:false}acceptAll(){if(!c)return;let e={necessary:true,analytics:true,marketing:true,preferences:true};this.saveConsent(e),this.logConsent(e,"accept_all"),this.activateScripts(e),this.hide();}rejectAll(){if(!c)return;let e={necessary:true,analytics:false,marketing:false,preferences:false};this.saveConsent(e),this.logConsent(e,"reject_all"),this.hide();}setCategories(e){if(!c)return;let n={...this.getCategories(),...e,necessary:true};this.saveConsent(n),this.logConsent(n,"customize"),this.activateScripts(n);}reset(){if(c){this.removeInjectedScripts();try{localStorage.removeItem(G);}catch{}this.events.emit("consent-changed",{...ne}),this.show();}}activateScripts(e){if(this.configCache?.thirdPartyScripts?.length)for(let[t,n]of Object.entries(e))n&&this.injectScriptsForCategory(t,this.configCache.thirdPartyScripts);}injectScriptsForCategory(e,t){for(let n of t){if(n.category!==e||this.injectedScriptIds.has(n.id))continue;this.injectedScriptIds.add(n.id);let r=document.createElement("div");r.innerHTML=n.script;let s=Array.from(r.children);for(let i=0;i<s.length;i++){let a=s[i],p=`${we}${n.id}-${i}`;if(a.tagName==="SCRIPT"){let g=document.createElement("script");for(let m of Array.from(a.attributes))g.setAttribute(m.name,m.value);a.textContent&&(g.textContent=a.textContent),g.id=p,document.head.appendChild(g);}else a.id=p,document.body.appendChild(a);}}}removeInjectedScripts(){for(let e of this.injectedScriptIds){let t=0,n;for(;n=document.getElementById(`${we}${e}-${t}`);)n.remove(),t++;}this.injectedScriptIds.clear();}cleanupThemeObserverIfIdle(){!this.bannerElement&&!this.preferencesElement&&(this.themeCleanup?.(),this.themeCleanup=null);}updateConsentTheme(e){let t=this.configCache?this.resolveColors(this.configCache,e):{bgColor:e==="dark"?"#18181b":"#ffffff",textColor:e==="dark"?"#f4f4f5":"#1a1a1a"},{bgColor:n,textColor:r}=t;if(this.bannerElement&&(this.bannerElement.style.background=n,this.bannerElement.style.color=r),this.preferencesElement){let s=this.preferencesElement.querySelector(":scope > div");s&&(s.style.background=n,s.style.color=r);}}resolveTheme(e){return e==="auto"?C():e==="dark"?"dark":"light"}resolveColors(e,t){if(e.themeStyles?.[t])return e.themeStyles[t];let n=t==="dark";return {primaryColor:e.primaryColor||"#0066cc",bgColor:n?"#18181b":"#ffffff",textColor:n?"#f4f4f5":"#1a1a1a"}}contrastColor(e){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return (.299*t+.587*n+.114*r)/255>.5?"#000000":"#ffffff"}injectBannerStylesOnce(){if(document.getElementById("lynkow-consent-styles"))return;let e=document.createElement("style");e.id="lynkow-consent-styles",e.textContent=`
|
|
2
2
|
#lynkow-consent-banner {
|
|
3
3
|
box-sizing: border-box;
|
|
4
4
|
max-height: calc(100vh - 40px);
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
width: 100%;
|
|
45
45
|
text-align: center;
|
|
46
46
|
}
|
|
47
|
-
`,document.head.appendChild(e);}createBannerHTML(e){let t=e.position||"bottom-right",n=e.theme||"light",
|
|
47
|
+
`,document.head.appendChild(e);}createBannerHTML(e){let t=e.position||"bottom-right",n=e.theme||"light",r=e.borderRadius??8,s=e.fontSize??13,i=e.orientation||"auto",a=e.maxWidth??580,p={"bottom-left":`bottom: 20px; left: 20px; max-width: ${a}px; border-radius: ${r}px;`,"bottom-right":`bottom: 20px; right: 20px; max-width: ${a}px; border-radius: ${r}px;`},g=p[t]||p["bottom-right"],m=this.resolveTheme(n),l=this.resolveColors(e,m),{primaryColor:h,bgColor:f,textColor:y}=l,F=e.texts||{description:"Ce site utilise des cookies pour ameliorer votre experience.",acceptAll:"Accepter tout",rejectAll:"Refuser",customize:"Personnaliser"};return `
|
|
48
48
|
<div id="lynkow-consent-banner"${i==="column"?' class="orientation-column"':""} style="
|
|
49
49
|
position: fixed;
|
|
50
50
|
${g}
|
|
@@ -54,11 +54,11 @@
|
|
|
54
54
|
color: ${y};
|
|
55
55
|
box-shadow: 0 4px 20px rgba(0,0,0,0.15);
|
|
56
56
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
57
|
-
font-size: ${
|
|
57
|
+
font-size: ${s}px;
|
|
58
58
|
">
|
|
59
59
|
<div class="lynkow-consent-row" style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap;">
|
|
60
60
|
<p style="margin: 0; line-height: 1.5; flex: 1; min-width: 200px;">
|
|
61
|
-
${F.description}${(()=>{let
|
|
61
|
+
${F.description}${(()=>{let le=e.cookiePolicyUrl||e.privacyPolicyUrl;if(!le)return "";let Le=F.privacyPolicy||"En savoir plus";return ` <a href="${le}" target="_blank" rel="noopener" style="text-decoration: underline; color: inherit;">${Le}</a>`})()}
|
|
62
62
|
</p>
|
|
63
63
|
<div class="lynkow-consent-actions" style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
|
|
64
64
|
<button id="lynkow-consent-accept" style="
|
|
@@ -66,9 +66,9 @@
|
|
|
66
66
|
background: ${h};
|
|
67
67
|
color: ${this.contrastColor(h)};
|
|
68
68
|
border: none;
|
|
69
|
-
border-radius: ${
|
|
69
|
+
border-radius: ${r}px;
|
|
70
70
|
cursor: pointer;
|
|
71
|
-
font-size: ${
|
|
71
|
+
font-size: ${s}px;
|
|
72
72
|
white-space: nowrap;
|
|
73
73
|
">${F.acceptAll}</button>
|
|
74
74
|
<button id="lynkow-consent-reject" style="
|
|
@@ -76,9 +76,9 @@
|
|
|
76
76
|
background: transparent;
|
|
77
77
|
color: inherit;
|
|
78
78
|
border: 1px solid currentColor;
|
|
79
|
-
border-radius: ${
|
|
79
|
+
border-radius: ${r}px;
|
|
80
80
|
cursor: pointer;
|
|
81
|
-
font-size: ${
|
|
81
|
+
font-size: ${s}px;
|
|
82
82
|
white-space: nowrap;
|
|
83
83
|
">${F.rejectAll}</button>
|
|
84
84
|
${e.showCustomizeButton!==false?`<button id="lynkow-consent-preferences" style="
|
|
@@ -87,14 +87,14 @@
|
|
|
87
87
|
color: inherit;
|
|
88
88
|
border: none;
|
|
89
89
|
cursor: pointer;
|
|
90
|
-
font-size: ${
|
|
90
|
+
font-size: ${s}px;
|
|
91
91
|
text-decoration: underline;
|
|
92
92
|
white-space: nowrap;
|
|
93
93
|
">${F.customize}</button>`:""}
|
|
94
94
|
</div>
|
|
95
95
|
</div>
|
|
96
96
|
</div>
|
|
97
|
-
`}createPreferencesHTML(e,t){let n=e.theme||"light",
|
|
97
|
+
`}createPreferencesHTML(e,t){let n=e.theme||"light",r=e.borderRadius??8,s=e.fontSize??13,i=this.resolveTheme(n),a=this.resolveColors(e,i),{primaryColor:p,bgColor:g,textColor:m}=a,l=e.texts||{save:"Enregistrer"},f=(e.categories||[]).map(y=>`
|
|
98
98
|
<label style="display: flex; align-items: flex-start; gap: 10px; margin: 15px 0; cursor: ${y.required?"not-allowed":"pointer"};">
|
|
99
99
|
<input
|
|
100
100
|
type="checkbox"
|
|
@@ -128,9 +128,9 @@
|
|
|
128
128
|
">
|
|
129
129
|
<div style="
|
|
130
130
|
background: ${g};
|
|
131
|
-
color: ${
|
|
131
|
+
color: ${m};
|
|
132
132
|
padding: 30px;
|
|
133
|
-
border-radius: ${
|
|
133
|
+
border-radius: ${r}px;
|
|
134
134
|
max-width: 500px;
|
|
135
135
|
width: 90%;
|
|
136
136
|
max-height: 80vh;
|
|
@@ -145,24 +145,24 @@
|
|
|
145
145
|
background: ${p};
|
|
146
146
|
color: ${this.contrastColor(p)};
|
|
147
147
|
border: none;
|
|
148
|
-
border-radius: ${
|
|
148
|
+
border-radius: ${r}px;
|
|
149
149
|
cursor: pointer;
|
|
150
|
-
font-size: ${
|
|
150
|
+
font-size: ${s}px;
|
|
151
151
|
">${l.save||"Enregistrer"}</button>
|
|
152
152
|
<button type="button" id="lynkow-consent-close" style="
|
|
153
153
|
padding: 10px 20px;
|
|
154
154
|
background: transparent;
|
|
155
155
|
color: inherit;
|
|
156
156
|
border: 1px solid currentColor;
|
|
157
|
-
border-radius: ${
|
|
157
|
+
border-radius: ${r}px;
|
|
158
158
|
cursor: pointer;
|
|
159
|
-
font-size: ${
|
|
159
|
+
font-size: ${s}px;
|
|
160
160
|
">Annuler</button>
|
|
161
161
|
</div>
|
|
162
162
|
</form>
|
|
163
163
|
</div>
|
|
164
164
|
</div>
|
|
165
|
-
`}attachBannerEvents(){let e=document.getElementById("lynkow-consent-accept"),t=document.getElementById("lynkow-consent-reject"),n=document.getElementById("lynkow-consent-preferences");e?.addEventListener("click",()=>{this.acceptAll();}),t?.addEventListener("click",()=>{this.rejectAll();}),n?.addEventListener("click",()=>{this.showPreferences();});}attachPreferencesEvents(e){let t=document.getElementById("lynkow-consent-form"),n=document.getElementById("lynkow-consent-close"),
|
|
165
|
+
`}attachBannerEvents(){let e=document.getElementById("lynkow-consent-accept"),t=document.getElementById("lynkow-consent-reject"),n=document.getElementById("lynkow-consent-preferences");e?.addEventListener("click",()=>{this.acceptAll();}),t?.addEventListener("click",()=>{this.rejectAll();}),n?.addEventListener("click",()=>{this.showPreferences();});}attachPreferencesEvents(e){let t=document.getElementById("lynkow-consent-form"),n=document.getElementById("lynkow-consent-close"),r=document.getElementById("lynkow-consent-preferences-modal");t?.addEventListener("submit",s=>{s.preventDefault();let i=new FormData(t),a={necessary:true,analytics:i.has("analytics"),marketing:i.has("marketing"),preferences:i.has("preferences")};this.setCategories(a),this.hide(),this.preferencesElement?.remove(),this.preferencesElement=null,this.cleanupThemeObserverIfIdle();}),n?.addEventListener("click",()=>{this.preferencesElement?.remove(),this.preferencesElement=null,this.cleanupThemeObserverIfIdle();}),r?.addEventListener("click",s=>{s.target===r&&(this.preferencesElement?.remove(),this.preferencesElement=null,this.cleanupThemeObserverIfIdle());});}destroy(){this.themeCleanup?.(),this.themeCleanup=null,this.hide(),this.preferencesElement?.remove(),this.preferencesElement=null,this.removeInjectedScripts();}};var oe="lynkow-badge-container",re="lynkow-badge-styles",U=class extends u{containerElement=null;themeCleanup=null;async inject(){if(c&&!document.getElementById(oe))try{let{data:e}=await this.getWithCache("branding:badge","/branding/badge",void 0,void 0,d.LONG);if(!document.getElementById(re)){let n=document.createElement("style");n.id=re,n.textContent=e.css,document.head.appendChild(n);}let t=document.createElement("div");t.id=oe,t.innerHTML=e.html,C()==="light"&&t.classList.add("lynkow-badge-light"),document.body.appendChild(t),this.containerElement=t,this.themeCleanup=A(n=>{this.containerElement&&this.containerElement.classList.toggle("lynkow-badge-light",n==="light");});}catch{}}remove(){c&&(this.themeCleanup?.(),this.themeCleanup=null,this.containerElement?.remove(),this.containerElement=null,document.getElementById(re)?.remove());}isVisible(){return c?document.getElementById(oe)!==null:false}destroy(){this.remove();}};var se="lynkow-enhancements-styles",ie="lynkow-enhancements-code-block-styles",ae="data-lynkow-clone",qe=new Set(["","module","text/plain","text/javascript","application/javascript","application/ecmascript","text/ecmascript","application/x-javascript","application/x-ecmascript"]),He='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>',Ue='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',Ke=`
|
|
166
166
|
/*
|
|
167
167
|
* Lynkow Content Enhancements, generic CSS reset & inline-style preservation.
|
|
168
168
|
* Always injected. Independent of code-block styling.
|
|
@@ -179,7 +179,7 @@
|
|
|
179
179
|
h1, h2, h3, h4, h5, h6, p, blockquote {
|
|
180
180
|
text-align: inherit;
|
|
181
181
|
}
|
|
182
|
-
`,
|
|
182
|
+
`,je=`
|
|
183
183
|
/*
|
|
184
184
|
* Lynkow Content Enhancements, code-block styling + copy button.
|
|
185
185
|
* Variable-based: consumers can override any --lynkow-code-* var without !important.
|
|
@@ -289,6 +289,6 @@
|
|
|
289
289
|
line-height: 1.5;
|
|
290
290
|
color: var(--lynkow-code-fg);
|
|
291
291
|
}
|
|
292
|
-
`,K=class{initialized=false;observer=null;pendingFrame=null;handleWidgetResize=e=>{if(!e.data||e.data.type!=="lynkow-widget-resize")return;document.querySelectorAll('iframe[src*="/widgets/calendar/"]').forEach(n=>{n.contentWindow===e.source&&(n.style.height=e.data.height+"px");});};injectGenericStyles(){if(!c||document.getElementById(oe))return;let e=document.createElement("style");e.id=oe,e.textContent=$e,document.head.appendChild(e);}injectCodeBlockStyles(){if(!c||document.getElementById(re))return;let e=document.createElement("style");e.id=re,e.textContent=Ae,document.head.appendChild(e);}async handleCopyClick(e){let t=e.closest(".code-block");if(!t)return;let n=t.querySelector("code");if(!n)return;let o=n.textContent||"";try{await navigator.clipboard.writeText(o),e.classList.add("copied"),e.innerHTML=Be,setTimeout(()=>{e.classList.remove("copied"),e.innerHTML=Pe;},2e3);}catch(r){console.error("Lynkow SDK: Failed to copy code",r);}}bindCodeBlockCopy(){if(!c)return;document.querySelectorAll("[data-copy-code]").forEach(t=>{t.dataset.lynkowBound||(t.dataset.lynkowBound="true",t.addEventListener("click",n=>{n.preventDefault(),this.handleCopyClick(t);}));});}activateScripts(e){if(!c)return;let n=(e instanceof HTMLElement?e:document.body).querySelectorAll("script:not([data-lynkow-activated])"),o=Array.from(n).filter(r=>!r.src&&r.isConnected&&Ie.has(r.type.toLowerCase()));o.length!==0&&(document.head.querySelectorAll(`script[${se}]`).forEach(r=>r.remove()),o.forEach(r=>{r.setAttribute("data-lynkow-activated","true");let i=document.createElement("script"),a=r.attributes;for(let p=0;p<a.length;p++){let g=a[p];g&&(g.name==="type"&&g.value==="text/plain"||g.name!=="data-lynkow-activated"&&i.setAttribute(g.name,g.value));}i.textContent=r.textContent,i.setAttribute(se,""),document.head.appendChild(i);}));}init(e={}){if(!c||this.initialized)return;let{codeBlocks:t=true}=e;this.injectGenericStyles(),this.activateScripts(),window.addEventListener("message",this.handleWidgetResize),t&&(this.injectCodeBlockStyles(),this.bindCodeBlockCopy()),this.observer||(this.observer=new MutationObserver(()=>{this.pendingFrame===null&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=null,this.activateScripts(),t&&this.bindCodeBlockCopy();}));}),this.observer.observe(document.body,{childList:true,subtree:true})),this.initialized=true;}isInitialized(){return this.initialized}destroy(){c&&(window.removeEventListener("message",this.handleWidgetResize),this.pendingFrame!==null&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=null),this.observer&&(this.observer.disconnect(),this.observer=null),document.getElementById(oe)?.remove(),document.getElementById(re)?.remove(),document.head.querySelectorAll(`script[${se}]`).forEach(e=>e.remove()),this.initialized=false);}};var U=class{srcset(e,t={}){if(!e)return "";let{widths:n=[400,800,1200,1920],fit:o="scale-down",quality:r=80,gravity:i}=t,a=this.parseImageUrl(e);return a?n.map(p=>{let g=[`w=${p}`,`fit=${o}`,"format=auto",`quality=${r}`,i&&`gravity=${i}`].filter(Boolean).join(",");return `${a.cdnBase}/cdn-cgi/image/${g}/${a.relativePath} ${p}w`}).join(", "):""}transform(e,t={}){if(!e)return "";let n=this.parseImageUrl(e);if(!n)return e||"";let o=[t.w&&`w=${t.w}`,t.h&&`h=${t.h}`,`fit=${t.fit||"scale-down"}`,`format=${t.format||"auto"}`,`quality=${t.quality||80}`,t.gravity&&`gravity=${t.gravity}`,t.dpr&&`dpr=${t.dpr}`].filter(Boolean).join(",");return `${n.cdnBase}/cdn-cgi/image/${o}/${n.relativePath}`}parseImageUrl(e){let t=e.indexOf("/cdn-cgi/image/");if(t!==-1){let r=e.substring(0,t),i=e.substring(t+15),a=i.indexOf("/");if(a===-1)return null;let p=i.substring(a+1);return {cdnBase:r,relativePath:p}}let n=e.indexOf("/sites/");if(n!==-1){let r=e.substring(0,n),i=e.substring(n+1);return {cdnBase:r,relativePath:i}}let o=e.indexOf("/avatars/");if(o!==-1){let r=e.substring(0,o),i=e.substring(o+1);return {cdnBase:r,relativePath:i}}return null}};var _=class extends m{async search(e,t){return this.get("/search",{q:e,locale:t?.locale,category:t?.category,tag:t?.tag,page:t?.page,limit:t?.limit},t)}async getConfig(e){return (await this.getWithCache("search-config","/search/config",void 0,e,d.MEDIUM)).data}async listProfiles(e){return (await this.getWithCache("search-profiles","/search/profiles",void 0,e,d.MEDIUM)).data}async searchByProfile(e,t,n){return this.get(`/search/${encodeURIComponent(e)}`,{q:t,locale:n?.locale,category:n?.category,tag:n?.tag,page:n?.page,limit:n?.limit},n)}};var _e=300*1e3,Fe="lynkow_cache_",C=new Map;function ge(s={}){let e=s.defaultTtl??_e,t=s.prefix??Fe;function n(u){return `${t}${u}`}function o(u){return Date.now()>u.expiresAt}function r(u){let l=n(u);if(c)try{let f=localStorage.getItem(l);if(!f)return null;let y=JSON.parse(f);return o(y)?(localStorage.removeItem(l),null):y.value}catch{return null}let h=C.get(l);return h?o(h)?(C.delete(l),null):h.value:null}function i(u,l,h=e){let f=n(u),y={value:l,expiresAt:Date.now()+h};if(c){try{localStorage.setItem(f,JSON.stringify(y));}catch{}return}C.set(f,y);}function a(u){let l=n(u);if(c){try{localStorage.removeItem(l);}catch{}return}C.delete(l);}function p(u){if(c){try{let l=[];for(let h=0;h<localStorage.length;h++){let f=localStorage.key(h);f&&f.startsWith(t)&&(!u||f.includes(u))&&l.push(f);}l.forEach(h=>localStorage.removeItem(h));}catch{}return}if(u)for(let l of C.keys())l.startsWith(t)&&l.includes(u)&&C.delete(l);else for(let l of C.keys())l.startsWith(t)&&C.delete(l);}async function g(u,l,h=e){let f=r(u);if(f!==null)return f;let y=await l();return i(u,y,h),y}return {get:r,set:i,remove:a,invalidate:p,getOrSet:g}}function he(s){let e=s.prefix||"[Lynkow]";return {debug(...t){s.debug&&console.debug(e,...t);},info(...t){console.info(e,...t);},warn(...t){console.warn(e,...t);},error(...t){console.error(e,...t);},log(t,...n){switch(t){case "debug":this.debug(...n);break;case "info":this.info(...n);break;case "warn":this.warn(...n);break;case "error":this.error(...n);break}}}}function fe(){let s=new Map;function e(i,a){return s.has(i)||s.set(i,new Set),s.get(i).add(a),()=>t(i,a)}function t(i,a){let p=s.get(i);p&&p.delete(a);}function n(i,a){let p=s.get(i);if(p)for(let g of p)try{g(a);}catch(u){console.error(`[Lynkow] Error in event listener for "${i}":`,u);}}function o(i,a){let p=(g=>{t(i,p),a(g);});return e(i,p)}function r(i){i?s.delete(i):s.clear();}return {on:e,off:t,emit:n,once:o,removeAllListeners:r}}var ye="lynkow_locale";function ie(s,e){let t=s.toLowerCase();return e.find(n=>n.toLowerCase()===t)??null}function ve(s,e){if(!c)return e;let t=De();if(t&&s.includes(t))return t;let n=qe(s);if(n)return n;let o=document.documentElement.lang;if(o){let r=ie(o,s);if(r)return r;let i=o.split("-")[0]?.toLowerCase();if(i){let a=ie(i,s);if(a)return a}}return e}function De(){if(!c)return null;try{return localStorage.getItem(ye)}catch{return null}}function Ce(s){if(c)try{localStorage.setItem(ye,s);}catch{}}function qe(s){if(!c)return null;let t=window.location.pathname.split("/").filter(Boolean);if(t.length>0){let n=t[0];if(n){let o=ie(n,s);if(o)return o}}return null}function we(s,e){return e.includes(s)}var be="https://api.lynkow.com";function He(s){if(!s.siteId)throw new Error("Lynkow SDK: siteId is required");let e=s.cache===true?ge():void 0,t=he({debug:s.debug??false}),n=fe(),o=(s.baseUrl||be).replace(/\/+$/,""),r={siteId:s.siteId,baseUrl:o,publishableKey:s.publishableKey,locale:s.locale,fetchOptions:s.fetchOptions||{},...e?{cache:e}:{}},i={locale:s.locale||"fr",availableLocales:["fr"],siteConfig:null,initialized:false},a={contents:new k(r),categories:new R(r),tags:new x(r),pages:new E(r),blocks:new S(r),forms:new T(r),reviews:new L(r),site:new O(r),legal:new I(r),cookies:new P(r),seo:new B(r),paths:new $(r),analytics:new H(r),consent:new N(r,n),branding:new M(r),enhancements:new K,media:new U,search:new _(r)};function p(l){r.locale=l;}async function g(){if(!i.initialized)try{let l=await a.site.getConfig();i.siteConfig=l;let h=l.defaultLocale||"fr";if(i.availableLocales=l.enabledLocales||[h],c&&!s.locale){let f=ve(i.availableLocales,h);i.locale=f,p(f);}i.initialized=!0,t.debug("Client initialized",{locale:i.locale,availableLocales:i.availableLocales}),c&&(a.analytics.init(),a.consent.hasConsented()||a.consent.show(),l.showBranding&&await a.branding.inject(),a.enhancements.init()),n.emit("ready",void 0);}catch(l){t.error("Failed to initialize client",l),n.emit("error",l);}}return c&&setTimeout(()=>{a.enhancements.init(),g();},0),{...a,globals:a.blocks,config:Object.freeze({siteId:s.siteId,baseUrl:o,debug:s.debug??false,cache:s.cache===true}),get locale(){return i.locale},get availableLocales(){return [...i.availableLocales]},setLocale(l){if(!we(l,i.availableLocales)){t.warn(`Locale "${l}" is not available. Available: ${i.availableLocales.join(", ")}`);return}l!==i.locale&&(i.locale=l,p(l),c&&Ce(l),e?.invalidate(),n.emit("locale-changed",l),t.debug("Locale changed to",l));},clearCache(){e?.invalidate(),t.debug("Cache cleared");},destroy(){a.analytics.destroy(),a.consent.destroy(),a.branding.destroy(),a.enhancements.destroy(),e?.invalidate(),n.removeAllListeners(),t.debug("Client destroyed");},on(l,h){return n.on(l,h)}}}function Ne(s){if(!s.siteId)throw new Error("Lynkow SDK: siteId is required");let e={siteId:s.siteId,baseUrl:(s.baseUrl||be).replace(/\/+$/,""),publishableKey:s.publishableKey,locale:s.locale,fetchOptions:s.fetchOptions||{}};return {contents:new k(e),categories:new R(e),tags:new x(e),pages:new E(e),blocks:new S(e),forms:new T(e),reviews:new L(e),site:new O(e),legal:new I(e),cookies:new P(e),seo:new B(e),paths:new $(e),search:new _(e)}}function Me(s){return s.type==="content"}function Ke(s){return s.type==="category"}function Ue(s){if(!s||s.length===0)return "";let e=s.map(o=>{let{["@context"]:r,...i}=o;return i});return `<script type="application/ld+json">${JSON.stringify({"@context":"https://schema.org","@graph":e}).replace(/<\/(script)/gi,"<\\/$1")}</script>`}function je(s,e){let t=s??[],n=e??[];if(n.length===0)return [...t];let o=new Set;for(let r of t){let i=r?.["@id"];typeof i=="string"&&o.add(i);}for(let r of n){let i=r?.["@id"];typeof i=="string"&&o.has(i)&&console.warn(`[lynkow] @id collision in mergeIntoGraph: "${i}" appears in both the server graph and your custom nodes. Google may merge them, which can duplicate properties on the rendered entity. Prefix custom @ids with the page URL to make them unique.`);}return [...t,...n]}
|
|
293
|
-
exports.AnalyticsService=
|
|
292
|
+
`,K=class{initialized=false;observer=null;pendingFrame=null;handleWidgetResize=e=>{if(!e.data||e.data.type!=="lynkow-widget-resize")return;document.querySelectorAll('iframe[src*="/widgets/calendar/"]').forEach(n=>{n.contentWindow===e.source&&(n.style.height=e.data.height+"px");});};injectGenericStyles(){if(!c||document.getElementById(se))return;let e=document.createElement("style");e.id=se,e.textContent=Ke,document.head.appendChild(e);}injectCodeBlockStyles(){if(!c||document.getElementById(ie))return;let e=document.createElement("style");e.id=ie,e.textContent=je,document.head.appendChild(e);}async handleCopyClick(e){let t=e.closest(".code-block");if(!t)return;let n=t.querySelector("code");if(!n)return;let r=n.textContent||"";try{await navigator.clipboard.writeText(r),e.classList.add("copied"),e.innerHTML=Ue,setTimeout(()=>{e.classList.remove("copied"),e.innerHTML=He;},2e3);}catch(s){console.error("Lynkow SDK: Failed to copy code",s);}}bindCodeBlockCopy(){if(!c)return;document.querySelectorAll("[data-copy-code]").forEach(t=>{t.dataset.lynkowBound||(t.dataset.lynkowBound="true",t.addEventListener("click",n=>{n.preventDefault(),this.handleCopyClick(t);}));});}activateScripts(e){if(!c)return;let n=(e instanceof HTMLElement?e:document.body).querySelectorAll("script:not([data-lynkow-activated])"),r=Array.from(n).filter(s=>!s.src&&s.isConnected&&qe.has(s.type.toLowerCase()));r.length!==0&&(document.head.querySelectorAll(`script[${ae}]`).forEach(s=>s.remove()),r.forEach(s=>{s.setAttribute("data-lynkow-activated","true");let i=document.createElement("script"),a=s.attributes;for(let p=0;p<a.length;p++){let g=a[p];g&&(g.name==="type"&&g.value==="text/plain"||g.name!=="data-lynkow-activated"&&i.setAttribute(g.name,g.value));}i.textContent=s.textContent,i.setAttribute(ae,""),document.head.appendChild(i);}));}init(e={}){if(!c||this.initialized)return;let{codeBlocks:t=true}=e;this.injectGenericStyles(),this.activateScripts(),window.addEventListener("message",this.handleWidgetResize),t&&(this.injectCodeBlockStyles(),this.bindCodeBlockCopy()),this.observer||(this.observer=new MutationObserver(()=>{this.pendingFrame===null&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=null,this.activateScripts(),t&&this.bindCodeBlockCopy();}));}),this.observer.observe(document.body,{childList:true,subtree:true})),this.initialized=true;}isInitialized(){return this.initialized}destroy(){c&&(window.removeEventListener("message",this.handleWidgetResize),this.pendingFrame!==null&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=null),this.observer&&(this.observer.disconnect(),this.observer=null),document.getElementById(se)?.remove(),document.getElementById(ie)?.remove(),document.head.querySelectorAll(`script[${ae}]`).forEach(e=>e.remove()),this.initialized=false);}};var j=class{srcset(e,t={}){if(!e)return "";let{widths:n=[400,800,1200,1920],fit:r="scale-down",quality:s=80,gravity:i}=t,a=this.parseImageUrl(e);return a?n.map(p=>{let g=[`w=${p}`,`fit=${r}`,"format=auto",`quality=${s}`,i&&`gravity=${i}`].filter(Boolean).join(",");return `${a.cdnBase}/cdn-cgi/image/${g}/${a.relativePath} ${p}w`}).join(", "):""}transform(e,t={}){if(!e)return "";let n=this.parseImageUrl(e);if(!n)return e||"";let r=[t.w&&`w=${t.w}`,t.h&&`h=${t.h}`,`fit=${t.fit||"scale-down"}`,`format=${t.format||"auto"}`,`quality=${t.quality||80}`,t.gravity&&`gravity=${t.gravity}`,t.dpr&&`dpr=${t.dpr}`].filter(Boolean).join(",");return `${n.cdnBase}/cdn-cgi/image/${r}/${n.relativePath}`}parseImageUrl(e){let t=e.indexOf("/cdn-cgi/image/");if(t!==-1){let s=e.substring(0,t),i=e.substring(t+15),a=i.indexOf("/");if(a===-1)return null;let p=i.substring(a+1);return {cdnBase:s,relativePath:p}}let n=e.indexOf("/sites/");if(n!==-1){let s=e.substring(0,n),i=e.substring(n+1);return {cdnBase:s,relativePath:i}}let r=e.indexOf("/avatars/");if(r!==-1){let s=e.substring(0,r),i=e.substring(r+1);return {cdnBase:s,relativePath:i}}return null}};var _=class extends u{async search(e,t){return this.get("/search",{q:e,locale:t?.locale,category:t?.category,tag:t?.tag,page:t?.page,limit:t?.limit},t)}async getConfig(e){return (await this.getWithCache("search-config","/search/config",void 0,e,d.MEDIUM)).data}async listProfiles(e){return (await this.getWithCache("search-profiles","/search/profiles",void 0,e,d.MEDIUM)).data}async searchByProfile(e,t,n){return this.get(`/search/${encodeURIComponent(e)}`,{q:t,locale:n?.locale,category:n?.category,tag:n?.tag,page:n?.page,limit:n?.limit},n)}};var ze=300*1e3,We="lynkow_cache_",w=new Map;function Ce(o={}){let e=o.defaultTtl??ze,t=o.prefix??We;function n(m){return `${t}${m}`}function r(m){return Date.now()>m.expiresAt}function s(m){let l=n(m);if(c)try{let f=localStorage.getItem(l);if(!f)return null;let y=JSON.parse(f);return r(y)?(localStorage.removeItem(l),null):y.value}catch{return null}let h=w.get(l);return h?r(h)?(w.delete(l),null):h.value:null}function i(m,l,h=e){let f=n(m),y={value:l,expiresAt:Date.now()+h};if(c){try{localStorage.setItem(f,JSON.stringify(y));}catch{}return}w.set(f,y);}function a(m){let l=n(m);if(c){try{localStorage.removeItem(l);}catch{}return}w.delete(l);}function p(m){if(c){try{let l=[];for(let h=0;h<localStorage.length;h++){let f=localStorage.key(h);f&&f.startsWith(t)&&(!m||f.includes(m))&&l.push(f);}l.forEach(h=>localStorage.removeItem(h));}catch{}return}if(m)for(let l of w.keys())l.startsWith(t)&&l.includes(m)&&w.delete(l);else for(let l of w.keys())l.startsWith(t)&&w.delete(l);}async function g(m,l,h=e){let f=s(m);if(f!==null)return f;let y=await l();return i(m,y,h),y}return {get:s,set:i,remove:a,invalidate:p,getOrSet:g}}function be(o){let e=o.prefix||"[Lynkow]";return {debug(...t){o.debug&&console.debug(e,...t);},info(...t){console.info(e,...t);},warn(...t){console.warn(e,...t);},error(...t){console.error(e,...t);},log(t,...n){switch(t){case "debug":this.debug(...n);break;case "info":this.info(...n);break;case "warn":this.warn(...n);break;case "error":this.error(...n);break}}}}function ke(){let o=new Map;function e(i,a){return o.has(i)||o.set(i,new Set),o.get(i).add(a),()=>t(i,a)}function t(i,a){let p=o.get(i);p&&p.delete(a);}function n(i,a){let p=o.get(i);if(p)for(let g of p)try{g(a);}catch(m){console.error(`[Lynkow] Error in event listener for "${i}":`,m);}}function r(i,a){let p=(g=>{t(i,p),a(g);});return e(i,p)}function s(i){i?o.delete(i):o.clear();}return {on:e,off:t,emit:n,once:r,removeAllListeners:s}}var Re="lynkow_locale";function ce(o,e){let t=o.toLowerCase();return e.find(n=>n.toLowerCase()===t)??null}function xe(o,e){if(!c)return e;let t=Ge();if(t&&o.includes(t))return t;let n=Je(o);if(n)return n;let r=document.documentElement.lang;if(r){let s=ce(r,o);if(s)return s;let i=r.split("-")[0]?.toLowerCase();if(i){let a=ce(i,o);if(a)return a}}return e}function Ge(){if(!c)return null;try{return localStorage.getItem(Re)}catch{return null}}function Ee(o){if(c)try{localStorage.setItem(Re,o);}catch{}}function Je(o){if(!c)return null;let t=window.location.pathname.split("/").filter(Boolean);if(t.length>0){let n=t[0];if(n){let r=ce(n,o);if(r)return r}}return null}function Se(o,e){return e.includes(o)}var Te="https://api.lynkow.com";function Ve(o){if(!o.siteId)throw new Error("Lynkow SDK: siteId is required");let e=o.cache===true?Ce():void 0,t=be({debug:o.debug??false}),n=ke(),r=(o.baseUrl||Te).replace(/\/+$/,""),s={siteId:o.siteId,baseUrl:r,publishableKey:o.publishableKey,locale:o.locale,fetchOptions:o.fetchOptions||{},retry:o.retry,...e?{cache:e}:{}},i={locale:o.locale||"fr",availableLocales:["fr"],siteConfig:null,initialized:false},a={contents:new k(s),categories:new R(s),tags:new x(s),pages:new E(s),blocks:new S(s),forms:new T(s),reviews:new L(s),site:new O(s),legal:new I(s),cookies:new P(s),seo:new B(s),paths:new $(s),analytics:new q(s),consent:new H(s,n),branding:new U(s),enhancements:new K,media:new j,search:new _(s)};function p(l){s.locale=l;}async function g(){if(!i.initialized)try{let l=await a.site.getConfig();i.siteConfig=l;let h=l.defaultLocale||"fr";if(i.availableLocales=l.enabledLocales||[h],c&&!o.locale){let f=xe(i.availableLocales,h);i.locale=f,p(f);}i.initialized=!0,t.debug("Client initialized",{locale:i.locale,availableLocales:i.availableLocales}),c&&(a.analytics.init(),a.consent.hasConsented()||a.consent.show(),l.showBranding&&await a.branding.inject(),a.enhancements.init()),n.emit("ready",void 0);}catch(l){t.error("Failed to initialize client",l),n.emit("error",l);}}return c&&setTimeout(()=>{a.enhancements.init(),g();},0),{...a,globals:a.blocks,config:Object.freeze({siteId:o.siteId,baseUrl:r,debug:o.debug??false,cache:o.cache===true}),get locale(){return i.locale},get availableLocales(){return [...i.availableLocales]},setLocale(l){if(!Se(l,i.availableLocales)){t.warn(`Locale "${l}" is not available. Available: ${i.availableLocales.join(", ")}`);return}l!==i.locale&&(i.locale=l,p(l),c&&Ee(l),e?.invalidate(),n.emit("locale-changed",l),t.debug("Locale changed to",l));},clearCache(){e?.invalidate(),t.debug("Cache cleared");},destroy(){a.analytics.destroy(),a.consent.destroy(),a.branding.destroy(),a.enhancements.destroy(),e?.invalidate(),n.removeAllListeners(),t.debug("Client destroyed");},on(l,h){return n.on(l,h)}}}function Xe(o){if(!o.siteId)throw new Error("Lynkow SDK: siteId is required");let e={siteId:o.siteId,baseUrl:(o.baseUrl||Te).replace(/\/+$/,""),publishableKey:o.publishableKey,locale:o.locale,fetchOptions:o.fetchOptions||{},retry:o.retry};return {contents:new k(e),categories:new R(e),tags:new x(e),pages:new E(e),blocks:new S(e),forms:new T(e),reviews:new L(e),site:new O(e),legal:new I(e),cookies:new P(e),seo:new B(e),paths:new $(e),search:new _(e)}}function Ye(o){return o.type==="content"}function Qe(o){return o.type==="category"}function Ze(o){if(!o||o.length===0)return "";let e=o.map(r=>{let{["@context"]:s,...i}=r;return i});return `<script type="application/ld+json">${JSON.stringify({"@context":"https://schema.org","@graph":e}).replace(/<\/(script)/gi,"<\\/$1")}</script>`}function et(o,e){let t=o??[],n=e??[];if(n.length===0)return [...t];let r=new Set;for(let s of t){let i=s?.["@id"];typeof i=="string"&&r.add(i);}for(let s of n){let i=s?.["@id"];typeof i=="string"&&r.has(i)&&console.warn(`[lynkow] @id collision in mergeIntoGraph: "${i}" appears in both the server graph and your custom nodes. Google may merge them, which can duplicate properties on the rendered entity. Prefix custom @ids with the page URL to make them unique.`);}return [...t,...n]}
|
|
293
|
+
exports.AnalyticsService=q;exports.BlocksService=S;exports.BrandingService=U;exports.CategoriesService=R;exports.ConsentService=H;exports.ContentsService=k;exports.CookiesService=P;exports.EnhancementsService=K;exports.FormsService=T;exports.LegalService=I;exports.LynkowError=v;exports.MediaHelperService=j;exports.PagesService=E;exports.PathsService=$;exports.ReviewsService=L;exports.SearchService=_;exports.SeoService=B;exports.SiteService=O;exports.TagsService=x;exports.browserOnly=Fe;exports.browserOnlyAsync=De;exports.createClient=Ve;exports.createLynkowClient=Xe;exports.detectSiteTheme=C;exports.isBrowser=c;exports.isCategoryResolve=Qe;exports.isContentResolve=Ye;exports.isLynkowError=Oe;exports.isServer=_e;exports.mergeIntoGraph=et;exports.onSiteThemeChange=A;exports.renderJsonLdGraph=Ze;//# sourceMappingURL=index.js.map
|
|
294
294
|
//# sourceMappingURL=index.js.map
|