@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.
package/dist/index.js ADDED
@@ -0,0 +1,1566 @@
1
+ "use client";
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __defProps = Object.defineProperties;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
13
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
+ var __spreadValues = (a, b) => {
15
+ for (var prop in b || (b = {}))
16
+ if (__hasOwnProp.call(b, prop))
17
+ __defNormalProp(a, prop, b[prop]);
18
+ if (__getOwnPropSymbols)
19
+ for (var prop of __getOwnPropSymbols(b)) {
20
+ if (__propIsEnum.call(b, prop))
21
+ __defNormalProp(a, prop, b[prop]);
22
+ }
23
+ return a;
24
+ };
25
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
26
+ var __objRest = (source, exclude) => {
27
+ var target = {};
28
+ for (var prop in source)
29
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
30
+ target[prop] = source[prop];
31
+ if (source != null && __getOwnPropSymbols)
32
+ for (var prop of __getOwnPropSymbols(source)) {
33
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
34
+ target[prop] = source[prop];
35
+ }
36
+ return target;
37
+ };
38
+ var __export = (target, all) => {
39
+ for (var name in all)
40
+ __defProp(target, name, { get: all[name], enumerable: true });
41
+ };
42
+ var __copyProps = (to, from, except, desc) => {
43
+ if (from && typeof from === "object" || typeof from === "function") {
44
+ for (let key of __getOwnPropNames(from))
45
+ if (!__hasOwnProp.call(to, key) && key !== except)
46
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
47
+ }
48
+ return to;
49
+ };
50
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
51
+ // If the importer is in node compatibility mode or this is not an ESM
52
+ // file that has been converted to a CommonJS file using a Babel-
53
+ // compatible transform (i.e. "__esModule" has not been set), then set
54
+ // "default" to the CommonJS "module.exports" for node compatibility.
55
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
56
+ mod
57
+ ));
58
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
59
+ var __async = (__this, __arguments, generator) => {
60
+ return new Promise((resolve, reject) => {
61
+ var fulfilled = (value) => {
62
+ try {
63
+ step(generator.next(value));
64
+ } catch (e) {
65
+ reject(e);
66
+ }
67
+ };
68
+ var rejected = (value) => {
69
+ try {
70
+ step(generator.throw(value));
71
+ } catch (e) {
72
+ reject(e);
73
+ }
74
+ };
75
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
76
+ step((generator = generator.apply(__this, __arguments)).next());
77
+ });
78
+ };
79
+
80
+ // src/index.ts
81
+ var src_exports = {};
82
+ __export(src_exports, {
83
+ DaouyCanvasContext: () => import_host3.DaouyCanvasContext,
84
+ DaouyCanvasHost: () => import_host3.DaouyCanvasHost,
85
+ DaouyComponent: () => DaouyComponent,
86
+ DaouyComponentLoader: () => DaouyComponentLoader,
87
+ DaouyRootProvider: () => DaouyRootProvider,
88
+ DaouyTranslatorContext: () => import_host3.DaouyTranslatorContext,
89
+ DataCtxReader: () => import_host3.DataCtxReader,
90
+ DataProvider: () => import_host3.DataProvider,
91
+ GlobalActionsContext: () => import_host3.GlobalActionsContext,
92
+ GlobalActionsProvider: () => import_host3.GlobalActionsProvider,
93
+ InternalDaouyComponentLoader: () => InternalDaouyComponentLoader,
94
+ PageParamsProvider: () => import_host3.PageParamsProvider,
95
+ convertBundlesToComponentRenderData: () => convertBundlesToComponentRenderData,
96
+ daouyPrepass: () => daouyPrepass,
97
+ extractDaouyQueryData: () => extractDaouyQueryData,
98
+ extractDaouyQueryDataFromElement: () => extractDaouyQueryDataFromElement,
99
+ hydrateFromElement: () => hydrateFromElement,
100
+ initDaouyLoader: () => initDaouyLoader,
101
+ matchesPagePath: () => matchesPagePath,
102
+ renderToElement: () => renderToElement,
103
+ renderToString: () => renderToString,
104
+ repeatedElement: () => import_host3.repeatedElement,
105
+ useDaouyCanvasComponentInfo: () => import_host3.useDaouyCanvasComponentInfo,
106
+ useDaouyCanvasContext: () => import_host3.useDaouyCanvasContext,
107
+ useDaouyComponent: () => useDaouyComponent,
108
+ useDaouyQueryData: () => import_query2.useDaouyQueryData,
109
+ useDataEnv: () => import_host3.useDataEnv,
110
+ useSelector: () => import_host3.useSelector,
111
+ useSelectors: () => import_host3.useSelectors
112
+ });
113
+ module.exports = __toCommonJS(src_exports);
114
+
115
+ // src/loader-client.ts
116
+ var DaouyDataSourcesContext = __toESM(require("@daouy/data-sources-context"));
117
+ var DaouyHost = __toESM(require("@daouy/host"));
118
+ var import_host2 = require("@daouy/host");
119
+ var import_loader_core3 = require("@daouy/loader-core");
120
+ var DaouyQuery = __toESM(require("@daouy/query"));
121
+ var import_react = __toESM(require("react"));
122
+ var import_react_dom = __toESM(require("react-dom"));
123
+ var jsxDevRuntime = __toESM(require("react/jsx-dev-runtime"));
124
+ var jsxRuntime = __toESM(require("react/jsx-runtime"));
125
+
126
+ // src/PlasmicRootProvider.tsx
127
+ var import_host = require("@daouy/host");
128
+ var import_query = require("@daouy/query");
129
+ var React2 = __toESM(require("react"));
130
+
131
+ // src/utils.tsx
132
+ var import_pascalcase = __toESM(require("pascalcase"));
133
+ var React = __toESM(require("react"));
134
+ var isBrowser = typeof window !== "undefined";
135
+ function useForceUpdate() {
136
+ const [, setTick] = React.useState(0);
137
+ const update = React.useCallback(() => {
138
+ setTick((tick) => tick + 1);
139
+ }, []);
140
+ return update;
141
+ }
142
+ function useStableLookupSpec(spec) {
143
+ return useStableLookupSpecs(spec)[0];
144
+ }
145
+ function useStableLookupSpecs(...specs) {
146
+ const [stableSpecs, setStableSpecs] = React.useState(specs);
147
+ React.useEffect(() => {
148
+ if (specs.length !== stableSpecs.length || specs.some((s, i) => !areLookupSpecsEqual(s, stableSpecs[i]))) {
149
+ setStableSpecs(specs);
150
+ }
151
+ }, [specs, stableSpecs]);
152
+ return stableSpecs;
153
+ }
154
+ function areLookupSpecsEqual(spec1, spec2) {
155
+ if (spec1 === spec2) {
156
+ return true;
157
+ }
158
+ if (typeof spec1 !== typeof spec2) {
159
+ return false;
160
+ }
161
+ const fullSpec1 = toFullLookup(spec1);
162
+ const fullSpec2 = toFullLookup(spec2);
163
+ return (isNameSpec(fullSpec1) && isNameSpec(fullSpec2) && fullSpec1.name === fullSpec2.name && fullSpec1.isCode === fullSpec2.isCode || isPathSpec(fullSpec1) && isPathSpec(fullSpec2) && fullSpec1.path === fullSpec2.path) && fullSpec1.projectId === fullSpec2.projectId;
164
+ }
165
+ function isNameSpec(lookup) {
166
+ return "name" in lookup;
167
+ }
168
+ function isPathSpec(lookup) {
169
+ return "path" in lookup;
170
+ }
171
+ function toFullLookup(lookup) {
172
+ const namePart = typeof lookup === "string" ? lookup : lookup.name;
173
+ const projectId = typeof lookup === "string" ? void 0 : lookup.projectId;
174
+ const codeComponent = typeof lookup === "string" ? void 0 : lookup.isCode;
175
+ if (codeComponent !== true && namePart.startsWith("/")) {
176
+ return { path: normalizePath(namePart), projectId };
177
+ } else {
178
+ return {
179
+ name: codeComponent ? namePart : normalizeName(namePart),
180
+ rawName: namePart.trim(),
181
+ projectId,
182
+ isCode: codeComponent
183
+ };
184
+ }
185
+ }
186
+ function normalizePath(path) {
187
+ return path.trim();
188
+ }
189
+ function normalizeName(name) {
190
+ return (0, import_pascalcase.default)(name).trim();
191
+ }
192
+ function useIsMounted() {
193
+ const ref = React.useRef(false);
194
+ const isMounted = React.useCallback(() => ref.current, []);
195
+ React.useEffect(() => {
196
+ ref.current = true;
197
+ return () => {
198
+ ref.current = false;
199
+ };
200
+ }, []);
201
+ return isMounted;
202
+ }
203
+ function matchesPagePath(pattern, path) {
204
+ const normalizedPattern = "/" + pattern.replace(/^\/|\/$/g, "");
205
+ const normalizedPath = "/" + path.replace(/^\/|\/$/g, "");
206
+ const regexString = normalizedPattern.replace(/\/\[\[\.\.\.([^\]^]+)]]/g, "(?:/([^]*))?").replace(/\/\[\.\.\.([^\]^]+)]/g, "/([^]*)").replace(/\[([^\]^]+)]/g, "([^/]+)").replace(/\//g, "\\/");
207
+ const regex = new RegExp(`^/?${regexString}$`);
208
+ const match = normalizedPath.match(regex);
209
+ if (!match)
210
+ return false;
211
+ const slugNames = [...pattern.matchAll(/\[\.?\.?\.?([^[\]]+)]/g)].map(
212
+ (m) => m[1]
213
+ );
214
+ const params = {};
215
+ for (let i = 0; i < slugNames.length; i++) {
216
+ const slugName = slugNames[i];
217
+ const value = match[i + 1];
218
+ if (pattern.includes(`[[...${slugName}]]`)) {
219
+ params[slugName] = value ? value.split("/").filter(Boolean) : [];
220
+ } else if (pattern.includes(`[...${slugName}]`)) {
221
+ params[slugName] = value.split("/").filter(Boolean);
222
+ } else if (value !== void 0) {
223
+ params[slugName] = value;
224
+ }
225
+ }
226
+ return { params };
227
+ }
228
+ function isDynamicPagePath(path) {
229
+ return !!path.match(/\[[^/]*\]/);
230
+ }
231
+ function matchesCompMeta(lookup, meta) {
232
+ if (lookup.projectId && meta.projectId !== lookup.projectId) {
233
+ return false;
234
+ }
235
+ return isNameSpec(lookup) ? (lookup.name === meta.name || lookup.rawName === meta.name || lookup.rawName === meta.displayName) && (lookup.isCode == null || lookup.isCode === meta.isCode) : !!(meta.path && matchesPagePath(meta.path, lookup.path));
236
+ }
237
+ function getCompMetas(metas, lookup) {
238
+ const full = toFullLookup(lookup);
239
+ return metas.filter((meta) => matchesCompMeta(full, meta)).map(
240
+ (meta) => {
241
+ if (isNameSpec(full) || !meta.path) {
242
+ return meta;
243
+ }
244
+ const match = matchesPagePath(meta.path, full.path);
245
+ if (!match) {
246
+ return meta;
247
+ }
248
+ return __spreadProps(__spreadValues({}, meta), { params: match.params });
249
+ }
250
+ ).sort(
251
+ (meta1, meta2) => (
252
+ // We sort the matched component metas by the number of path params, so
253
+ // if there are two pages `/products/foo` and `/products/[slug]`,
254
+ // the first one will have higher precedence.
255
+ Array.from(Object.keys(meta1.params || {})).length - Array.from(Object.keys(meta2.params || {})).length
256
+ )
257
+ );
258
+ }
259
+ function getLookupSpecName(lookup) {
260
+ if (typeof lookup === "string") {
261
+ return lookup;
262
+ } else if (lookup.projectId) {
263
+ return `${lookup.name} (project ${lookup.projectId})`;
264
+ } else {
265
+ return lookup.name;
266
+ }
267
+ }
268
+ function MaybeWrap(props) {
269
+ return props.cond ? props.wrapper(props.children) : props.children;
270
+ }
271
+ function uniq(elements) {
272
+ return Array.from(new Set(elements));
273
+ }
274
+ function intersect(a, b) {
275
+ const setB = new Set(b);
276
+ return a.filter((elt) => setB.has(elt));
277
+ }
278
+
279
+ // src/variation.ts
280
+ function getDaouyCookieValues() {
281
+ return Object.fromEntries(
282
+ document.cookie.split("; ").filter((cookie) => cookie.includes("daouy:")).map((cookie) => cookie.split("=")).map(([key, value]) => [key.split(":")[1], value])
283
+ );
284
+ }
285
+ function updateDaouyCookieValue(key, value) {
286
+ document.cookie = `daouy:${key}=${value}`;
287
+ }
288
+ var getGlobalVariantsFromSplits = (splits, variation) => {
289
+ const globalVariants = [];
290
+ Object.keys(variation).map((variationKey) => {
291
+ const [_type, splitId] = variationKey.split(".");
292
+ const sliceId = variation[variationKey];
293
+ const split = splits.find(
294
+ (s) => s.id === splitId || s.externalId === splitId
295
+ );
296
+ if (split) {
297
+ const slice = split.slices.find((s) => s.id === sliceId || s.externalId === sliceId);
298
+ if (slice) {
299
+ slice.contents.map((x) => {
300
+ globalVariants.push({
301
+ name: x.group,
302
+ value: x.variant,
303
+ projectId: x.projectId
304
+ });
305
+ });
306
+ }
307
+ }
308
+ });
309
+ return globalVariants;
310
+ };
311
+ var mergeGlobalVariantsSpec = (target, from) => {
312
+ let result = [...target];
313
+ const existingGlobalVariants = new Set(
314
+ target.map((t) => {
315
+ var _a;
316
+ return `${t.name}-${(_a = t.projectId) != null ? _a : ""}`;
317
+ })
318
+ );
319
+ const newGlobals = from.filter(
320
+ (t) => {
321
+ var _a;
322
+ return !existingGlobalVariants.has(`${t.name}-${(_a = t.projectId) != null ? _a : ""}`);
323
+ }
324
+ );
325
+ if (newGlobals.length > 0) {
326
+ result = [...result, ...newGlobals];
327
+ }
328
+ return result;
329
+ };
330
+
331
+ // src/PlasmicRootProvider.tsx
332
+ var DaouyRootContext = React2.createContext(void 0);
333
+ function DaouyRootProvider(props) {
334
+ const {
335
+ globalVariants,
336
+ prefetchedData,
337
+ children,
338
+ skipCss,
339
+ skipFonts,
340
+ prefetchedQueryData,
341
+ suspenseForQueryData,
342
+ globalContextsProps,
343
+ variation,
344
+ translator,
345
+ Head,
346
+ Link,
347
+ pageRoute,
348
+ pageParams,
349
+ pageQuery,
350
+ suspenseFallback,
351
+ disableLoadingBoundary,
352
+ disableRootLoadingBoundary,
353
+ styleTokenOverridesProjectId
354
+ } = props;
355
+ const loader = props.loader.__internal;
356
+ if (prefetchedData) {
357
+ loader.registerPrefetchedBundle(prefetchedData.bundle);
358
+ }
359
+ const [splits, setSplits] = React2.useState(loader.getActiveSplits());
360
+ const forceUpdate = useForceUpdate();
361
+ const watcher = React2.useMemo(
362
+ () => ({
363
+ onDataFetched: () => {
364
+ setSplits(loader.getActiveSplits());
365
+ forceUpdate();
366
+ }
367
+ }),
368
+ [loader, forceUpdate]
369
+ );
370
+ React2.useEffect(() => {
371
+ loader.subscribeDaouyRoot(watcher);
372
+ return () => loader.unsubscribeDaouyRoot(watcher);
373
+ }, [watcher, loader]);
374
+ const currentContextValue = React2.useContext(DaouyRootContext);
375
+ const { user, userAuthToken, isUserLoading, authRedirectUri } = props;
376
+ const value = React2.useMemo(() => {
377
+ var _a, _b, _c;
378
+ const withCurrentContextValueFallback = (v, key) => {
379
+ return v !== void 0 ? v : currentContextValue == null ? void 0 : currentContextValue[key];
380
+ };
381
+ return {
382
+ globalVariants: [
383
+ ...mergeGlobalVariantsSpec(
384
+ globalVariants != null ? globalVariants : [],
385
+ getGlobalVariantsFromSplits(splits, variation != null ? variation : {})
386
+ ),
387
+ ...(_a = currentContextValue == null ? void 0 : currentContextValue.globalVariants) != null ? _a : []
388
+ ],
389
+ globalContextsProps: __spreadValues(__spreadValues({}, (_b = currentContextValue == null ? void 0 : currentContextValue.globalContextsProps) != null ? _b : {}), globalContextsProps != null ? globalContextsProps : {}),
390
+ loader: withCurrentContextValueFallback(loader, "loader"),
391
+ variation: __spreadValues(__spreadValues({}, (_c = currentContextValue == null ? void 0 : currentContextValue.variation) != null ? _c : {}), variation != null ? variation : {}),
392
+ translator: withCurrentContextValueFallback(translator, "translator"),
393
+ Head: withCurrentContextValueFallback(Head, "Head"),
394
+ Link: withCurrentContextValueFallback(Link, "Link"),
395
+ user: withCurrentContextValueFallback(user, "user"),
396
+ userAuthToken: withCurrentContextValueFallback(
397
+ userAuthToken,
398
+ "userAuthToken"
399
+ ),
400
+ isUserLoading: withCurrentContextValueFallback(
401
+ isUserLoading,
402
+ "isUserLoading"
403
+ ),
404
+ authRedirectUri: withCurrentContextValueFallback(
405
+ authRedirectUri,
406
+ "authRedirectUri"
407
+ ),
408
+ suspenseFallback: withCurrentContextValueFallback(
409
+ suspenseFallback,
410
+ "suspenseFallback"
411
+ ),
412
+ disableLoadingBoundary: withCurrentContextValueFallback(
413
+ disableLoadingBoundary,
414
+ "disableLoadingBoundary"
415
+ ),
416
+ styleTokenOverridesProjectId
417
+ };
418
+ }, [
419
+ globalVariants,
420
+ variation,
421
+ globalContextsProps,
422
+ loader,
423
+ splits,
424
+ translator,
425
+ Head,
426
+ Link,
427
+ user,
428
+ userAuthToken,
429
+ isUserLoading,
430
+ authRedirectUri,
431
+ suspenseFallback,
432
+ disableLoadingBoundary,
433
+ styleTokenOverridesProjectId,
434
+ currentContextValue
435
+ ]);
436
+ React2.useEffect(() => {
437
+ loader.trackRender({
438
+ renderCtx: {
439
+ // We track the provider as a single entity
440
+ rootComponentId: "provider",
441
+ teamIds: loader.getTeamIds(),
442
+ projectIds: loader.getProjectIds()
443
+ },
444
+ variation: value.variation
445
+ });
446
+ }, [loader, value]);
447
+ const reactMajorVersion = +React2.version.split(".")[0];
448
+ const shouldDisableRootLoadingBoundary = disableRootLoadingBoundary != null ? disableRootLoadingBoundary : loader.getBundle().disableRootLoadingBoundaryByDefault;
449
+ return /* @__PURE__ */ React2.createElement(
450
+ import_query.DaouyQueryDataProvider,
451
+ {
452
+ prefetchedCache: prefetchedQueryData,
453
+ suspense: suspenseForQueryData
454
+ },
455
+ /* @__PURE__ */ React2.createElement(DaouyRootContext.Provider, { value }, !skipCss && /* @__PURE__ */ React2.createElement(
456
+ DaouyCss,
457
+ {
458
+ loader,
459
+ prefetchedData,
460
+ skipFonts
461
+ }
462
+ ), /* @__PURE__ */ React2.createElement(
463
+ import_host.PageParamsProvider,
464
+ {
465
+ route: pageRoute,
466
+ params: pageParams,
467
+ query: pageQuery
468
+ },
469
+ /* @__PURE__ */ React2.createElement(
470
+ MaybeWrap,
471
+ {
472
+ cond: !shouldDisableRootLoadingBoundary && reactMajorVersion >= 18,
473
+ wrapper: (contents) => /* @__PURE__ */ React2.createElement(React2.Suspense, { fallback: suspenseFallback != null ? suspenseFallback : "Loading..." }, contents)
474
+ },
475
+ children
476
+ )
477
+ ))
478
+ );
479
+ }
480
+ var DaouyCss = React2.memo(function DaouyCss2(props) {
481
+ const { loader, prefetchedData, skipFonts } = props;
482
+ const [useScopedCss, setUseScopedCss] = React2.useState(!!prefetchedData);
483
+ const builtCss = buildCss(loader, {
484
+ scopedCompMetas: useScopedCss && prefetchedData ? prefetchedData.bundle.components : void 0,
485
+ skipFonts
486
+ });
487
+ const forceUpdate = useForceUpdate();
488
+ const watcher = React2.useMemo(
489
+ () => ({
490
+ onDataFetched: () => {
491
+ setUseScopedCss(false);
492
+ forceUpdate();
493
+ }
494
+ }),
495
+ [loader, forceUpdate]
496
+ );
497
+ React2.useEffect(() => {
498
+ loader.subscribeDaouyRoot(watcher);
499
+ return () => loader.unsubscribeDaouyRoot(watcher);
500
+ }, [watcher, loader]);
501
+ return /* @__PURE__ */ React2.createElement("style", { dangerouslySetInnerHTML: { __html: builtCss } });
502
+ });
503
+ function buildCss(loader, opts) {
504
+ const { scopedCompMetas, skipFonts } = opts;
505
+ const cssFiles = scopedCompMetas && /* @__PURE__ */ new Set([
506
+ "entrypoint.css",
507
+ ...scopedCompMetas.map((c) => c.cssFile)
508
+ ]);
509
+ const cssModules = loader.getLookup().getCss().filter((f) => !cssFiles || cssFiles.has(f.fileName));
510
+ const getPri = (fileName) => fileName === "entrypoint.css" ? 0 : 1;
511
+ const compareModules = (a, b) => getPri(a.fileName) !== getPri(b.fileName) ? getPri(a.fileName) - getPri(b.fileName) : a.fileName.localeCompare(b.fileName);
512
+ cssModules.sort(compareModules);
513
+ const remoteFonts = loader.getLookup().getRemoteFonts();
514
+ return `
515
+ ${skipFonts ? "" : remoteFonts.map((f) => `@import url('${f.url}');`).join("\n")}
516
+ ${cssModules.map((mod) => mod.source).join("\n")}
517
+ `;
518
+ }
519
+ function useDaouyRootContext() {
520
+ return React2.useContext(DaouyRootContext);
521
+ }
522
+
523
+ // src/global-variants.ts
524
+ function createUseGlobalVariant(name, projectId) {
525
+ return () => {
526
+ var _a;
527
+ const rootContext = useDaouyRootContext();
528
+ if (!rootContext) {
529
+ return void 0;
530
+ }
531
+ const loader = rootContext.loader;
532
+ const spec = [
533
+ ...loader.getGlobalVariants(),
534
+ ...(_a = rootContext.globalVariants) != null ? _a : []
535
+ ].find(
536
+ (spec2) => spec2.name === name && (!spec2.projectId || spec2.projectId === projectId)
537
+ );
538
+ return spec ? spec.value : void 0;
539
+ };
540
+ }
541
+
542
+ // src/loader-shared.ts
543
+ var import_loader_core2 = require("@daouy/loader-core");
544
+ var import_loader_fetcher = require("@daouy/loader-fetcher");
545
+ var import_loader_splits = require("@daouy/loader-splits");
546
+
547
+ // src/bundles.ts
548
+ var import_loader_core = require("@daouy/loader-core");
549
+ function getUsedComps(allComponents, entryCompIds) {
550
+ const q = [...entryCompIds];
551
+ const seenIds = new Set(entryCompIds);
552
+ const componentMetaById = new Map(
553
+ allComponents.map((meta) => [meta.id, meta])
554
+ );
555
+ const usedComps = [];
556
+ while (q.length > 0) {
557
+ const [id] = q.splice(0, 1);
558
+ const meta = componentMetaById.get(id);
559
+ if (!meta) {
560
+ continue;
561
+ }
562
+ usedComps.push(meta);
563
+ meta.usedComponents.forEach((usedCompId) => {
564
+ if (!seenIds.has(usedCompId)) {
565
+ seenIds.add(usedCompId);
566
+ q.push(usedCompId);
567
+ }
568
+ });
569
+ }
570
+ return usedComps;
571
+ }
572
+ function prepComponentData(bundle, compMetas, opts) {
573
+ if (compMetas.length === 0) {
574
+ return {
575
+ entryCompMetas: bundle.components,
576
+ bundle,
577
+ remoteFontUrls: []
578
+ };
579
+ }
580
+ const usedComps = getUsedComps(
581
+ bundle.components,
582
+ compMetas.map((compMeta) => compMeta.id)
583
+ );
584
+ const compPaths = usedComps.map((compMeta) => compMeta.entry);
585
+ const subBundle = (0, import_loader_core.getBundleSubset)(
586
+ bundle,
587
+ [
588
+ "entrypoint.css",
589
+ ...compPaths,
590
+ "root-provider.js",
591
+ ...bundle.projects.map((x) => x.styleTokensProviderFileName).filter((x) => !!x),
592
+ ...bundle.projects.map((x) => x.globalContextsProviderFileName).filter((x) => !!x),
593
+ // We need to explicitly include global context provider components
594
+ // to make sure they are kept in bundle.components. That's because
595
+ // for esbuild, just the globalContextsProviderFileName is not enough,
596
+ // because it will import a chunk that includes the global context
597
+ // component, instead of importing that global context component's
598
+ // entry file. And because nothing depends on the global context component's
599
+ // entry file, we end up excluding the global context component from
600
+ // bundle.components, which then makes its substitution not work.
601
+ // Instead, we forcibly include it here (we'll definitely need it anyway!).
602
+ ...bundle.components.filter((c) => c.isGlobalContextProvider).map((c) => c.entry),
603
+ ...bundle.globalGroups.map((g) => g.contextFile)
604
+ ],
605
+ opts
606
+ );
607
+ const remoteFontUrls = [];
608
+ subBundle.projects.forEach(
609
+ (p) => remoteFontUrls.push(...p.remoteFonts.map((f) => f.url))
610
+ );
611
+ return {
612
+ entryCompMetas: compMetas,
613
+ bundle: subBundle,
614
+ remoteFontUrls
615
+ };
616
+ }
617
+ function mergeBundles(target, from) {
618
+ var _a, _b, _c, _d, _e, _f, _g;
619
+ const existingProjects = new Set(target.projects.map((p) => p.id));
620
+ const newProjects = from.projects.filter((p) => !existingProjects.has(p.id));
621
+ if (newProjects.length > 0) {
622
+ target = __spreadProps(__spreadValues({}, target), {
623
+ projects: [...target.projects, ...newProjects]
624
+ });
625
+ }
626
+ const existingCompIds = new Set(target.components.map((c) => c.id));
627
+ function shouldIncludeComponentInBundle(c) {
628
+ var _a2;
629
+ if (existingCompIds.has(c.id)) {
630
+ return false;
631
+ }
632
+ if (!existingProjects.has(c.projectId)) {
633
+ return true;
634
+ }
635
+ const targetBundleFilteredIds = (_a2 = target.filteredIds[c.projectId]) != null ? _a2 : [];
636
+ return targetBundleFilteredIds.includes(c.id);
637
+ }
638
+ const newCompMetas = from.components.filter(
639
+ (m) => shouldIncludeComponentInBundle(m)
640
+ );
641
+ if (newCompMetas.length > 0) {
642
+ target = __spreadProps(__spreadValues({}, target), {
643
+ components: [...target.components, ...newCompMetas]
644
+ });
645
+ target.filteredIds = Object.fromEntries(
646
+ Object.entries(target.filteredIds).map(([k, v]) => [k, [...v]])
647
+ );
648
+ from.projects.forEach((fromProject) => {
649
+ var _a2, _b2;
650
+ const projectId = fromProject.id;
651
+ const fromBundleFilteredIds = (_a2 = from.filteredIds[projectId]) != null ? _a2 : [];
652
+ if (!existingProjects.has(projectId)) {
653
+ target.filteredIds[projectId] = [...fromBundleFilteredIds];
654
+ } else {
655
+ target.filteredIds[projectId] = intersect(
656
+ (_b2 = target.filteredIds[projectId]) != null ? _b2 : [],
657
+ fromBundleFilteredIds
658
+ );
659
+ }
660
+ });
661
+ }
662
+ const existingModules = {
663
+ browser: new Set(target.modules.browser.map((m) => m.fileName)),
664
+ server: new Set(target.modules.server.map((m) => m.fileName))
665
+ };
666
+ const newModules = {
667
+ browser: from.modules.browser.filter(
668
+ (m) => !existingModules.browser.has(m.fileName)
669
+ ),
670
+ server: from.modules.server.filter(
671
+ (m) => !existingModules.server.has(m.fileName)
672
+ )
673
+ };
674
+ if (newModules.browser.length > 0 || newModules.server.length > 0) {
675
+ target = __spreadProps(__spreadValues({}, target), {
676
+ modules: {
677
+ browser: [...target.modules.browser, ...newModules.browser],
678
+ server: [...target.modules.server, ...newModules.server]
679
+ }
680
+ });
681
+ }
682
+ const existingGlobalIds = new Set(target.globalGroups.map((g) => g.id));
683
+ const newGlobals = from.globalGroups.filter(
684
+ (g) => !existingGlobalIds.has(g.id)
685
+ );
686
+ if (newGlobals.length > 0) {
687
+ target = __spreadProps(__spreadValues({}, target), {
688
+ globalGroups: [...target.globalGroups, ...newGlobals]
689
+ });
690
+ }
691
+ const existingSplitIds = new Set(target.activeSplits.map((s) => s.id));
692
+ const newSplits = (_a = from.activeSplits.filter(
693
+ // Don't include splits belonging to projects already present
694
+ // in the target bundle
695
+ (s) => !existingSplitIds.has(s.id) && !existingProjects.has(s.projectId)
696
+ )) != null ? _a : [];
697
+ if (newSplits.length > 0) {
698
+ target = __spreadProps(__spreadValues({}, target), {
699
+ activeSplits: [...target.activeSplits, ...newSplits]
700
+ });
701
+ }
702
+ target.bundleKey = (_c = (_b = target.bundleKey) != null ? _b : from.bundleKey) != null ? _c : null;
703
+ target.deferChunksByDefault = (_e = (_d = target.deferChunksByDefault) != null ? _d : from.deferChunksByDefault) != null ? _e : false;
704
+ target.disableRootLoadingBoundaryByDefault = (_g = (_f = target.disableRootLoadingBoundaryByDefault) != null ? _f : from.disableRootLoadingBoundaryByDefault) != null ? _g : false;
705
+ return target;
706
+ }
707
+ var convertBundlesToComponentRenderData = (bundles, compMetas) => {
708
+ if (bundles.length === 0) {
709
+ return null;
710
+ }
711
+ const mergedBundles = bundles.reduce((prev, cur) => mergeBundles(prev, cur));
712
+ return prepComponentData(mergedBundles, compMetas);
713
+ };
714
+
715
+ // src/component-lookup.ts
716
+ function getFirstCompMeta(metas, lookup) {
717
+ const filtered = getCompMetas(metas, lookup);
718
+ return filtered.length === 0 ? void 0 : filtered[0];
719
+ }
720
+ var ComponentLookup = class {
721
+ constructor(bundle, registry) {
722
+ this.bundle = bundle;
723
+ this.registry = registry;
724
+ }
725
+ getComponentMeta(spec) {
726
+ const compMeta = getFirstCompMeta(this.bundle.components, spec);
727
+ return compMeta;
728
+ }
729
+ getComponent(spec, opts = {}) {
730
+ const compMeta = getFirstCompMeta(this.bundle.components, spec);
731
+ if (!compMeta) {
732
+ throw new Error(`Component not found: ${spec}`);
733
+ }
734
+ const moduleName = compMeta.entry;
735
+ if (!this.registry.hasModule(moduleName, opts)) {
736
+ throw new Error(`Component not yet fetched: ${compMeta.name}`);
737
+ }
738
+ const entry = this.registry.load(moduleName, {
739
+ forceOriginal: opts.forceOriginal
740
+ });
741
+ return !opts.forceOriginal && typeof (entry == null ? void 0 : entry.getDaouyComponent) === "function" ? entry.getDaouyComponent() : entry.default;
742
+ }
743
+ hasComponent(spec) {
744
+ const compMeta = getFirstCompMeta(this.bundle.components, spec);
745
+ if (compMeta) {
746
+ return this.registry.hasModule(compMeta.entry);
747
+ }
748
+ return false;
749
+ }
750
+ getGlobalContexts() {
751
+ const customGlobalMetas = this.bundle.globalGroups.filter(
752
+ (m) => m.type === "global-user-defined"
753
+ );
754
+ return customGlobalMetas.map((meta) => ({
755
+ meta,
756
+ context: this.registry.load(meta.contextFile).default
757
+ }));
758
+ }
759
+ /** Returns StyleTokensProvider if the project has style token overrides. */
760
+ maybeGetStyleTokensProvider(spec, styleTokenOverridesProjectId) {
761
+ const compMeta = getFirstCompMeta(this.bundle.components, spec);
762
+ let projectMeta;
763
+ if (styleTokenOverridesProjectId) {
764
+ projectMeta = this.bundle.projects.find(
765
+ (x) => x.id === styleTokenOverridesProjectId
766
+ );
767
+ if (!projectMeta) {
768
+ console.warn(
769
+ `styleTokenOverridesProjectId "${styleTokenOverridesProjectId}" not found. Defaulting to root component's project.`
770
+ );
771
+ }
772
+ }
773
+ if (!projectMeta && (compMeta == null ? void 0 : compMeta.projectId)) {
774
+ projectMeta = this.bundle.projects.find(
775
+ (x) => x.id === compMeta.projectId
776
+ );
777
+ }
778
+ if (!projectMeta || !projectMeta.styleTokensProviderFileName || !this.registry.hasModule(projectMeta.styleTokensProviderFileName) || !projectMeta.hasStyleTokenOverrides) {
779
+ return void 0;
780
+ }
781
+ const entry = this.registry.load(projectMeta.styleTokensProviderFileName);
782
+ return entry.StyleTokensProvider;
783
+ }
784
+ getGlobalContextsProvider(spec) {
785
+ const compMeta = getFirstCompMeta(this.bundle.components, spec);
786
+ const projectMeta = compMeta ? this.bundle.projects.find((x) => x.id === compMeta.projectId) : void 0;
787
+ if (!projectMeta || !projectMeta.globalContextsProviderFileName || !this.registry.hasModule(projectMeta.globalContextsProviderFileName)) {
788
+ return void 0;
789
+ }
790
+ const entry = this.registry.load(
791
+ projectMeta.globalContextsProviderFileName
792
+ );
793
+ return typeof (entry == null ? void 0 : entry.getDaouyComponent) === "function" ? entry.getDaouyComponent() : entry.default;
794
+ }
795
+ getRootProvider() {
796
+ const entry = this.registry.load("root-provider.js");
797
+ return entry.default;
798
+ }
799
+ getCss() {
800
+ return this.bundle.modules.browser.filter(
801
+ (mod) => mod.type === "asset" && mod.fileName.endsWith("css")
802
+ );
803
+ }
804
+ getRemoteFonts() {
805
+ return this.bundle.projects.flatMap((p) => p.remoteFonts);
806
+ }
807
+ };
808
+
809
+ // src/loader-shared.ts
810
+ var SUBSTITUTED_COMPONENTS = {};
811
+ var REGISTERED_CODE_COMPONENT_HELPERS = {};
812
+ var SUBSTITUTED_GLOBAL_VARIANT_HOOKS = {};
813
+ var REGISTERED_CUSTOM_FUNCTIONS = {};
814
+ function customFunctionImportAlias(meta) {
815
+ const customFunctionPrefix = `__fn_`;
816
+ return meta.namespace ? `${customFunctionPrefix}${meta.namespace}__${meta.name}` : `${customFunctionPrefix}${meta.name}`;
817
+ }
818
+ function internalSetRegisteredFunction(fn, meta) {
819
+ REGISTERED_CUSTOM_FUNCTIONS[customFunctionImportAlias(meta)] = fn;
820
+ }
821
+ function parseFetchComponentDataArgs(...args) {
822
+ let specs;
823
+ let opts;
824
+ if (Array.isArray(args[0])) {
825
+ specs = args[0];
826
+ opts = args[1];
827
+ } else {
828
+ specs = args;
829
+ opts = void 0;
830
+ }
831
+ return { specs, opts };
832
+ }
833
+ var BaseInternalDaouyComponentLoader = class {
834
+ constructor(args) {
835
+ this.registry = new import_loader_core2.Registry();
836
+ this.globalVariants = [];
837
+ this.subs = [];
838
+ this.bundle = {
839
+ modules: {
840
+ browser: [],
841
+ server: []
842
+ },
843
+ components: [],
844
+ globalGroups: [],
845
+ projects: [],
846
+ activeSplits: [],
847
+ bundleKey: null,
848
+ deferChunksByDefault: false,
849
+ disableRootLoadingBoundaryByDefault: false,
850
+ filteredIds: {}
851
+ };
852
+ this.opts = args.opts;
853
+ this.fetcher = args.fetcher;
854
+ this.onBundleMerged = args.onBundleMerged;
855
+ this.onBundleFetched = args.onBundleFetched;
856
+ this.registerModules(args.builtinModules);
857
+ }
858
+ maybeGetCompMetas(...specs) {
859
+ const found = /* @__PURE__ */ new Set();
860
+ const missing = [];
861
+ for (const spec of specs) {
862
+ const filteredMetas = getCompMetas(this.bundle.components, spec);
863
+ if (filteredMetas.length > 0) {
864
+ filteredMetas.forEach((meta) => found.add(meta));
865
+ } else {
866
+ missing.push(spec);
867
+ }
868
+ }
869
+ return { found: Array.from(found.keys()), missing };
870
+ }
871
+ maybeFetchComponentData(...args) {
872
+ return __async(this, null, function* () {
873
+ const { specs, opts } = parseFetchComponentDataArgs(...args);
874
+ const returnWithSpecsToFetch = (specsToFetch) => __async(this, null, function* () {
875
+ yield this.fetchMissingData({ missingSpecs: specsToFetch });
876
+ const { found: existingMetas2, missing: missingSpecs2 } = this.maybeGetCompMetas(...specs);
877
+ if (missingSpecs2.length > 0) {
878
+ return null;
879
+ }
880
+ return prepComponentData(this.bundle, existingMetas2, opts);
881
+ });
882
+ if (this.opts.alwaysFresh) {
883
+ return yield returnWithSpecsToFetch(specs);
884
+ }
885
+ const { found: existingMetas, missing: missingSpecs } = this.maybeGetCompMetas(...specs);
886
+ if (missingSpecs.length === 0) {
887
+ return prepComponentData(this.bundle, existingMetas, opts);
888
+ }
889
+ return yield returnWithSpecsToFetch(missingSpecs);
890
+ });
891
+ }
892
+ fetchComponentData(...args) {
893
+ return __async(this, null, function* () {
894
+ const { specs, opts } = parseFetchComponentDataArgs(...args);
895
+ const data = yield this.maybeFetchComponentData(specs, opts);
896
+ if (!data) {
897
+ const { missing: missingSpecs } = this.maybeGetCompMetas(...specs);
898
+ throw new Error(
899
+ `Unable to find components ${missingSpecs.map(getLookupSpecName).join(", ")}`
900
+ );
901
+ }
902
+ return data;
903
+ });
904
+ }
905
+ fetchPages(opts) {
906
+ return __async(this, null, function* () {
907
+ this.maybeReportClientSideFetch(
908
+ () => `Daouy: fetching all page metadata in the browser`
909
+ );
910
+ const data = yield this.fetchAllData();
911
+ return data.components.filter(
912
+ (comp) => comp.isPage && comp.path && ((opts == null ? void 0 : opts.includeDynamicPages) || !isDynamicPagePath(comp.path))
913
+ );
914
+ });
915
+ }
916
+ fetchComponents() {
917
+ return __async(this, null, function* () {
918
+ this.maybeReportClientSideFetch(
919
+ () => `Daouy: fetching all component metadata in the browser`
920
+ );
921
+ const data = yield this.fetchAllData();
922
+ return data.components;
923
+ });
924
+ }
925
+ getActiveSplits() {
926
+ return this.bundle.activeSplits;
927
+ }
928
+ getChunksUrl(bundle, modules) {
929
+ return this.fetcher.getChunksUrl(bundle, modules);
930
+ }
931
+ fetchMissingData(opts) {
932
+ return __async(this, null, function* () {
933
+ this.maybeReportClientSideFetch(
934
+ () => `Daouy: fetching missing components in the browser: ${opts.missingSpecs.map((spec) => getLookupSpecName(spec)).join(", ")}`
935
+ );
936
+ return this.fetchAllData();
937
+ });
938
+ }
939
+ maybeReportClientSideFetch(mkMsg) {
940
+ if (isBrowser && this.opts.onClientSideFetch) {
941
+ const msg = mkMsg();
942
+ if (this.opts.onClientSideFetch === "warn") {
943
+ console.warn(msg);
944
+ } else {
945
+ throw new Error(msg);
946
+ }
947
+ }
948
+ }
949
+ fetchAllData() {
950
+ return __async(this, null, function* () {
951
+ var _a;
952
+ const bundle = yield this.fetcher.fetchAllData();
953
+ this.mergeBundle(bundle);
954
+ (_a = this.onBundleFetched) == null ? void 0 : _a.call(this);
955
+ return bundle;
956
+ });
957
+ }
958
+ mergeBundle(newBundle) {
959
+ var _a, _b;
960
+ newBundle.bundleKey = (_a = newBundle.bundleKey) != null ? _a : null;
961
+ if (newBundle.bundleKey && this.bundle.bundleKey && newBundle.bundleKey !== this.bundle.bundleKey) {
962
+ console.warn(
963
+ `Daouy Error: Different code export hashes. This can happen if your app is using different loaders with different project IDs or project versions.
964
+ Conflicting values:
965
+ ${newBundle.bundleKey}
966
+ ${this.bundle.bundleKey}`
967
+ );
968
+ }
969
+ this.bundle = mergeBundles(newBundle, this.bundle);
970
+ (_b = this.onBundleMerged) == null ? void 0 : _b.call(this);
971
+ }
972
+ getBundle() {
973
+ return this.bundle;
974
+ }
975
+ clearCache() {
976
+ this.bundle = {
977
+ modules: {
978
+ browser: [],
979
+ server: []
980
+ },
981
+ components: [],
982
+ globalGroups: [],
983
+ projects: [],
984
+ activeSplits: [],
985
+ bundleKey: null,
986
+ deferChunksByDefault: false,
987
+ disableRootLoadingBoundaryByDefault: false,
988
+ filteredIds: {}
989
+ };
990
+ this.registry.clear();
991
+ }
992
+ registerModules(modules) {
993
+ if (Object.keys(modules).some(
994
+ (name) => this.registry.getRegisteredModule(name) !== modules[name]
995
+ )) {
996
+ if (!this.registry.isEmpty()) {
997
+ console.warn(
998
+ "Calling DaouyComponentLoader.registerModules() after Daouy component has rendered; starting over."
999
+ );
1000
+ this.registry.clear();
1001
+ }
1002
+ for (const key of Object.keys(modules)) {
1003
+ this.registry.register(key, modules[key]);
1004
+ }
1005
+ }
1006
+ }
1007
+ substituteComponent(component, name) {
1008
+ this.internalSubstituteComponent(component, name, void 0);
1009
+ }
1010
+ internalSubstituteComponent(component, name, codeComponentHelpers) {
1011
+ if (!this.isRegistryEmpty()) {
1012
+ console.warn(
1013
+ "Calling DaouyComponentLoader.registerSubstitution() after Daouy component has rendered; starting over."
1014
+ );
1015
+ this.clearRegistry();
1016
+ }
1017
+ this.subs.push({ lookup: name, component, codeComponentHelpers });
1018
+ }
1019
+ refreshRegistry() {
1020
+ for (const sub of this.subs) {
1021
+ const metas = getCompMetas(this.getBundle().components, sub.lookup);
1022
+ metas.forEach((meta) => {
1023
+ SUBSTITUTED_COMPONENTS[meta.id] = sub.component;
1024
+ if (sub.codeComponentHelpers) {
1025
+ REGISTERED_CODE_COMPONENT_HELPERS[meta.id] = sub.codeComponentHelpers;
1026
+ }
1027
+ });
1028
+ }
1029
+ this.registry.updateModules(this.getBundle());
1030
+ }
1031
+ isRegistryEmpty() {
1032
+ return this.registry.isEmpty();
1033
+ }
1034
+ clearRegistry() {
1035
+ this.registry.clear();
1036
+ }
1037
+ setGlobalVariants(globalVariants) {
1038
+ this.globalVariants = globalVariants;
1039
+ }
1040
+ getGlobalVariants() {
1041
+ return this.globalVariants;
1042
+ }
1043
+ registerPrefetchedBundle(bundle) {
1044
+ if (!isBrowser) {
1045
+ const cachedBundle = (0, import_loader_fetcher.internal_getCachedBundleInNodeServer)(this.opts);
1046
+ if (cachedBundle) {
1047
+ this.mergeBundle(cachedBundle);
1048
+ }
1049
+ }
1050
+ this.mergeBundle(bundle);
1051
+ }
1052
+ getLookup() {
1053
+ return new ComponentLookup(this.getBundle(), this.registry);
1054
+ }
1055
+ trackConversion(_value = 0) {
1056
+ }
1057
+ getActiveVariation(opts) {
1058
+ return __async(this, null, function* () {
1059
+ yield this.fetchComponents();
1060
+ return (0, import_loader_splits.getActiveVariation)(__spreadProps(__spreadValues({}, opts), {
1061
+ splits: this.getBundle().activeSplits
1062
+ }));
1063
+ });
1064
+ }
1065
+ getTeamIds() {
1066
+ return uniq(
1067
+ this.getBundle().projects.map(
1068
+ (p) => p.teamId ? `${p.teamId}${p.indirect ? "@indirect" : ""}` : null
1069
+ ).filter((x) => !!x)
1070
+ );
1071
+ }
1072
+ getProjectIds() {
1073
+ return uniq(
1074
+ this.getBundle().projects.map(
1075
+ (p) => `${p.id}${p.indirect ? "@indirect" : ""}`
1076
+ )
1077
+ );
1078
+ }
1079
+ trackRender(_opts) {
1080
+ }
1081
+ loadServerQueriesModule(fileName) {
1082
+ return this.registry.load(fileName);
1083
+ }
1084
+ };
1085
+ var DaouyComponentLoader = class {
1086
+ constructor(internal) {
1087
+ this.warnedRegisterComponent = false;
1088
+ this.__internal = internal;
1089
+ }
1090
+ /**
1091
+ * Sets global variants to be used for all components. Note that
1092
+ * this is not reactive, and will not re-render all components
1093
+ * already mounted; instead, it should be used to activate global
1094
+ * variants that should always be activated for the lifetime of this
1095
+ * app. If you'd like to reactively change the global variants,
1096
+ * you should specify them via <DaouyRootProvider />
1097
+ */
1098
+ setGlobalVariants(globalVariants) {
1099
+ this.__internal.setGlobalVariants(globalVariants);
1100
+ }
1101
+ registerModules(modules) {
1102
+ this.__internal.registerModules(modules);
1103
+ }
1104
+ /**
1105
+ * Register custom components that should be swapped in for
1106
+ * components defined in your project. You can use this to
1107
+ * swap in / substitute a Daouy component with a "real" component.
1108
+ */
1109
+ substituteComponent(component, name) {
1110
+ this.__internal.substituteComponent(component, name);
1111
+ }
1112
+ registerComponent(component, metaOrName) {
1113
+ if (metaOrName && typeof metaOrName === "object" && "props" in metaOrName) {
1114
+ this.__internal.registerComponent(component, metaOrName);
1115
+ } else {
1116
+ if (process.env.NODE_ENV === "development" && !this.warnedRegisterComponent) {
1117
+ console.warn(
1118
+ `DaouyLoader: Using deprecated method \`registerComponent\` for component substitution. Please consider using \`substituteComponent\` instead.`
1119
+ );
1120
+ this.warnedRegisterComponent = true;
1121
+ }
1122
+ this.substituteComponent(component, metaOrName);
1123
+ }
1124
+ }
1125
+ registerFunction(fn, meta) {
1126
+ this.__internal.registerFunction(fn, meta);
1127
+ }
1128
+ registerGlobalContext(context, meta) {
1129
+ this.__internal.registerGlobalContext(context, meta);
1130
+ }
1131
+ registerTrait(trait, meta) {
1132
+ this.__internal.registerTrait(trait, meta);
1133
+ }
1134
+ registerToken(token) {
1135
+ this.__internal.registerToken(token);
1136
+ }
1137
+ fetchComponentData(...args) {
1138
+ return this.__internal.fetchComponentData(...args);
1139
+ }
1140
+ maybeFetchComponentData(...args) {
1141
+ return __async(this, null, function* () {
1142
+ return this.__internal.maybeFetchComponentData(...args);
1143
+ });
1144
+ }
1145
+ /**
1146
+ * Returns all the page component metadata for these projects.
1147
+ */
1148
+ fetchPages(opts) {
1149
+ return __async(this, null, function* () {
1150
+ return this.__internal.fetchPages(opts);
1151
+ });
1152
+ }
1153
+ /**
1154
+ * Returns all components metadata for these projects.
1155
+ */
1156
+ fetchComponents() {
1157
+ return __async(this, null, function* () {
1158
+ return this.__internal.fetchComponents();
1159
+ });
1160
+ }
1161
+ _getActiveVariation(opts) {
1162
+ return __async(this, null, function* () {
1163
+ return this.__internal.getActiveVariation(opts);
1164
+ });
1165
+ }
1166
+ getActiveVariation(opts) {
1167
+ return __async(this, null, function* () {
1168
+ return this._getActiveVariation({
1169
+ traits: opts.traits,
1170
+ getKnownValue: (key) => {
1171
+ if (opts.known) {
1172
+ return opts.known[key];
1173
+ } else {
1174
+ const cookies = getDaouyCookieValues();
1175
+ return cookies[key];
1176
+ }
1177
+ },
1178
+ updateKnownValue: (key, value) => {
1179
+ if (!opts.known) {
1180
+ updateDaouyCookieValue(key, value);
1181
+ }
1182
+ }
1183
+ });
1184
+ });
1185
+ }
1186
+ getChunksUrl(bundle, modules) {
1187
+ return this.__internal.getChunksUrl(bundle, modules);
1188
+ }
1189
+ getExternalVariation(variation, filters) {
1190
+ return (0, import_loader_splits.getExternalIds)(this.getActiveSplits(), variation, filters);
1191
+ }
1192
+ getActiveSplits() {
1193
+ return this.__internal.getActiveSplits();
1194
+ }
1195
+ trackConversion(value = 0) {
1196
+ this.__internal.trackConversion(value);
1197
+ }
1198
+ clearCache() {
1199
+ return this.__internal.clearCache();
1200
+ }
1201
+ getExecFuncModule(renderData, fileNameKey) {
1202
+ if (renderData.entryCompMetas.length === 0) {
1203
+ return void 0;
1204
+ }
1205
+ const fileName = renderData.entryCompMetas[0][fileNameKey];
1206
+ if (!fileName) {
1207
+ return void 0;
1208
+ }
1209
+ return this.__internal.loadServerQueriesModule(fileName);
1210
+ }
1211
+ unstable__getServerQueriesData(renderData, $ctx) {
1212
+ return __async(this, null, function* () {
1213
+ const module2 = this.getExecFuncModule(
1214
+ renderData,
1215
+ "serverQueriesExecFuncFileName"
1216
+ );
1217
+ try {
1218
+ const $serverQueries = yield module2 == null ? void 0 : module2.executeServerQueries($ctx);
1219
+ return $serverQueries;
1220
+ } catch (err) {
1221
+ console.error("Error executing server queries function", err);
1222
+ return {};
1223
+ }
1224
+ });
1225
+ }
1226
+ unstable__generateMetadata(renderData, props) {
1227
+ return __async(this, null, function* () {
1228
+ var _a;
1229
+ const module2 = this.getExecFuncModule(
1230
+ renderData,
1231
+ "generateMetadataFuncFileName"
1232
+ );
1233
+ const fallback = ((_a = renderData.entryCompMetas[0]) == null ? void 0 : _a.pageMetadata) || {};
1234
+ if (!module2) {
1235
+ return fallback;
1236
+ }
1237
+ try {
1238
+ const metadata = yield module2.generateMetadata(props);
1239
+ return metadata;
1240
+ } catch (err) {
1241
+ return fallback;
1242
+ }
1243
+ });
1244
+ }
1245
+ };
1246
+
1247
+ // src/loader-client.ts
1248
+ var InternalDaouyComponentLoader = class extends BaseInternalDaouyComponentLoader {
1249
+ constructor(opts) {
1250
+ super({
1251
+ opts,
1252
+ fetcher: new import_loader_core3.DaouyModulesFetcher(opts),
1253
+ onBundleMerged: () => {
1254
+ this.refreshRegistry();
1255
+ },
1256
+ onBundleFetched: () => {
1257
+ this.roots.forEach((watcher) => {
1258
+ var _a;
1259
+ return (_a = watcher.onDataFetched) == null ? void 0 : _a.call(watcher);
1260
+ });
1261
+ },
1262
+ builtinModules: {
1263
+ react: import_react.default,
1264
+ "react-dom": import_react_dom.default,
1265
+ "react/jsx-runtime": jsxRuntime,
1266
+ "react/jsx-dev-runtime": jsxDevRuntime,
1267
+ // Also inject @daouy/query and @daouy/host to use the
1268
+ // same contexts here and in loader-downloaded code.
1269
+ "@daouy/query": DaouyQuery,
1270
+ "@daouy/data-sources-context": DaouyDataSourcesContext,
1271
+ "@daouy/host": DaouyHost,
1272
+ "@daouy/loader-runtime-registry": {
1273
+ components: SUBSTITUTED_COMPONENTS,
1274
+ globalVariantHooks: SUBSTITUTED_GLOBAL_VARIANT_HOOKS,
1275
+ codeComponentHelpers: REGISTERED_CODE_COMPONENT_HELPERS,
1276
+ functions: REGISTERED_CUSTOM_FUNCTIONS
1277
+ }
1278
+ }
1279
+ });
1280
+ this.roots = [];
1281
+ }
1282
+ registerComponent(component, meta) {
1283
+ var _a, _b;
1284
+ const stateHelpers = Object.fromEntries(
1285
+ Object.entries((_a = meta.states) != null ? _a : {}).filter(
1286
+ ([_, stateSpec]) => Object.keys(stateSpec).some((key) => import_host2.stateHelpersKeys.includes(key))
1287
+ ).map(([stateName, stateSpec]) => [
1288
+ stateName,
1289
+ Object.fromEntries(
1290
+ import_host2.stateHelpersKeys.filter((key) => key in stateSpec).map((key) => [key, stateSpec[key]])
1291
+ )
1292
+ ])
1293
+ );
1294
+ const helpers = { states: stateHelpers };
1295
+ this.internalSubstituteComponent(
1296
+ component,
1297
+ { name: meta.name, isCode: true },
1298
+ Object.keys(stateHelpers).length > 0 ? helpers : void 0
1299
+ );
1300
+ (0, import_host2.registerComponent)(component, __spreadValues(__spreadProps(__spreadValues({}, meta), {
1301
+ // Import path is not used as we will use component substitution
1302
+ importPath: (_b = meta.importPath) != null ? _b : ""
1303
+ }), Object.keys(stateHelpers).length > 0 ? {
1304
+ componentHelpers: {
1305
+ helpers,
1306
+ importPath: "",
1307
+ importName: ""
1308
+ }
1309
+ } : {}));
1310
+ }
1311
+ registerFunction(fn, meta) {
1312
+ var _a;
1313
+ (0, import_host2.registerFunction)(fn, __spreadProps(__spreadValues({}, meta), {
1314
+ importPath: (_a = meta.importPath) != null ? _a : ""
1315
+ }));
1316
+ internalSetRegisteredFunction(fn, meta);
1317
+ }
1318
+ registerGlobalContext(context, meta) {
1319
+ var _a;
1320
+ this.substituteComponent(context, { name: meta.name, isCode: true });
1321
+ (0, import_host2.registerGlobalContext)(context, __spreadProps(__spreadValues({}, meta), {
1322
+ importPath: (_a = meta.importPath) != null ? _a : ""
1323
+ }));
1324
+ }
1325
+ registerTrait(trait, meta) {
1326
+ (0, import_host2.registerTrait)(trait, meta);
1327
+ }
1328
+ registerToken(token) {
1329
+ (0, import_host2.registerToken)(token);
1330
+ }
1331
+ subscribeDaouyRoot(watcher) {
1332
+ this.roots.push(watcher);
1333
+ }
1334
+ unsubscribeDaouyRoot(watcher) {
1335
+ const index = this.roots.indexOf(watcher);
1336
+ if (index >= 0) {
1337
+ this.roots.splice(index, 1);
1338
+ }
1339
+ }
1340
+ refreshRegistry() {
1341
+ for (const globalGroup of this.getBundle().globalGroups) {
1342
+ if (globalGroup.type !== "global-screen") {
1343
+ SUBSTITUTED_GLOBAL_VARIANT_HOOKS[globalGroup.id] = createUseGlobalVariant(globalGroup.name, globalGroup.projectId);
1344
+ }
1345
+ }
1346
+ super.refreshRegistry();
1347
+ }
1348
+ };
1349
+
1350
+ // src/index.ts
1351
+ var import_host3 = require("@daouy/host");
1352
+ var import_query2 = require("@daouy/query");
1353
+
1354
+ // src/PlasmicComponent.tsx
1355
+ var React5 = __toESM(require("react"));
1356
+
1357
+ // src/usePlasmicComponent.tsx
1358
+ var React4 = __toESM(require("react"));
1359
+ function useDaouyComponent(spec, opts = {}) {
1360
+ const rootContext = useDaouyRootContext();
1361
+ if (!rootContext) {
1362
+ throw new Error(
1363
+ `You can only use useDaouyComponent if wrapped in <DaouyRootProvider />`
1364
+ );
1365
+ }
1366
+ const loader = rootContext.loader;
1367
+ const lookup = loader.getLookup();
1368
+ const component = lookup.hasComponent(spec) ? lookup.getComponent(spec, opts) : void 0;
1369
+ const stableSpec = useStableLookupSpec(spec);
1370
+ const isMounted = useIsMounted();
1371
+ const forceUpdate = useForceUpdate();
1372
+ React4.useEffect(() => {
1373
+ if (!component) {
1374
+ (() => __async(this, null, function* () {
1375
+ yield loader.fetchComponentData(stableSpec);
1376
+ if (isMounted()) {
1377
+ forceUpdate();
1378
+ }
1379
+ }))();
1380
+ }
1381
+ }, [component, stableSpec]);
1382
+ return component;
1383
+ }
1384
+
1385
+ // src/PlasmicComponent.tsx
1386
+ var DaouyComponentContext = React5.createContext(false);
1387
+ function DaouyComponent(props) {
1388
+ const { component, projectId, componentProps, forceOriginal } = props;
1389
+ const rootContext = useDaouyRootContext();
1390
+ const isRootLoader = !React5.useContext(DaouyComponentContext);
1391
+ if (!rootContext) {
1392
+ throw new Error(
1393
+ `You must use <DaouyRootProvider/> at the root of your app`
1394
+ );
1395
+ }
1396
+ const _a = rootContext, {
1397
+ loader,
1398
+ globalContextsProps,
1399
+ variation,
1400
+ userAuthToken,
1401
+ isUserLoading,
1402
+ authRedirectUri,
1403
+ translator
1404
+ } = _a, rest = __objRest(_a, [
1405
+ "loader",
1406
+ "globalContextsProps",
1407
+ "variation",
1408
+ "userAuthToken",
1409
+ "isUserLoading",
1410
+ "authRedirectUri",
1411
+ "translator"
1412
+ ]);
1413
+ const Component = useDaouyComponent(
1414
+ { name: component, projectId, isCode: false },
1415
+ { forceOriginal }
1416
+ );
1417
+ React5.useEffect(() => {
1418
+ if (isRootLoader) {
1419
+ const meta = loader.getLookup().getComponentMeta({ name: component, projectId });
1420
+ if (meta) {
1421
+ loader.trackRender({
1422
+ renderCtx: {
1423
+ rootProjectId: meta.projectId,
1424
+ rootComponentId: meta.id,
1425
+ rootComponentName: component,
1426
+ teamIds: loader.getTeamIds(),
1427
+ projectIds: loader.getProjectIds()
1428
+ },
1429
+ variation
1430
+ });
1431
+ }
1432
+ }
1433
+ }, [component, projectId, loader, variation]);
1434
+ const element = React5.useMemo(() => {
1435
+ var _a2;
1436
+ if (!Component) {
1437
+ return null;
1438
+ }
1439
+ let elt = /* @__PURE__ */ React5.createElement(Component, __spreadValues({}, componentProps));
1440
+ if (isRootLoader) {
1441
+ const lookup = loader.getLookup();
1442
+ const ReactWebRootProvider = lookup.getRootProvider();
1443
+ const StyleTokensProvider = lookup.maybeGetStyleTokensProvider(
1444
+ {
1445
+ name: component,
1446
+ projectId
1447
+ },
1448
+ rootContext.styleTokenOverridesProjectId
1449
+ );
1450
+ const GlobalContextsProvider = lookup.getGlobalContextsProvider({
1451
+ name: component,
1452
+ projectId
1453
+ });
1454
+ elt = /* @__PURE__ */ React5.createElement(
1455
+ ReactWebRootProvider,
1456
+ __spreadProps(__spreadValues({}, rest), {
1457
+ userAuthToken,
1458
+ isUserLoading,
1459
+ authRedirectUri,
1460
+ i18n: {
1461
+ translator,
1462
+ tagPrefix: (_a2 = loader.opts.i18n) == null ? void 0 : _a2.tagPrefix
1463
+ }
1464
+ }),
1465
+ /* @__PURE__ */ React5.createElement(
1466
+ MaybeWrap,
1467
+ {
1468
+ cond: !!GlobalContextsProvider,
1469
+ wrapper: (children) => /* @__PURE__ */ React5.createElement(GlobalContextsProvider, __spreadValues({}, globalContextsProps), children)
1470
+ },
1471
+ /* @__PURE__ */ React5.createElement(
1472
+ MaybeWrap,
1473
+ {
1474
+ cond: !!StyleTokensProvider,
1475
+ wrapper: (children) => /* @__PURE__ */ React5.createElement(StyleTokensProvider, null, children)
1476
+ },
1477
+ /* @__PURE__ */ React5.createElement(DaouyComponentContext.Provider, { value: true }, elt)
1478
+ )
1479
+ )
1480
+ );
1481
+ }
1482
+ return elt;
1483
+ }, [
1484
+ Component,
1485
+ componentProps,
1486
+ loader,
1487
+ isRootLoader,
1488
+ component,
1489
+ projectId,
1490
+ globalContextsProps,
1491
+ userAuthToken,
1492
+ // Just use the token to memo, `user` should be derived from it
1493
+ isUserLoading,
1494
+ authRedirectUri
1495
+ ]);
1496
+ return element;
1497
+ }
1498
+
1499
+ // src/prepass-client.ts
1500
+ var import_prepass = require("@daouy/prepass");
1501
+ function extractDaouyQueryData(element) {
1502
+ return (0, import_prepass.extractDaouyQueryData)(element);
1503
+ }
1504
+ function daouyPrepass(element) {
1505
+ return (0, import_prepass.daouyPrepass)(element);
1506
+ }
1507
+
1508
+ // src/render.tsx
1509
+ var import_prepass2 = require("@daouy/prepass");
1510
+ var import_react2 = __toESM(require("react"));
1511
+ var import_react_dom2 = __toESM(require("react-dom"));
1512
+ var import_server = require("react-dom/server");
1513
+ function renderToElement(_0, _1, _2) {
1514
+ return __async(this, arguments, function* (loader, target, lookup, opts = {}) {
1515
+ return new Promise((resolve) => {
1516
+ const element = makeElement(loader, lookup, opts);
1517
+ import_react_dom2.default.render(element, target, () => resolve());
1518
+ });
1519
+ });
1520
+ }
1521
+ function renderToString(loader, lookup, opts = {}) {
1522
+ const element = makeElement(loader, lookup, opts);
1523
+ return (0, import_server.renderToString)(element);
1524
+ }
1525
+ function extractDaouyQueryDataFromElement(_0, _1) {
1526
+ return __async(this, arguments, function* (loader, lookup, opts = {}) {
1527
+ const element = makeElement(loader, lookup, opts);
1528
+ return (0, import_prepass2.extractDaouyQueryData)(element);
1529
+ });
1530
+ }
1531
+ function hydrateFromElement(_0, _1, _2) {
1532
+ return __async(this, arguments, function* (loader, target, lookup, opts = {}) {
1533
+ return new Promise((resolve) => {
1534
+ const element = makeElement(loader, lookup, opts);
1535
+ import_react_dom2.default.hydrate(element, target, () => resolve());
1536
+ });
1537
+ });
1538
+ }
1539
+ function makeElement(loader, lookup, opts = {}) {
1540
+ return /* @__PURE__ */ import_react2.default.createElement(
1541
+ DaouyRootProvider,
1542
+ {
1543
+ loader,
1544
+ prefetchedData: opts.prefetchedData,
1545
+ globalVariants: opts.globalVariants,
1546
+ prefetchedQueryData: opts.prefetchedQueryData,
1547
+ pageParams: opts.pageParams,
1548
+ pageQuery: opts.pageQuery
1549
+ },
1550
+ /* @__PURE__ */ import_react2.default.createElement(
1551
+ DaouyComponent,
1552
+ {
1553
+ component: typeof lookup === "string" ? lookup : lookup.name,
1554
+ projectId: typeof lookup === "string" ? void 0 : lookup.projectId,
1555
+ componentProps: opts.componentProps
1556
+ }
1557
+ )
1558
+ );
1559
+ }
1560
+
1561
+ // src/index.ts
1562
+ function initDaouyLoader(opts) {
1563
+ const internal = new InternalDaouyComponentLoader(opts);
1564
+ return new DaouyComponentLoader(internal);
1565
+ }
1566
+ //# sourceMappingURL=index.js.map