@daouy/loader-react 1.0.409

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,503 @@
1
+ import { AssetModule } from '@daouy/loader-core';
2
+ import type { CodeComponentMeta as CodeComponentMeta_2 } from '@daouy/host';
3
+ import { CodeModule } from '@daouy/loader-fetcher';
4
+ import type { ComponentHelpers } from '@daouy/host';
5
+ import { ComponentMeta } from '@daouy/loader-core';
6
+ import { ComponentMeta as ComponentMeta_2 } from '@daouy/loader-fetcher';
7
+ import type { CustomFunctionMeta as CustomFunctionMeta_2 } from '@daouy/host';
8
+ import { daouyDataSourcesContext } from '@daouy/data-sources-context';
9
+ import { daouyHost } from '@daouy/host';
10
+ import { DaouyModulesFetcher } from '@daouy/loader-core';
11
+ import { daouyQuery } from '@daouy/query';
12
+ import { FontMeta } from '@daouy/loader-core';
13
+ import { getActiveVariation } from '@daouy/loader-splits';
14
+ import { getExternalIds } from '@daouy/loader-splits';
15
+ import type { GlobalContextMeta as GlobalContextMeta_2 } from '@daouy/host';
16
+ import { GlobalGroupMeta } from '@daouy/loader-core';
17
+ import { LoaderBundleCache } from '@daouy/loader-core';
18
+ import { LoaderBundleOutput } from '@daouy/loader-fetcher';
19
+ import { LoaderBundleOutput as LoaderBundleOutput_2 } from '@daouy/loader-core';
20
+ import { PageMeta } from '@daouy/loader-core';
21
+ import { PageMetadata } from '@daouy/loader-core';
22
+ import { react } from 'react';
23
+ import * as React_2 from 'react';
24
+ import { default as React_3 } from 'react';
25
+ import { reactDom } from 'react-dom';
26
+ import { reactJsxDevRuntime } from 'react/jsx-dev-runtime';
27
+ import { reactJsxRuntime } from 'react/jsx-runtime';
28
+ import { Registry } from '@daouy/loader-core';
29
+ import { Split } from '@daouy/loader-fetcher';
30
+ import type { StateHelpers } from '@daouy/host';
31
+ import type { StateSpec } from '@daouy/host';
32
+ import type { TokenRegistration } from '@daouy/host';
33
+ import { TrackRenderOptions } from '@daouy/loader-core';
34
+ import type { TraitMeta } from '@daouy/host';
35
+ import type { useDataEnv } from '@daouy/host';
36
+ import type { useMutableDaouyQueryData } from '@daouy/query';
37
+ import type { useSelector } from '@daouy/host';
38
+ import type { useSelectors } from '@daouy/host';
39
+
40
+ /**
41
+ * Performs a prepass over Daouy content, kicking off the necessary
42
+ * data fetches, and populating the fetched data into a cache. This
43
+ * cache can be passed as prefetchedQueryData into DaouyRootProvider.
44
+ *
45
+ * To limit rendering errors that can occur when you do this, we recommend
46
+ * that you pass in _only_ the DaouyComponents that you are planning to use
47
+ * as the argument. For example:
48
+ *
49
+ * const cache = await extractDaouyQueryData(
50
+ * <ClientDaouyRootProvider prefetchedData={daouyData}>
51
+ * <DaouyComponent component="Home" componentProps={{
52
+ * // Specify the component prop overrides you are planning to use
53
+ * // to render the page, as they may change what data is fetched.
54
+ * ...
55
+ * }} />
56
+ * <DaouyComponent component="NavBar" componentProps={{
57
+ * ...
58
+ * }} />
59
+ * ...
60
+ * </ClientDaouyRootProvider>,
61
+ * DAOUY
62
+ * );
63
+ *
64
+ * If your DaouyComponent will be wrapping components that require special
65
+ * context set up, you should also wrap the element above with those context
66
+ * providers. Avoid, however, wrapping the root provider, because we inspect
67
+ * the props passed to the root element.
68
+ *
69
+ * You should avoid passing in elements that are not related to Daouy, as any
70
+ * rendering errors from those elements during the prepass may result in data
71
+ * not being populated in the cache.
72
+ *
73
+ * @param element a React element containing instances of DaouyComponent.
74
+ * Will attempt to satisfy all data needs from useDaouyDataQuery()
75
+ * in this element tree.
76
+ * @returns an object mapping query key to fetched data
77
+ */
78
+ export declare function __EXPERMIENTAL__extractDaouyQueryData(element: React.ReactElement, loader: DaouyComponentLoader): Promise<Record<string, any>>;
79
+
80
+ /** Subset of loader functionality that works on Client and React Server Components. */
81
+ declare abstract class BaseInternalDaouyComponentLoader {
82
+ readonly opts: InitOptions;
83
+ private readonly registry;
84
+ private readonly fetcher;
85
+ private readonly onBundleMerged?;
86
+ private readonly onBundleFetched?;
87
+ private globalVariants;
88
+ private subs;
89
+ private bundle;
90
+ constructor(args: {
91
+ opts: InitOptions;
92
+ fetcher: DaouyModulesFetcher;
93
+ /** Called after `mergeBundle` (including `fetch` calls). */
94
+ onBundleMerged?: () => void;
95
+ /** Called after any `fetch` calls. */
96
+ onBundleFetched?: () => void;
97
+ builtinModules: BuiltinRegisteredModules;
98
+ });
99
+ private maybeGetCompMetas;
100
+ maybeFetchComponentData(specs: ComponentLookupSpec[], opts?: FetchComponentDataOpts): Promise<ComponentRenderData | null>;
101
+ maybeFetchComponentData(...specs: ComponentLookupSpec[]): Promise<ComponentRenderData | null>;
102
+ fetchComponentData(specs: ComponentLookupSpec[], opts?: FetchComponentDataOpts): Promise<ComponentRenderData>;
103
+ fetchComponentData(...specs: ComponentLookupSpec[]): Promise<ComponentRenderData>;
104
+ fetchPages(opts?: FetchPagesOpts): Promise<PageMeta[]>;
105
+ fetchComponents(): Promise<ComponentMeta_2[]>;
106
+ getActiveSplits(): Split[];
107
+ getChunksUrl(bundle: LoaderBundleOutput, modules: CodeModule[]): string;
108
+ private fetchMissingData;
109
+ private maybeReportClientSideFetch;
110
+ private fetchAllData;
111
+ mergeBundle(newBundle: LoaderBundleOutput): void;
112
+ getBundle(): LoaderBundleOutput;
113
+ clearCache(): void;
114
+ registerModules(modules: Record<string, any>): void;
115
+ substituteComponent<P>(component: React.ComponentType<P>, name: ComponentLookupSpec): void;
116
+ protected internalSubstituteComponent<P>(component: React.ComponentType<P>, name: ComponentLookupSpec, codeComponentHelpers: ComponentHelpers<React.ComponentProps<React.ComponentType<P>>> | undefined): void;
117
+ abstract registerComponent<T extends React.ComponentType<any>>(component: T, meta: CodeComponentMeta<React.ComponentProps<T>>): void;
118
+ abstract registerFunction<F extends (...args: any[]) => any>(fn: F, meta: CustomFunctionMeta<F>): void;
119
+ abstract registerGlobalContext<T extends React.ComponentType<any>>(context: T, meta: GlobalContextMeta<React.ComponentProps<T>>): void;
120
+ abstract registerTrait(trait: string, meta: TraitMeta): void;
121
+ abstract registerToken(token: TokenRegistration): void;
122
+ protected refreshRegistry(): void;
123
+ isRegistryEmpty(): boolean;
124
+ clearRegistry(): void;
125
+ setGlobalVariants(globalVariants: GlobalVariantSpec[]): void;
126
+ getGlobalVariants(): GlobalVariantSpec[];
127
+ registerPrefetchedBundle(bundle: LoaderBundleOutput): void;
128
+ getLookup(): ComponentLookup;
129
+ trackConversion(_value?: number): void;
130
+ getActiveVariation(opts: Omit<Parameters<typeof getActiveVariation>[0], "splits">): Promise<Record<string, string>>;
131
+ getTeamIds(): string[];
132
+ getProjectIds(): string[];
133
+ trackRender(_opts?: TrackRenderOptions): void;
134
+ loadServerQueriesModule(fileName: string): any;
135
+ }
136
+
137
+ declare interface BuiltinRegisteredModules {
138
+ react: react;
139
+ "react-dom": reactDom;
140
+ "react/jsx-runtime": reactJsxRuntime;
141
+ "react/jsx-dev-runtime": reactJsxDevRuntime;
142
+ "@daouy/query": daouyQuery;
143
+ "@daouy/data-sources-context": daouyDataSourcesContext;
144
+ "@daouy/host": daouyHost;
145
+ "@daouy/loader-runtime-registry": {
146
+ components: Record<string, React.ComponentType<any>>;
147
+ globalVariantHooks: Record<string, () => any>;
148
+ codeComponentHelpers: Record<string, ComponentHelpers<any>>;
149
+ functions: Record<string, (...args: any[]) => any>;
150
+ };
151
+ }
152
+
153
+ declare type CodeComponentMeta<P> = Omit<CodeComponentMeta_2<P>, "importPath" | "componentHelpers" | "states"> & {
154
+ /**
155
+ * The path to be used when importing the component in the generated code.
156
+ * It can be the name of the package that contains the component, or the path
157
+ * to the file in the project (relative to the root directory).
158
+ * Optional: not used by Daouy headless API, only by codegen.
159
+ */
160
+ importPath?: string;
161
+ /**
162
+ * The states helpers are registered together with the states for the Daouy headless API
163
+ */
164
+ states?: Record<string, StateSpec<P> & StateHelpers<P, any>>;
165
+ /**
166
+ * Helper function to enable data extraction when running Daouy from
167
+ * Next.js App Router.
168
+ */
169
+ getServerInfo?: (props: P, ops: ReactServerOps) => ServerInfo;
170
+ };
171
+
172
+ declare class ComponentLookup {
173
+ private bundle;
174
+ private registry;
175
+ constructor(bundle: LoaderBundleOutput_2, registry: Registry);
176
+ getComponentMeta(spec: ComponentLookupSpec): ComponentMeta | undefined;
177
+ getComponent<P extends React_2.ComponentType = any>(spec: ComponentLookupSpec, opts?: {
178
+ forceOriginal?: boolean;
179
+ }): any;
180
+ hasComponent(spec: ComponentLookupSpec): boolean;
181
+ getGlobalContexts(): {
182
+ meta: GlobalGroupMeta;
183
+ context: any;
184
+ }[];
185
+ /** Returns StyleTokensProvider if the project has style token overrides. */
186
+ maybeGetStyleTokensProvider(spec: ComponentLookupSpec, styleTokenOverridesProjectId?: string): any;
187
+ getGlobalContextsProvider(spec: ComponentLookupSpec): any;
188
+ getRootProvider(): any;
189
+ getCss(): AssetModule[];
190
+ getRemoteFonts(): FontMeta[];
191
+ }
192
+
193
+ declare type ComponentLookupSpec = string | {
194
+ name: string;
195
+ projectId?: string;
196
+ isCode?: boolean;
197
+ };
198
+
199
+ export { ComponentMeta }
200
+
201
+ export declare interface ComponentRenderData {
202
+ entryCompMetas: (ComponentMeta_2 & {
203
+ params?: Record<string, string>;
204
+ })[];
205
+ bundle: LoaderBundleOutput;
206
+ remoteFontUrls: string[];
207
+ }
208
+
209
+ export declare const convertBundlesToComponentRenderData: (bundles: LoaderBundleOutput_2[], compMetas: ComponentMeta[]) => ComponentRenderData | null;
210
+
211
+ declare type CustomFunctionMeta<F extends (...args: any[]) => any> = Omit<CustomFunctionMeta_2<F>, "importPath"> & {
212
+ /**
213
+ * The path to be used when importing the function in the generated code.
214
+ * It can be the name of the package that contains the function, or the path
215
+ * to the file in the project (relative to the root directory).
216
+ * Optional: not used by Daouy headless API, only by codegen.
217
+ */
218
+ importPath?: string;
219
+ };
220
+
221
+ /**
222
+ * Library for fetching component data, and registering
223
+ * custom components.
224
+ */
225
+ export declare class DaouyComponentLoader {
226
+ private __internal;
227
+ constructor(internal: BaseInternalDaouyComponentLoader);
228
+ /**
229
+ * Sets global variants to be used for all components. Note that
230
+ * this is not reactive, and will not re-render all components
231
+ * already mounted; instead, it should be used to activate global
232
+ * variants that should always be activated for the lifetime of this
233
+ * app. If you'd like to reactively change the global variants,
234
+ * you should specify them via <DaouyRootProvider />
235
+ */
236
+ setGlobalVariants(globalVariants: GlobalVariantSpec[]): void;
237
+ registerModules(modules: Record<string, any>): void;
238
+ /**
239
+ * Register custom components that should be swapped in for
240
+ * components defined in your project. You can use this to
241
+ * swap in / substitute a Daouy component with a "real" component.
242
+ */
243
+ substituteComponent<P>(component: React.ComponentType<P>, name: ComponentLookupSpec): void;
244
+ /**
245
+ * Register code components to be used on Daouy Editor.
246
+ */
247
+ registerComponent<T extends React.ComponentType<any>>(component: T, meta: CodeComponentMeta<React.ComponentProps<T>>): void;
248
+ /**
249
+ * [[deprecated]] Please use `substituteComponent` instead for component
250
+ * substitution, or the other `registerComponent` overload to register
251
+ * code components to be used on Daouy Editor.
252
+ *
253
+ * @see `substituteComponent`
254
+ */
255
+ registerComponent<T extends React.ComponentType<any>>(component: T, name: ComponentLookupSpec): void;
256
+ private warnedRegisterComponent;
257
+ registerFunction<F extends (...args: any[]) => any>(fn: F, meta: CustomFunctionMeta<F>): void;
258
+ registerGlobalContext<T extends React.ComponentType<any>>(context: T, meta: GlobalContextMeta<React.ComponentProps<T>>): void;
259
+ registerTrait(trait: string, meta: TraitMeta): void;
260
+ registerToken(token: TokenRegistration): void;
261
+ /**
262
+ * Pre-fetches component data needed to for DaouyLoader to render
263
+ * these components. Should be passed into DaouyRootProvider as
264
+ * the prefetchedData prop.
265
+ *
266
+ * You can look up a component either by:
267
+ * - the name of the component
268
+ * - the path for a page component
269
+ * - an array of strings that make up parts of the path
270
+ * - object { name: "name_or_path", projectId: ...}, to specify which project
271
+ * to use, if multiple projects have the same component name
272
+ *
273
+ * Throws an Error if a specified component to fetch does not exist in
274
+ * the Daouy project.
275
+ */
276
+ fetchComponentData(...specs: ComponentLookupSpec[]): Promise<ComponentRenderData>;
277
+ fetchComponentData(specs: ComponentLookupSpec[], opts?: FetchComponentDataOpts): Promise<ComponentRenderData>;
278
+ /**
279
+ * Like fetchComponentData(), but returns null instead of throwing an Error
280
+ * when a component is not found. Useful when you are implementing a catch-all
281
+ * page and want to check if a specific path had been defined for Daouy.
282
+ */
283
+ maybeFetchComponentData(...specs: ComponentLookupSpec[]): Promise<ComponentRenderData | null>;
284
+ maybeFetchComponentData(specs: ComponentLookupSpec[], opts?: FetchComponentDataOpts): Promise<ComponentRenderData | null>;
285
+ /**
286
+ * Returns all the page component metadata for these projects.
287
+ */
288
+ fetchPages(opts?: FetchPagesOpts): Promise<PageMeta[]>;
289
+ /**
290
+ * Returns all components metadata for these projects.
291
+ */
292
+ fetchComponents(): Promise<ComponentMeta_2[]>;
293
+ protected _getActiveVariation(opts: Parameters<typeof DaouyComponentLoader.__internal.getActiveVariation>[0]): Promise<Record<string, string>>;
294
+ getActiveVariation(opts: {
295
+ known?: Record<string, string>;
296
+ traits: Record<string, string | number | boolean>;
297
+ }): Promise<Record<string, string>>;
298
+ getChunksUrl(bundle: LoaderBundleOutput, modules: CodeModule[]): string;
299
+ getExternalVariation(variation: Record<string, string>, filters?: Parameters<typeof getExternalIds>[2]): Record<string, string>;
300
+ getActiveSplits(): Split[];
301
+ trackConversion(value?: number): void;
302
+ clearCache(): void;
303
+ getExecFuncModule(renderData: ComponentRenderData, fileNameKey: "serverQueriesExecFuncFileName" | "generateMetadataFuncFileName"): any;
304
+ unstable__getServerQueriesData(renderData: ComponentRenderData, $ctx: Record<string, any>): Promise<any>;
305
+ unstable__generateMetadata(renderData: ComponentRenderData, props: {
306
+ params: Promise<ParamsRecord> | ParamsRecord;
307
+ query: Promise<ParamsRecord> | ParamsRecord;
308
+ }): Promise<any>;
309
+ }
310
+
311
+ declare interface FetchComponentDataOpts {
312
+ /**
313
+ * Will fetch either code targeting SSR or browser hydration in the
314
+ * returned bundle.
315
+ *
316
+ * By default, the target is browser. That's okay, because even when
317
+ * doing SSR, as long as you are using the same instance of DaouyLoader
318
+ * that was used to fetch component data, it will still know how to get at
319
+ * the server code.
320
+ *
321
+ * But, if you are building your own SSR solution, where fetching and rendering
322
+ * are using different instances of DaouyLoader, then you'll want to make
323
+ * sure that when you fetch, you are fetching the right one to be used in the
324
+ * right environment for either SSR or browser hydration.
325
+ */
326
+ target?: "server" | "browser";
327
+ }
328
+
329
+ declare type FetchPagesOpts = {
330
+ /**
331
+ * Whether to include dynamic pages in fetchPages() output. A page is
332
+ * considered dynamic if its path contains some param between brackets,
333
+ * e.g. "[slug]".
334
+ */
335
+ includeDynamicPages?: boolean;
336
+ };
337
+
338
+ declare type GlobalContextMeta<P> = Omit<GlobalContextMeta_2<P>, "importPath"> & {
339
+ /**
340
+ * The path to be used when importing the component in the generated code.
341
+ * It can be the name of the package that contains the component, or the path
342
+ * to the file in the project (relative to the root directory).
343
+ * Optional: not used by Daouy headless API, only by codegen.
344
+ */
345
+ importPath?: string;
346
+ };
347
+
348
+ declare interface GlobalVariantSpec {
349
+ name: string;
350
+ projectId?: string;
351
+ value: any;
352
+ }
353
+
354
+ export declare function initDaouyLoader(opts: InitOptions): DaouyComponentLoader;
355
+
356
+ export declare interface InitOptions {
357
+ projects: {
358
+ id: string;
359
+ token: string;
360
+ version?: string;
361
+ }[];
362
+ cache?: LoaderBundleCache;
363
+ platform?: "react" | "nextjs" | "gatsby";
364
+ platformOptions?: {
365
+ nextjs?: {
366
+ appDir: boolean;
367
+ };
368
+ };
369
+ preview?: boolean;
370
+ host?: string;
371
+ onClientSideFetch?: "warn" | "error";
372
+ i18n?: {
373
+ keyScheme: "content" | "hash" | "path";
374
+ tagPrefix?: string;
375
+ };
376
+ /**
377
+ * @deprecated use i18n.keyScheme instead
378
+ */
379
+ i18nKeyScheme?: "content" | "hash";
380
+ /**
381
+ * By default, fetchComponentData() and fetchPages() calls cached in memory
382
+ * with the DaouyComponentLoader instance. If alwaysFresh is true, then
383
+ * data is always freshly fetched over the network.
384
+ */
385
+ alwaysFresh?: boolean;
386
+ /**
387
+ * If true, generated code from the server won't include page metadata tags
388
+ */
389
+ skipHead?: boolean;
390
+ /**
391
+ * If true, uses browser / node's native fetch
392
+ */
393
+ nativeFetch?: boolean;
394
+ /**
395
+ * If true, will not redirect to the codegen server automatically, and will
396
+ * try to reuse the existing bundle in the cache.
397
+ */
398
+ manualRedirect?: boolean;
399
+ }
400
+
401
+ export declare class InternalDaouyComponentLoader extends BaseInternalDaouyComponentLoader {
402
+ constructor(opts: InitOptions);
403
+ registerComponent<T extends React_3.ComponentType<any>>(component: T, meta: CodeComponentMeta<React_3.ComponentProps<T>>): void;
404
+ registerFunction<F extends (...args: any[]) => any>(fn: F, meta: CustomFunctionMeta<F>): void;
405
+ registerGlobalContext<T extends React_3.ComponentType<any>>(context: T, meta: GlobalContextMeta<React_3.ComponentProps<T>>): void;
406
+ registerTrait: (trait: string, meta: TraitMeta) => void;
407
+ registerToken: (token: TokenRegistration) => void;
408
+ refreshRegistry(): void;
409
+ }
410
+
411
+ /**
412
+ * Check if `lookup` resolves to `pagePath`. If it's a match, return an object
413
+ * containing path params; otherwise, return false.
414
+ *
415
+ * For example,
416
+ * - `matchesPagePath("/hello/[name]", "/hello/world")` -> `{params: {name:
417
+ * "world"}}`
418
+ * - `matchesPagePath("/hello/[name]", "/")` -> `false`
419
+ * - `matchesPagePath("/hello/[...catchall]", "/hello/a/b/c")` -> `{params: {catchall: ["a", "b", "c"]}}`
420
+ * - `matchesPagePath("/hello/[[...catchall]]", "/hello/")` -> `{params: {catchall: []}}`
421
+ * - `matchesPagePath("/", "")` -> `{params: {}}`
422
+ */
423
+ export declare function matchesPagePath(pattern: string, path: string): false | {
424
+ params: Record<string, string | string[]>;
425
+ };
426
+
427
+ export { PageMeta }
428
+
429
+ export { PageMetadata }
430
+
431
+ declare type ParamsRecord = Record<string, string | string[] | undefined>;
432
+
433
+ /**
434
+ * Helper functions to describe code component behaviors, in order to allow
435
+ * data extraction in RSC / Next.js App routing.
436
+ */
437
+ declare interface ReactServerOps {
438
+ readDataEnv: typeof useDataEnv;
439
+ readDataSelector: typeof useSelector;
440
+ readDataSelectors: typeof useSelectors;
441
+ /**
442
+ * The contexts are passed using a key instead of the context provider
443
+ * Notice it cannot access the default context value if none has been provided,
444
+ * since React server components cannot create contexts.
445
+ */
446
+ readContext: (contextKey: string) => any;
447
+ /**
448
+ * Allows data fetching from the code component and caching the result,
449
+ * which will be stored in the `queryCache` returned by
450
+ * `extractDaouyQueryData`.
451
+ */
452
+ fetchData: typeof useMutableDaouyQueryData;
453
+ }
454
+
455
+ /**
456
+ * Each child of a code component might receive separate `DataProvider` and
457
+ * Context values.
458
+ */
459
+ declare interface ServerChildData {
460
+ providedData?: ServerProvidedData | ServerProvidedData[];
461
+ providedContexts?: ServerProvidedContext | ServerProvidedContext[];
462
+ node: React.ReactNode;
463
+ }
464
+
465
+ declare interface ServerInfo {
466
+ /**
467
+ * Optional: Indicates the React Nodes created by the component and the
468
+ * respective contexts provided to them. If not specified, it will render the
469
+ * children passed to the component as props.
470
+ */
471
+ children?: ServerChildData | ServerChildData[];
472
+ providedData?: ServerProvidedData | ServerProvidedData[];
473
+ providedContexts?: ServerProvidedContext | ServerProvidedContext[];
474
+ }
475
+
476
+ /**
477
+ * Provides a new value for a given context key, similar to Context.Provider.
478
+ * The context itself is not available (RSC doesn't allow calling
479
+ * `createContext`) so each context will need to be represented as a unique
480
+ * "context key". Also it means the default context value is not available
481
+ * in case no value is passed (and reading that context will return `undefined`)
482
+ */
483
+ declare interface ServerProvidedContext {
484
+ /**
485
+ * Identifier to the context, required to read it later via
486
+ * `ReactServerOps.readContext()`.
487
+ */
488
+ contextKey: string;
489
+ /**
490
+ * Context value being provided (similar to `Context.Provider`).
491
+ */
492
+ value: any;
493
+ }
494
+
495
+ /**
496
+ * Represents data provided by a code component via `DataProvider`
497
+ */
498
+ declare interface ServerProvidedData {
499
+ name: string;
500
+ data: any;
501
+ }
502
+
503
+ export { }