@plasmicapp/loader-nextjs 1.0.321 → 1.0.323

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cache.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { InitOptions } from '@plasmicapp/loader-react/react-server-conditional';
1
+ import type { InitOptions } from "@plasmicapp/loader-react/react-server-conditional";
2
+ import type { NextInitOptions } from "./shared-exports";
2
3
  export declare function initPlasmicLoaderWithCache<T extends {
3
4
  clearCache(): void;
4
- }>(initFn: (opts: InitOptions) => T, opts: InitOptions): T;
5
+ }>(initFn: (opts: InitOptions) => T, { nextNavigation, ...opts }: NextInitOptions): T;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /// <reference types="node" />
2
- import { InitOptions, InternalPlasmicComponentLoader, PlasmicComponentLoader, PlasmicRootProvider as CommonPlasmicRootProvider } from "@plasmicapp/loader-react";
2
+ import { InternalPlasmicComponentLoader, PlasmicComponentLoader, PlasmicRootProvider as CommonPlasmicRootProvider } from "@plasmicapp/loader-react";
3
3
  import { IncomingMessage, ServerResponse } from "http";
4
4
  import * as React from "react";
5
+ import type { NextInitOptions } from "./shared-exports";
5
6
  export { DataCtxReader, DataProvider, extractPlasmicQueryData, PageParamsProvider, PlasmicCanvasContext, PlasmicCanvasHost, PlasmicComponent, plasmicPrepass, repeatedElement, useDataEnv, usePlasmicCanvasContext, usePlasmicComponent, usePlasmicQueryData, useSelector, useSelectors, } from "@plasmicapp/loader-react";
6
7
  export type { CodeComponentMeta, PlasmicTranslator, PropType, TokenRegistration, } from "@plasmicapp/loader-react";
7
8
  export * from "./shared-exports";
@@ -19,5 +20,5 @@ export declare class NextJsPlasmicComponentLoader extends PlasmicComponentLoader
19
20
  traits: Record<string, string | number | boolean>;
20
21
  }): Promise<Record<string, string>>;
21
22
  }
22
- export declare function initPlasmicLoader(opts: InitOptions): NextJsPlasmicComponentLoader;
23
+ export declare function initPlasmicLoader(opts: NextInitOptions): NextJsPlasmicComponentLoader;
23
24
  export declare function PlasmicRootProvider(props: Omit<React.ComponentProps<typeof CommonPlasmicRootProvider>, "Head">): React.JSX.Element;
