@plasmicapp/loader-react 1.0.253 → 1.0.255

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