@plasmicapp/loader-react 1.0.38 → 1.0.39-6.beta

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