@@ -0,0 +1,363 @@
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/index.tsx
55
+ import {
56
+ InternalPlasmicComponentLoader,
57
+ PlasmicComponentLoader,
58
+ PlasmicRootProvider as CommonPlasmicRootProvider
59
+ } from "@plasmicapp/loader-react";
60
+ import NextHead from "next/head.js";
61
+ import NextLink from "next/link.js";
62
+ import * as NextRouter from "next/router.js";
63
+ import * as React from "react";
64
+
65
+ // src/cache.ts
66
+ import path from "path";
67
+
68
+ // src/server-require.ts
69
+ var secretRequire;
70
+ try {
71
+ secretRequire = eval("require");
72
+ } catch (err) {
73
+ try {
74
+ secretRequire = eval("(module) => import(module)");
75
+ } catch (err2) {
76
+ secretRequire = void 0;
77
+ }
78
+ }
79
+ function serverRequire(module) {
80
+ return __async(this, null, function* () {
81
+ if (!secretRequire) {
82
+ throw new Error(
83
+ `Unexpected serverRequire() -- can only do this from a Node server!`
84
+ );
85
+ }
86
+ return secretRequire(module);
87
+ });
88
+ }
89
+ function serverRequireFs() {
90
+ return __async(this, null, function* () {
91
+ return serverRequire("fs");
92
+ });
93
+ }
94
+
95
+ // src/cache.ts
96
+ var FileCache = class {
97
+ constructor(filePath) {
98
+ this.filePath = filePath;
99
+ }
100
+ get() {
101
+ return __async(this, null, function* () {
102
+ const fs = yield serverRequireFs();
103
+ try {
104
+ yield fs.promises.mkdir(path.dirname(this.filePath), { recursive: true });
105
+ const data = (yield fs.promises.readFile(this.filePath)).toString();
106
+ return JSON.parse(data);
107
+ } catch (e) {
108
+ return void 0;
109
+ }
110
+ });
111
+ }
112
+ set(data) {
113
+ return __async(this, null, function* () {
114
+ const fs = yield serverRequireFs();
115
+ try {
116
+ yield fs.promises.writeFile(this.filePath, JSON.stringify(data));
117
+ } catch (err2) {
118
+ console.warn(`Error writing to Plasmic cache: ${err2}`);
119
+ }
120
+ });
121
+ }
122
+ clear() {
123
+ return __async(this, null, function* () {
124
+ const fs = yield serverRequireFs();
125
+ try {
126
+ fs.promises.unlink(this.filePath);
127
+ } catch (err2) {
128
+ }
129
+ });
130
+ }
131
+ };
132
+ function makeCache(opts) {
133
+ const cacheDir = path.resolve(process.cwd(), ".next", ".plasmic");
134
+ const cachePath = path.join(
135
+ cacheDir,
136
+ `plasmic-${[...opts.projects.map((p) => {
137
+ var _a;
138
+ return `${p.id}@${(_a = p.version) != null ? _a : ""}`;
139
+ })].sort().join("-")}${opts.preview ? "-preview" : ""}-cache.json`
140
+ );
141
+ return new FileCache(cachePath);
142
+ }
143
+ function initPlasmicLoaderWithCache(initFn, _a) {
144
+ var _b = _a, { nextNavigation } = _b, opts = __objRest(_b, ["nextNavigation"]);
145
+ const isBrowser = typeof window !== "undefined";
146
+ const isProd = process.env.NODE_ENV === "production";
147
+ const cache = isBrowser || isProd ? void 0 : makeCache(opts);
148
+ const loader = initFn(__spreadProps(__spreadValues({
149
+ onClientSideFetch: "warn"
150
+ }, opts), {
151
+ cache,
152
+ platform: "nextjs",
153
+ platformOptions: {
154
+ nextjs: {
155
+ appDir: !!nextNavigation
156
+ }
157
+ },
158
+ // For Nextjs 12, revalidate may in fact re-use an existing instance
159
+ // of PlasmicComponentLoader that's already in memory, so we need to
160
+ // make sure we don't re-use the data cached in memory.
161
+ // We also enforce this for dev mode, so that we don't have to restart
162
+ // the dev server, in case getStaticProps() re-uses the same PlasmicComponentLoader
163
+ alwaysFresh: !isBrowser
164
+ }));
165
+ if (!isProd) {
166
+ const stringOpts = JSON.stringify(opts);
167
+ if (process.env.PLASMIC_OPTS && process.env.PLASMIC_OPTS !== stringOpts) {
168
+ console.warn(
169
+ `PLASMIC: We detected that you created a new PlasmicLoader with different configurations. You may need to restart your dev server.
170
+ `
171
+ );
172
+ }
173
+ process.env.PLASMIC_OPTS = stringOpts;
174
+ }
175
+ if (cache) {
176
+ if (!isProd) {
177
+ if (process.env.PLASMIC_WATCHED !== "true") {
178
+ (() => __async(this, null, function* () {
179
+ process.env.PLASMIC_WATCHED = "true";
180
+ console.log(`Subscribing to Plasmic changes...`);
181
+ try {
182
+ const PlasmicRemoteChangeWatcher = (yield serverRequire("@plasmicapp/watcher")).PlasmicRemoteChangeWatcher;
183
+ const watcher = new PlasmicRemoteChangeWatcher({
184
+ projects: opts.projects,
185
+ host: opts.host
186
+ });
187
+ const clearCache = () => {
188
+ cache.clear();
189
+ loader.clearCache();
190
+ };
191
+ watcher.subscribe({
192
+ onUpdate: () => {
193
+ if (opts.preview) {
194
+ clearCache();
195
+ }
196
+ },
197
+ onPublish: () => {
198
+ if (!opts.preview) {
199
+ clearCache();
200
+ }
201
+ }
202
+ });
203
+ } catch (e) {
204
+ console.warn("Couldn't subscribe to Plasmic changes", e);
205
+ }
206
+ }))();
207
+ }
208
+ } else {
209
+ cache.clear();
210
+ loader.clearCache();
211
+ }
212
+ }
213
+ return loader;
214
+ }
215
+
216
+ // src/index.tsx
217
+ import {
218
+ DataCtxReader,
219
+ DataProvider,
220
+ extractPlasmicQueryData,
221
+ PageParamsProvider,
222
+ PlasmicCanvasContext,
223
+ PlasmicCanvasHost,
224
+ PlasmicComponent,
225
+ plasmicPrepass,
226
+ repeatedElement,
227
+ useDataEnv,
228
+ usePlasmicCanvasContext,
229
+ usePlasmicComponent,
230
+ usePlasmicQueryData,
231
+ useSelector,
232
+ useSelectors
233
+ } from "@plasmicapp/loader-react";
234
+ var NextJsPlasmicComponentLoader = class extends PlasmicComponentLoader {
235
+ constructor(internal) {
236
+ super(internal);
237
+ }
238
+ getActiveVariation(opts) {
239
+ return __async(this, null, function* () {
240
+ const extractBuiltinTraits = () => {
241
+ var _a, _b, _c, _d;
242
+ const url = new URL(
243
+ (_b = (_a = opts.req) == null ? void 0 : _a.url) != null ? _b : "/",
244
+ `https://${(_d = (_c = opts.req) == null ? void 0 : _c.headers.host) != null ? _d : "server.side"}`
245
+ );
246
+ return {
247
+ pageUrl: url.href
248
+ };
249
+ };
250
+ return this._getActiveVariation({
251
+ traits: __spreadValues(__spreadValues({}, extractBuiltinTraits()), opts.traits),
252
+ getKnownValue: (key) => {
253
+ var _a, _b;
254
+ if (opts.known) {
255
+ return opts.known[key];
256
+ } else {
257
+ return (_b = (_a = opts.req) == null ? void 0 : _a.cookies[`plasmic:${key}`]) != null ? _b : void 0;
258
+ }
259
+ },
260
+ updateKnownValue: (key, value) => {
261
+ var _a, _b, _c;
262
+ if (opts.res) {
263
+ const cookie = `plasmic:${key}=${value}`;
264
+ const resCookie = (_b = (_a = opts.res) == null ? void 0 : _a.getHeader("Set-Cookie")) != null ? _b : [];
265
+ let newCookies = [];
266
+ if (Array.isArray(resCookie)) {
267
+ newCookies = [...resCookie, `plasmic:${key}=${value}`];
268
+ } else {
269
+ newCookies = [`${resCookie}`, cookie];
270
+ }
271
+ (_c = opts.res) == null ? void 0 : _c.setHeader("Set-Cookie", newCookies);
272
+ }
273
+ }
274
+ });
275
+ });
276
+ }
277
+ };
278
+ function initPlasmicLoader(opts) {
279
+ const loader = initPlasmicLoaderWithCache(
280
+ (opts2) => new NextJsPlasmicComponentLoader(
281
+ new InternalPlasmicComponentLoader(opts2)
282
+ ),
283
+ opts
284
+ );
285
+ loader.registerModules({
286
+ "next/head": NextHead,
287
+ "next/link": NextLink,
288
+ "next/router": NextRouter
289
+ });
290
+ if (opts.nextNavigation) {
291
+ loader.registerModules({
292
+ "next/navigation": opts.nextNavigation
293
+ });
294
+ }
295
+ return loader;
296
+ }
297
+ var PlasmicNextLink = React.forwardRef(function PlasmicNextLink2(props, ref) {
298
+ if (props.href) {
299
+ const _a = props, {
300
+ href,
301
+ replace,
302
+ scroll,
303
+ shallow,
304
+ passHref,
305
+ prefetch,
306
+ locale
307
+ } = _a, rest = __objRest(_a, [
308
+ "href",
309
+ "replace",
310
+ "scroll",
311
+ "shallow",
312
+ "passHref",
313
+ "prefetch",
314
+ "locale"
315
+ ]);
316
+ const isFragment = typeof href === "string" && href.startsWith("#");
317
+ return /* @__PURE__ */ React.createElement(
318
+ NextLink,
319
+ __spreadValues({
320
+ href,
321
+ replace,
322
+ scroll: scroll != null ? scroll : isFragment ? false : void 0,
323
+ shallow,
324
+ passHref,
325
+ prefetch,
326
+ locale
327
+ }, { legacyBehavior: true }),
328
+ /* @__PURE__ */ React.createElement("a", __spreadProps(__spreadValues({}, rest), { ref }))
329
+ );
330
+ } else {
331
+ return /* @__PURE__ */ React.createElement("a", __spreadProps(__spreadValues({}, props), { href: void 0, ref }));
332
+ }
333
+ });
334
+ function PlasmicRootProvider(props) {
335
+ return /* @__PURE__ */ React.createElement(
336
+ CommonPlasmicRootProvider,
337
+ __spreadValues({
338
+ Head: NextHead,
339
+ Link: PlasmicNextLink
340
+ }, props)
341
+ );
342
+ }
343
+ export {
344
+ DataCtxReader,
345
+ DataProvider,
346
+ NextJsPlasmicComponentLoader,
347
+ PageParamsProvider,
348
+ PlasmicCanvasContext,
349
+ PlasmicCanvasHost,
350
+ PlasmicComponent,
351
+ PlasmicRootProvider,
352
+ extractPlasmicQueryData,
353
+ initPlasmicLoader,
354
+ plasmicPrepass,
355
+ repeatedElement,
356
+ useDataEnv,
357
+ usePlasmicCanvasContext,
358
+ usePlasmicComponent,
359
+ usePlasmicQueryData,
360
+ useSelector,
361
+ useSelectors
362
+ };
363
+ //# sourceMappingURL=index.esm.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.tsx", "../src/cache.ts", "../src/server-require.ts"],
4
+ "sourcesContent": ["import {\n InternalPlasmicComponentLoader,\n PlasmicComponentLoader,\n PlasmicRootProvider as CommonPlasmicRootProvider,\n} from \"@plasmicapp/loader-react\";\nimport { IncomingMessage, ServerResponse } from \"http\";\n// NextHead and NextLink must be default imported (`import Pkg`) instead of a namespace import (`import * as Pkg`).\n// Otherwise, there's a Next.js 12 bug when referencing these dependencies due to default import interop.\n// The transpiled CommonJS code would create a `default` field on the package,\n// causing React to think it's an invalid React object:\n// ```\n// const NextHead = __defaultInterop(require('next/head.js'))\n// assert(typeof NextHead === 'object')\n// assert(typeof NextHead.default === 'function')\n// ```\nimport NextHead from \"next/head.js\";\nimport NextLink from \"next/link.js\";\nimport * as NextRouter from \"next/router.js\";\nimport * as React from \"react\";\nimport { initPlasmicLoaderWithCache } from \"./cache\";\nimport type { NextInitOptions } from \"./shared-exports\";\n\nexport {\n DataCtxReader,\n DataProvider,\n extractPlasmicQueryData,\n PageParamsProvider,\n PlasmicCanvasContext,\n PlasmicCanvasHost,\n PlasmicComponent,\n plasmicPrepass,\n repeatedElement,\n useDataEnv,\n usePlasmicCanvasContext,\n usePlasmicComponent,\n usePlasmicQueryData,\n useSelector,\n useSelectors,\n} from \"@plasmicapp/loader-react\";\nexport type {\n CodeComponentMeta,\n PlasmicTranslator,\n PropType,\n TokenRegistration,\n} from \"@plasmicapp/loader-react\";\nexport * from \"./shared-exports\";\n\ntype ServerRequest = IncomingMessage & {\n cookies: {\n [key: string]: string;\n };\n};\nexport class NextJsPlasmicComponentLoader extends PlasmicComponentLoader {\n constructor(internal: InternalPlasmicComponentLoader) {\n super(internal);\n }\n\n async getActiveVariation(opts: {\n req?: ServerRequest;\n res?: ServerResponse;\n known?: Record<string, string>;\n traits: Record<string, string | number | boolean>;\n }) {\n const extractBuiltinTraits = () => {\n const url = new URL(\n opts.req?.url ?? \"/\",\n `https://${opts.req?.headers.host ?? \"server.side\"}`\n );\n return {\n pageUrl: url.href,\n };\n };\n\n return this._getActiveVariation({\n traits: {\n ...extractBuiltinTraits(),\n ...opts.traits,\n },\n getKnownValue: (key: string) => {\n if (opts.known) {\n return opts.known[key];\n } else {\n return opts.req?.cookies[`plasmic:${key}`] ?? undefined;\n }\n },\n updateKnownValue: (key: string, value: string) => {\n if (opts.res) {\n const cookie = `plasmic:${key}=${value}`;\n const resCookie = opts.res?.getHeader(\"Set-Cookie\") ?? [];\n let newCookies: string[] = [];\n if (Array.isArray(resCookie)) {\n newCookies = [...resCookie, `plasmic:${key}=${value}`];\n } else {\n newCookies = [`${resCookie}`, cookie];\n }\n\n opts.res?.setHeader(\"Set-Cookie\", newCookies);\n }\n },\n });\n }\n}\n\nexport function initPlasmicLoader(opts: NextInitOptions) {\n const loader = initPlasmicLoaderWithCache<NextJsPlasmicComponentLoader>(\n (opts) =>\n new NextJsPlasmicComponentLoader(\n new InternalPlasmicComponentLoader(opts)\n ),\n opts\n );\n loader.registerModules({\n \"next/head\": NextHead,\n \"next/link\": NextLink,\n \"next/router\": NextRouter,\n });\n if (opts.nextNavigation) {\n loader.registerModules({\n \"next/navigation\": opts.nextNavigation,\n });\n }\n return loader;\n}\n\nconst PlasmicNextLink = React.forwardRef(function PlasmicNextLink(\n props: React.ComponentProps<typeof NextLink>,\n ref: React.Ref<HTMLAnchorElement>\n) {\n // Basically renders NextLink, except when href is undefined,\n // which freaks out NextLink :-/\n if (props.href) {\n const {\n href,\n replace,\n scroll,\n shallow,\n passHref,\n prefetch,\n locale,\n ...rest\n } = props;\n // If this is a fragment identifier link, then we set\n // scroll={false} so that smooth scrolling works\n const isFragment = typeof href === \"string\" && href.startsWith(\"#\");\n // We use legacyBehavior, because we don't know which\n // version of next the user has installed\n return (\n <NextLink\n href={href}\n replace={replace}\n scroll={scroll != null ? scroll : isFragment ? false : undefined}\n shallow={shallow}\n passHref={passHref}\n prefetch={prefetch}\n locale={locale}\n {...({ legacyBehavior: true } as any)}\n >\n <a {...rest} ref={ref} />\n </NextLink>\n );\n } else {\n return <a {...props} href={undefined} ref={ref} />;\n }\n});\n\nexport function PlasmicRootProvider(\n // We omit Head but still allow override for Link\n props: Omit<React.ComponentProps<typeof CommonPlasmicRootProvider>, \"Head\">\n) {\n return (\n <CommonPlasmicRootProvider\n Head={NextHead}\n Link={PlasmicNextLink}\n {...props}\n />\n );\n}\n", "import { LoaderBundleOutput } from \"@plasmicapp/loader-core\";\nimport type { InitOptions } from \"@plasmicapp/loader-react/react-server-conditional\";\nimport type * as Watcher from \"@plasmicapp/watcher\";\nimport path from \"path\";\nimport { serverRequire, serverRequireFs } from \"./server-require\";\nimport type { NextInitOptions } from \"./shared-exports\";\n\nclass FileCache {\n constructor(private filePath: string) {}\n\n async get() {\n const fs = await serverRequireFs();\n try {\n await fs.promises.mkdir(path.dirname(this.filePath), { recursive: true });\n const data = (await fs.promises.readFile(this.filePath)).toString();\n return JSON.parse(data);\n } catch {\n return undefined;\n }\n }\n\n async set(data: LoaderBundleOutput) {\n const fs = await serverRequireFs();\n try {\n await fs.promises.writeFile(this.filePath, JSON.stringify(data));\n } catch (err) {\n console.warn(`Error writing to Plasmic cache: ${err}`);\n }\n }\n\n async clear() {\n const fs = await serverRequireFs();\n try {\n fs.promises.unlink(this.filePath);\n } catch (err) {\n // noop\n }\n }\n}\n\nfunction makeCache(opts: InitOptions) {\n const cacheDir = path.resolve(process.cwd(), \".next\", \".plasmic\");\n const cachePath = path.join(\n cacheDir,\n `plasmic-${[...opts.projects.map((p) => `${p.id}@${p.version ?? \"\"}`)]\n .sort()\n .join(\"-\")}${opts.preview ? \"-preview\" : \"\"}-cache.json`\n );\n return new FileCache(cachePath);\n}\n\nexport function initPlasmicLoaderWithCache<\n T extends {\n clearCache(): void;\n }\n>(\n initFn: (opts: InitOptions) => T,\n { nextNavigation, ...opts }: NextInitOptions\n): T {\n const isBrowser = typeof window !== \"undefined\";\n const isProd = process.env.NODE_ENV === \"production\";\n const cache = isBrowser || isProd ? undefined : makeCache(opts);\n const loader = initFn({\n onClientSideFetch: \"warn\",\n ...opts,\n cache,\n platform: \"nextjs\",\n platformOptions: {\n nextjs: {\n appDir: !!nextNavigation,\n },\n },\n // For Nextjs 12, revalidate may in fact re-use an existing instance\n // of PlasmicComponentLoader that's already in memory, so we need to\n // make sure we don't re-use the data cached in memory.\n // We also enforce this for dev mode, so that we don't have to restart\n // the dev server, in case getStaticProps() re-uses the same PlasmicComponentLoader\n alwaysFresh: !isBrowser,\n });\n\n if (!isProd) {\n const stringOpts = JSON.stringify(opts);\n\n if (process.env.PLASMIC_OPTS && process.env.PLASMIC_OPTS !== stringOpts) {\n console.warn(\n `PLASMIC: We detected that you created a new PlasmicLoader with different configurations. You may need to restart your dev server.\\n`\n );\n }\n\n process.env.PLASMIC_OPTS = stringOpts;\n }\n\n if (cache) {\n if (!isProd) {\n if (process.env.PLASMIC_WATCHED !== \"true\") {\n (async () => {\n process.env.PLASMIC_WATCHED = \"true\";\n console.log(`Subscribing to Plasmic changes...`);\n\n // Import using serverRequire, so webpack doesn't bundle us into client bundle\n try {\n const PlasmicRemoteChangeWatcher = (\n await serverRequire<typeof Watcher>(\"@plasmicapp/watcher\")\n ).PlasmicRemoteChangeWatcher;\n const watcher = new PlasmicRemoteChangeWatcher({\n projects: opts.projects,\n host: opts.host,\n });\n\n const clearCache = () => {\n cache.clear();\n loader.clearCache();\n };\n\n watcher.subscribe({\n onUpdate: () => {\n if (opts.preview) {\n clearCache();\n }\n },\n onPublish: () => {\n if (!opts.preview) {\n clearCache();\n }\n },\n });\n } catch (e) {\n console.warn(\"Couldn't subscribe to Plasmic changes\", e);\n }\n })();\n }\n } else {\n cache.clear();\n loader.clearCache();\n }\n }\n return loader;\n}\n", "import type * as FS from \"fs\";\n\nlet secretRequire: ((module: string) => any) | undefined;\ntry {\n // Secretly use require/import without webpack knowing\n // eslint-disable-next-line\n secretRequire = eval(\"require\");\n} catch (err) {\n try {\n // eslint-disable-next-line\n secretRequire = eval(\"(module) => import(module)\");\n } catch (err) {\n secretRequire = undefined;\n }\n}\n\nexport async function serverRequire<T>(module: string): Promise<T> {\n if (!secretRequire) {\n throw new Error(\n `Unexpected serverRequire() -- can only do this from a Node server!`\n );\n }\n return secretRequire(module) as Promise<T>;\n}\n\nexport async function serverRequireFs() {\n return serverRequire<typeof FS>(\"fs\");\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA,uBAAuB;AAAA,OAClB;AAWP,OAAO,cAAc;AACrB,OAAO,cAAc;AACrB,YAAY,gBAAg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M,aAAa,OAAO,SAAS,YAAY,KAAK,WAAW,GAAG;AAGlE,WACE;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA,QAAQ,UAAU,OAAO,SAAS,aAAa,QAAQ;AAAA,QACvD;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,SACK,EAAE,gBAAgB,KAAK;AAAA,MAE5B,oCAAC,sCAAM,OAAN,EAAY,MAAU;AAAA,IACzB;AAAA,EAEJ,OAAO;AACL,WAAO,oCAAC,sCAAM,QAAN,EAAa,MAAM,QAAW,MAAU;AAAA,EAClD;AACF,CAAC;AAEM,SAAS,oBAEd,OACA;AACA,SACE;AAAA,IAAC;AAAA;AAAA,MACC,MAAM;AAAA,MACN,MAAM;AAAA,OACF;AAAA,EACN;AAEJ;",
6
+ "names": ["err", "err", "opts", "PlasmicNextLink"]
7
+ }
package/dist/index.js CHANGED
@@ -114,18 +114,26 @@ var secretRequire;
114
114
  try {
115
115
  secretRequire = eval("require");
116
116
  } catch (err) {
117
- secretRequire = void 0;
117
+ try {
118
+ secretRequire = eval("(module) => import(module)");
119
+ } catch (err2) {
120
+ secretRequire = void 0;
121
+ }
118
122
  }
119
123
  function serverRequire(module2) {
120
- if (!secretRequire) {
121
- throw new Error(
122
- `Unexpected serverRequire() -- can only do this from a Node server!`
123
- );
124
- }
125
- return secretRequire(module2);
124
+ return __async(this, null, function* () {
125
+ if (!secretRequire) {
126
+ throw new Error(
127
+ `Unexpected serverRequire() -- can only do this from a Node server!`
128
+ );
129
+ }
130
+ return secretRequire(module2);
131
+ });
126
132
  }
127
133
  function serverRequireFs() {
128
- return serverRequire("fs");
134
+ return __async(this, null, function* () {
135
+ return serverRequire("fs");
136
+ });
129
137
  }
130
138
 
131
139
  // src/cache.ts
@@ -135,7 +143,7 @@ var FileCache = class {
135
143
  }
136
144
  get() {
137
145
  return __async(this, null, function* () {
138
- const fs = serverRequireFs();
146
+ const fs = yield serverRequireFs();
139
147
  try {
140
148
  yield fs.promises.mkdir(import_path.default.dirname(this.filePath), { recursive: true });
141
149
  const data = (yield fs.promises.readFile(this.filePath)).toString();
@@ -147,20 +155,22 @@ var FileCache = class {
147
155
  }
148
156
  set(data) {
149
157
  return __async(this, null, function* () {
150
- const fs = serverRequireFs();
158
+ const fs = yield serverRequireFs();
151
159
  try {
152
160
  yield fs.promises.writeFile(this.filePath, JSON.stringify(data));
153
- } catch (err) {
154
- console.warn(`Error writing to Plasmic cache: ${err}`);
161
+ } catch (err2) {
162
+ console.warn(`Error writing to Plasmic cache: ${err2}`);
155
163
  }
156
164
  });
157
165
  }
158
166
  clear() {
159
- const fs = serverRequireFs();
160
- try {
161
- fs.unlinkSync(this.filePath);
162
- } catch (err) {
163
- }
167
+ return __async(this, null, function* () {
168
+ const fs = yield serverRequireFs();
169
+ try {
170
+ fs.promises.unlink(this.filePath);
171
+ } catch (err2) {
172
+ }
173
+ });
164
174
  }
165
175
  };
166
176
  function makeCache(opts) {
@@ -174,7 +184,8 @@ function makeCache(opts) {
174
184
  );
175
185
  return new FileCache(cachePath);
176
186
  }
177
- function initPlasmicLoaderWithCache(initFn, opts) {
187
+ function initPlasmicLoaderWithCache(initFn, _a) {
188
+ var _b = _a, { nextNavigation } = _b, opts = __objRest(_b, ["nextNavigation"]);
178
189
  const isBrowser = typeof window !== "undefined";
179
190
  const isProd = process.env.NODE_ENV === "production";
180
191
  const cache = isBrowser || isProd ? void 0 : makeCache(opts);
@@ -183,6 +194,11 @@ function initPlasmicLoaderWithCache(initFn, opts) {
183
194
  }, opts), {
184
195
  cache,
185
196
  platform: "nextjs",
197
+ platformOptions: {
198
+ nextjs: {
199
+ appDir: !!nextNavigation
200
+ }
201
+ },
186
202
  // For Nextjs 12, revalidate may in fact re-use an existing instance
187
203
  // of PlasmicComponentLoader that's already in memory, so we need to
188
204
  // make sure we don't re-use the data cached in memory.
@@ -203,33 +219,35 @@ function initPlasmicLoaderWithCache(initFn, opts) {
203
219
  if (cache) {
204
220
  if (!isProd) {
205
221
  if (process.env.PLASMIC_WATCHED !== "true") {
206
- process.env.PLASMIC_WATCHED = "true";
207
- console.log(`Subscribing to Plasmic changes...`);
208
- try {
209
- const PlasmicRemoteChangeWatcher = serverRequire("@plasmicapp/watcher").PlasmicRemoteChangeWatcher;
210
- const watcher = new PlasmicRemoteChangeWatcher({
211
- projects: opts.projects,
212
- host: opts.host
213
- });
214
- const clearCache = () => {
215
- cache.clear();
216
- loader.clearCache();
217
- };
218
- watcher.subscribe({
219
- onUpdate: () => {
220
- if (opts.preview) {
221
- clearCache();
222
- }
223
- },
224
- onPublish: () => {
225
- if (!opts.preview) {
226
- clearCache();
222
+ (() => __async(this, null, function* () {
223
+ process.env.PLASMIC_WATCHED = "true";
224
+ console.log(`Subscribing to Plasmic changes...`);
225
+ try {
226
+ const PlasmicRemoteChangeWatcher = (yield serverRequire("@plasmicapp/watcher")).PlasmicRemoteChangeWatcher;
227
+ const watcher = new PlasmicRemoteChangeWatcher({
228
+ projects: opts.projects,
229
+ host: opts.host
230
+ });
231
+ const clearCache = () => {
232
+ cache.clear();
233
+ loader.clearCache();
234
+ };
235
+ watcher.subscribe({
236
+ onUpdate: () => {
237
+ if (opts.preview) {
238
+ clearCache();
239
+ }
240
+ },
241
+ onPublish: () => {
242
+ if (!opts.preview) {
243
+ clearCache();
244
+ }
227
245
  }
228
- }
229
- });
230
- } catch (e) {
231
- console.warn("Couldn't subscribe to Plasmic changes", e);
232
- }
246
+ });
247
+ } catch (e) {
248
+ console.warn("Couldn't subscribe to Plasmic changes", e);
249
+ }
250
+ }))();
233
251
  }
234
252
  } else {
235
253
  cache.clear();
@@ -244,11 +262,6 @@ var import_loader_react2 = require("@plasmicapp/loader-react");
244
262
  var NextJsPlasmicComponentLoader = class extends import_loader_react.PlasmicComponentLoader {
245
263
  constructor(internal) {
246
264
  super(internal);
247
- this.registerModules({
248
- "next/head": import_head.default,
249
- "next/link": import_link.default,
250
- "next/router": NextRouter
251
- });
252
265
  }
253
266
  getActiveVariation(opts) {
254
267
  return __async(this, null, function* () {
@@ -290,15 +303,24 @@ var NextJsPlasmicComponentLoader = class extends import_loader_react.PlasmicComp
290
303
  });
291
304
  }
292
305
  };
293
- var initPlasmicLoaderNext = (opts) => {
294
- const internal = new import_loader_react.InternalPlasmicComponentLoader(opts);
295
- return new NextJsPlasmicComponentLoader(internal);
296
- };
297
306
  function initPlasmicLoader(opts) {
298
- return initPlasmicLoaderWithCache(
299
- initPlasmicLoaderNext,
307
+ const loader = initPlasmicLoaderWithCache(
308
+ (opts2) => new NextJsPlasmicComponentLoader(
309
+ new import_loader_react.InternalPlasmicComponentLoader(opts2)
310
+ ),
300
311
  opts
301
312
  );
313
+ loader.registerModules({
314
+ "next/head": import_head.default,
315
+ "next/link": import_link.default,
316
+ "next/router": NextRouter
317
+ });
318
+ if (opts.nextNavigation) {
319
+ loader.registerModules({
320
+ "next/navigation": opts.nextNavigation
321
+ });
322
+ }
323
+ return loader;
302
324
  }
303
325
  var PlasmicNextLink = React.forwardRef(function PlasmicNextLink2(props, ref) {
304
326
  if (props.href) {