@plasmicapp/loader-fetcher 1.0.19 → 1.0.21
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/loader-fetcher.cjs.development.js +3 -2
- package/dist/loader-fetcher.cjs.development.js.map +1 -1
- package/dist/loader-fetcher.cjs.production.min.js +1 -1
- package/dist/loader-fetcher.cjs.production.min.js.map +1 -1
- package/dist/loader-fetcher.esm.js +3 -2
- package/dist/loader-fetcher.esm.js.map +1 -1
- package/package.json +2 -2
|
@@ -38,7 +38,7 @@ class Api {
|
|
|
38
38
|
try {
|
|
39
39
|
return JSON.parse(text);
|
|
40
40
|
} catch (err) {
|
|
41
|
-
throw new Error(`Error parsing JSON response: ${err}; response: ${text}`);
|
|
41
|
+
throw new Error(`Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`);
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
44
|
async fetchHtmlData(opts) {
|
|
@@ -132,6 +132,7 @@ class PlasmicModulesFetcher {
|
|
|
132
132
|
if (isBrowser) {
|
|
133
133
|
return;
|
|
134
134
|
}
|
|
135
|
+
const global = globalThis;
|
|
135
136
|
if (global.__PLASMIC_BUNDLES === undefined) {
|
|
136
137
|
global.__PLASMIC_BUNDLES = {};
|
|
137
138
|
}
|
|
@@ -143,6 +144,7 @@ function internal_getCachedBundleInNodeServer(opts) {
|
|
|
143
144
|
if (isBrowser) {
|
|
144
145
|
throw new Error(`Should not be consulting Node server cache in browser`);
|
|
145
146
|
}
|
|
147
|
+
const global = globalThis;
|
|
146
148
|
return (_global$__PLASMIC_BUN = global.__PLASMIC_BUNDLES) == null ? void 0 : _global$__PLASMIC_BUN[getBundleKey(opts)];
|
|
147
149
|
}
|
|
148
150
|
function getBundleKey({
|
|
@@ -160,7 +162,6 @@ function getBundleKey({
|
|
|
160
162
|
projects
|
|
161
163
|
});
|
|
162
164
|
}
|
|
163
|
-
const global = globalThis;
|
|
164
165
|
|
|
165
166
|
exports.Api = Api;
|
|
166
167
|
exports.PlasmicModulesFetcher = PlasmicModulesFetcher;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader-fetcher.cjs.development.js","sources":["../src/api.ts","../src/fetcher.ts"],"sourcesContent":["import fetch from '@plasmicapp/isomorphic-unfetch';\n\nexport interface ComponentMeta {\n id: string;\n usedComponents: string[];\n projectId: string;\n name: string;\n displayName: string;\n cssFile: string;\n path: string | undefined;\n isPage: boolean;\n plumeType?: string;\n entry: string;\n isCode: boolean;\n isGlobalContextProvider: boolean;\n pageMetadata?: PageMetadata;\n metadata?: Record<string, string>;\n}\n\nexport interface PageMeta extends ComponentMeta {\n isPage: true;\n path: string;\n plumeType: never;\n pageMetadata: PageMetadata;\n}\n\nexport interface PageMetadata {\n path: string;\n title?: string | null;\n description?: string | null;\n openGraphImageUrl?: string | null;\n}\n\nexport interface GlobalGroupMeta {\n id: string;\n projectId: string;\n name: string;\n type: string;\n contextFile: string;\n useName: string;\n}\n\nexport interface ProjectMeta {\n id: string;\n teamId?: string;\n indirect?: boolean;\n name: string;\n version: string;\n remoteFonts: FontMeta[];\n globalContextsProviderFileName: string;\n}\n\nexport interface FontMeta {\n url: string;\n}\n\ninterface GlobalVariantSplitContent {\n type: 'global-variant';\n projectId: string;\n group: string;\n variant: string;\n}\n\ninterface Slice {\n id: string;\n contents: GlobalVariantSplitContent[];\n externalId?: string;\n}\n\nexport interface ExperimentSlice extends Slice {\n prob: number;\n}\n\nexport interface SegmentSlice extends Slice {\n cond: any;\n}\n\nexport interface ExperimentSplit {\n id: string;\n externalId?: string;\n type: 'experiment';\n slices: ExperimentSlice[];\n}\n\nexport interface SegmentSplit {\n id: string;\n externalId?: string;\n type: 'segment';\n slices: SegmentSlice[];\n}\n\nexport type Split = ExperimentSplit | SegmentSplit;\n\nexport interface LoaderBundleOutput {\n modules: {\n browser: (CodeModule | AssetModule)[];\n server: (CodeModule | AssetModule)[];\n };\n external: string[];\n components: ComponentMeta[];\n globalGroups: GlobalGroupMeta[];\n projects: ProjectMeta[];\n activeSplits: Split[];\n}\n\nexport interface LoaderHtmlOutput {\n html: string;\n}\n\nexport interface CodeModule {\n fileName: string;\n code: string;\n imports: string[];\n type: 'code';\n}\n\nexport interface AssetModule {\n fileName: string;\n source: string;\n type: 'asset';\n}\n\nconst VERSION = '9';\n\nexport const isBrowser =\n typeof window !== 'undefined' &&\n window != null &&\n typeof window.document !== 'undefined';\n\nexport class Api {\n private host: string;\n constructor(\n private opts: {\n projects: { id: string; token: string }[];\n host?: string;\n }\n ) {\n this.host = opts.host ?? 'https://codegen.plasmic.app';\n }\n\n async fetchLoaderData(\n projectIds: string[],\n opts: {\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n browserOnly?: boolean;\n i18nKeyScheme?: 'content' | 'hash';\n }\n ) {\n const { platform, preview } = opts;\n const query = new URLSearchParams([\n ['platform', platform ?? 'react'],\n ...projectIds.map((projectId) => ['projectId', projectId]),\n ...(opts.browserOnly ? [['browserOnly', 'true']] : []),\n ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : []),\n ]).toString();\n\n const url = `${this.host}/api/v1/loader/code/${\n preview ? 'preview' : 'published'\n }?${query}`;\n const resp = await fetch(url, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n if (resp.status >= 400) {\n const error = await this.parseJsonResponse(resp);\n throw new Error(\n `Error fetching loader data: ${\n error?.error?.message ?? resp.statusText\n }`\n );\n }\n const json = await this.parseJsonResponse(resp);\n return json as LoaderBundleOutput;\n }\n\n private async parseJsonResponse(resp: Response) {\n const text = await resp.text();\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(`Error parsing JSON response: ${err}; response: ${text}`);\n }\n }\n\n async fetchHtmlData(opts: {\n projectId: string;\n component: string;\n hydrate?: boolean;\n embedHydrate?: boolean;\n }) {\n const { projectId, component, embedHydrate, hydrate } = opts;\n const query = new URLSearchParams([\n ['projectId', projectId],\n ['component', component],\n ['embedHydrate', embedHydrate ? '1' : '0'],\n ['hydrate', hydrate ? '1' : '0'],\n ]).toString();\n const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n const json = await resp.json();\n return json as LoaderHtmlOutput;\n }\n\n private makeGetHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n ...this.makeAuthHeaders(),\n };\n }\n\n // @ts-ignore\n private makePostHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n 'Content-Type': 'application/json',\n ...this.makeAuthHeaders(),\n };\n }\n\n private makeAuthHeaders() {\n const tokens = this.opts.projects\n .map((p) => `${p.id}:${p.token}`)\n .join(',');\n return {\n 'x-plasmic-api-project-tokens': tokens,\n };\n }\n}\n","import { Api, isBrowser, LoaderBundleOutput } from './api';\n\nexport interface FetcherOptions {\n projects: {\n id: string;\n version?: string;\n token: string;\n }[];\n cache?: LoaderBundleCache;\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n host?: string;\n i18nKeyScheme?: 'content' | 'hash';\n}\n\nexport interface LoaderBundleCache {\n set: (data: LoaderBundleOutput) => Promise<void>;\n get: () => Promise<LoaderBundleOutput>;\n}\n\nexport class PlasmicModulesFetcher {\n private api: Api;\n private curFetch: Promise<LoaderBundleOutput> | undefined = undefined;\n constructor(private opts: FetcherOptions) {\n this.api = new Api({\n projects: opts.projects,\n host: opts.host,\n });\n }\n\n async fetchAllData() {\n // getCachedOrFetched uses a cache defined by the user.\n const bundle = await this.getCachedOrFetch();\n\n // For React Server Components (Next.js 13+),\n // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.\n // We don't want to pass them via normal page props because that will be serialized to the browser.\n // Instead, we pass the bundle (including the server modules) via the Node `global` variable.\n //\n // cacheBundleInNodeServer caches a bundle in the Node server process.\n this.cacheBundleInNodeServer(bundle);\n\n return bundle;\n }\n\n private async getCachedOrFetch() {\n if (this.opts.cache) {\n const cachedData = await this.opts.cache.get();\n if (cachedData) {\n return cachedData;\n }\n }\n if (this.curFetch) {\n return await this.curFetch;\n }\n console.debug('Plasmic: doing a fresh fetch...');\n this.curFetch = this.doFetch();\n const data = await this.curFetch;\n this.curFetch = undefined;\n return data;\n }\n\n private async doFetch() {\n const data = await this.api.fetchLoaderData(\n this.opts.projects.map((p) =>\n p.version ? `${p.id}@${p.version}` : p.id\n ),\n {\n platform: this.opts.platform,\n preview: this.opts.preview,\n i18nKeyScheme: this.opts.i18nKeyScheme,\n browserOnly: isBrowser,\n }\n );\n if (this.opts.cache) {\n await this.opts.cache.set(data);\n }\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(', ')}`\n );\n return data;\n }\n\n private cacheBundleInNodeServer(bundle: LoaderBundleOutput) {\n if (isBrowser) {\n return;\n }\n\n if (global.__PLASMIC_BUNDLES === undefined) {\n global.__PLASMIC_BUNDLES = {};\n }\n global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;\n }\n}\n\nexport function internal_getCachedBundleInNodeServer(\n opts: FetcherOptions\n): LoaderBundleOutput | undefined {\n if (isBrowser) {\n throw new Error(`Should not be consulting Node server cache in browser`);\n }\n\n return global.__PLASMIC_BUNDLES?.[getBundleKey(opts)];\n}\n\nfunction getBundleKey({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n}: FetcherOptions) {\n return JSON.stringify({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n });\n}\n\ninterface GlobalWithBundles {\n __PLASMIC_BUNDLES?: { [bundleKey: string]: LoaderBundleOutput };\n}\nconst global = globalThis as GlobalWithBundles;\n"],"names":["VERSION","isBrowser","window","document","Api","constructor","opts","host","fetchLoaderData","projectIds","platform","preview","query","URLSearchParams","map","projectId","browserOnly","i18nKeyScheme","toString","url","resp","fetch","method","headers","makeGetHeaders","status","error","parseJsonResponse","Error","message","statusText","json","text","JSON","parse","err","fetchHtmlData","component","embedHydrate","hydrate","makeAuthHeaders","makePostHeaders","tokens","projects","p","id","token","join","PlasmicModulesFetcher","undefined","api","fetchAllData","bundle","getCachedOrFetch","cacheBundleInNodeServer","cache","cachedData","get","curFetch","console","debug","doFetch","data","version","set","name","global","__PLASMIC_BUNDLES","getBundleKey","internal_getCachedBundleInNodeServer","stringify","globalThis"],"mappings":";;;;;;;;AA0HA,MAAMA,OAAO,GAAG,GAAG;AAEZ,MAAMC,SAAS,GACpB,OAAOC,MAAM,KAAK,WAAW,IAC7BA,MAAM,IAAI,IAAI,IACd,OAAOA,MAAM,CAACC,QAAQ,KAAK,WAAW;MAE3BC,GAAG;EAEdC,YACUC,IAGP;;IAHO,SAAI,GAAJA,IAAI;IAKZ,IAAI,CAACC,IAAI,iBAAGD,IAAI,CAACC,IAAI,yBAAI,6BAA6B;;EAGxD,MAAMC,eAAe,CACnBC,UAAoB,EACpBH,IAKC;IAED,MAAM;MAAEI,QAAQ;MAAEC;KAAS,GAAGL,IAAI;IAClC,MAAMM,KAAK,GAAG,IAAIC,eAAe,CAAC,CAChC,CAAC,UAAU,EAAEH,QAAQ,WAARA,QAAQ,GAAI,OAAO,CAAC,EACjC,GAAGD,UAAU,CAACK,GAAG,CAAEC,SAAS,IAAK,CAAC,WAAW,EAAEA,SAAS,CAAC,CAAC,EAC1D,IAAIT,IAAI,CAACU,WAAW,GAAG,CAAC,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EACtD,IAAIV,IAAI,CAACW,aAAa,GAAG,CAAC,CAAC,eAAe,EAAEX,IAAI,CAACW,aAAa,CAAC,CAAC,GAAG,EAAE,CAAC,CACvE,CAAC,CAACC,QAAQ,EAAE;IAEb,MAAMC,GAAG,MAAM,IAAI,CAACZ,2BAClBI,OAAO,GAAG,SAAS,GAAG,eACpBC,OAAO;IACX,MAAMQ,IAAI,GAAG,MAAMC,KAAK,CAACF,GAAG,EAAE;MAC5BG,MAAM,EAAE,KAAK;MACbC,OAAO,EAAE,IAAI,CAAC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,CAAC;;EAG1E,gCAAOsC,MAAM,CAACC,iBAAiB,qBAAxB,sBAA2BC,YAAY,CAAC9D,IAAI,CAAC,CAAC;AACvD;AAEA,SAAS8D,YAAY,CAAC;EACpB7D,IAAI;EACJG,QAAQ;EACRO,aAAa;EACbN,OAAO;EACPgC;CACe;EACf,OAAOV,IAAI,CAACqC,SAAS,CAAC;IACpB/D,IAAI;IACJG,QAAQ;IACRO,aAAa;IACbN,OAAO;IACPgC;GACD,CAAC;AACJ;AAKA,MAAMuB,MAAM,GAAGK,UAA+B;;;;;;"}
|
|
1
|
+
{"version":3,"file":"loader-fetcher.cjs.development.js","sources":["../src/api.ts","../src/fetcher.ts"],"sourcesContent":["import fetch from '@plasmicapp/isomorphic-unfetch';\n\nexport interface ComponentMeta {\n id: string;\n usedComponents: string[];\n projectId: string;\n name: string;\n displayName: string;\n cssFile: string;\n path: string | undefined;\n isPage: boolean;\n plumeType?: string;\n entry: string;\n isCode: boolean;\n isGlobalContextProvider: boolean;\n pageMetadata?: PageMetadata;\n metadata?: Record<string, string>;\n}\n\nexport interface PageMeta extends ComponentMeta {\n isPage: true;\n path: string;\n plumeType: never;\n pageMetadata: PageMetadata;\n}\n\nexport interface PageMetadata {\n path: string;\n title?: string | null;\n description?: string | null;\n openGraphImageUrl?: string | null;\n}\n\nexport interface GlobalGroupMeta {\n id: string;\n projectId: string;\n name: string;\n type: string;\n contextFile: string;\n useName: string;\n}\n\nexport interface ProjectMeta {\n id: string;\n teamId?: string;\n indirect?: boolean;\n name: string;\n version: string;\n remoteFonts: FontMeta[];\n globalContextsProviderFileName: string;\n}\n\nexport interface FontMeta {\n url: string;\n}\n\ninterface GlobalVariantSplitContent {\n type: 'global-variant';\n projectId: string;\n group: string;\n variant: string;\n}\n\ninterface Slice {\n id: string;\n contents: GlobalVariantSplitContent[];\n externalId?: string;\n}\n\nexport interface ExperimentSlice extends Slice {\n prob: number;\n}\n\nexport interface SegmentSlice extends Slice {\n cond: any;\n}\n\nexport interface ExperimentSplit {\n id: string;\n externalId?: string;\n type: 'experiment';\n slices: ExperimentSlice[];\n}\n\nexport interface SegmentSplit {\n id: string;\n externalId?: string;\n type: 'segment';\n slices: SegmentSlice[];\n}\n\nexport type Split = ExperimentSplit | SegmentSplit;\n\nexport interface LoaderBundleOutput {\n modules: {\n browser: (CodeModule | AssetModule)[];\n server: (CodeModule | AssetModule)[];\n };\n external: string[];\n components: ComponentMeta[];\n globalGroups: GlobalGroupMeta[];\n projects: ProjectMeta[];\n activeSplits: Split[];\n}\n\nexport interface LoaderHtmlOutput {\n html: string;\n}\n\nexport interface CodeModule {\n fileName: string;\n code: string;\n imports: string[];\n type: 'code';\n}\n\nexport interface AssetModule {\n fileName: string;\n source: string;\n type: 'asset';\n}\n\nconst VERSION = '9';\n\nexport const isBrowser =\n typeof window !== 'undefined' &&\n window != null &&\n typeof window.document !== 'undefined';\n\nexport class Api {\n private host: string;\n constructor(\n private opts: {\n projects: { id: string; token: string }[];\n host?: string;\n }\n ) {\n this.host = opts.host ?? 'https://codegen.plasmic.app';\n }\n\n async fetchLoaderData(\n projectIds: string[],\n opts: {\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n browserOnly?: boolean;\n i18nKeyScheme?: 'content' | 'hash';\n }\n ) {\n const { platform, preview } = opts;\n const query = new URLSearchParams([\n ['platform', platform ?? 'react'],\n ...projectIds.map((projectId) => ['projectId', projectId]),\n ...(opts.browserOnly ? [['browserOnly', 'true']] : []),\n ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : []),\n ]).toString();\n\n const url = `${this.host}/api/v1/loader/code/${\n preview ? 'preview' : 'published'\n }?${query}`;\n const resp = await fetch(url, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n if (resp.status >= 400) {\n const error = await this.parseJsonResponse(resp);\n throw new Error(\n `Error fetching loader data: ${\n error?.error?.message ?? resp.statusText\n }`\n );\n }\n const json = await this.parseJsonResponse(resp);\n return json as LoaderBundleOutput;\n }\n\n private async parseJsonResponse(resp: Response) {\n const text = await resp.text();\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(\n `Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`\n );\n }\n }\n\n async fetchHtmlData(opts: {\n projectId: string;\n component: string;\n hydrate?: boolean;\n embedHydrate?: boolean;\n }) {\n const { projectId, component, embedHydrate, hydrate } = opts;\n const query = new URLSearchParams([\n ['projectId', projectId],\n ['component', component],\n ['embedHydrate', embedHydrate ? '1' : '0'],\n ['hydrate', hydrate ? '1' : '0'],\n ]).toString();\n const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n const json = await resp.json();\n return json as LoaderHtmlOutput;\n }\n\n private makeGetHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n ...this.makeAuthHeaders(),\n };\n }\n\n // @ts-ignore\n private makePostHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n 'Content-Type': 'application/json',\n ...this.makeAuthHeaders(),\n };\n }\n\n private makeAuthHeaders() {\n const tokens = this.opts.projects\n .map((p) => `${p.id}:${p.token}`)\n .join(',');\n return {\n 'x-plasmic-api-project-tokens': tokens,\n };\n }\n}\n","import { Api, isBrowser, LoaderBundleOutput } from './api';\n\nexport interface FetcherOptions {\n projects: {\n id: string;\n version?: string;\n token: string;\n }[];\n cache?: LoaderBundleCache;\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n host?: string;\n i18nKeyScheme?: 'content' | 'hash';\n}\n\nexport interface LoaderBundleCache {\n set: (data: LoaderBundleOutput) => Promise<void>;\n get: () => Promise<LoaderBundleOutput>;\n}\n\nexport class PlasmicModulesFetcher {\n private api: Api;\n private curFetch: Promise<LoaderBundleOutput> | undefined = undefined;\n constructor(private opts: FetcherOptions) {\n this.api = new Api({\n projects: opts.projects,\n host: opts.host,\n });\n }\n\n async fetchAllData() {\n // getCachedOrFetched uses a cache defined by the user.\n const bundle = await this.getCachedOrFetch();\n\n // For React Server Components (Next.js 13+),\n // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.\n // We don't want to pass them via normal page props because that will be serialized to the browser.\n // Instead, we pass the bundle (including the server modules) via the Node `global` variable.\n //\n // cacheBundleInNodeServer caches a bundle in the Node server process.\n this.cacheBundleInNodeServer(bundle);\n\n return bundle;\n }\n\n private async getCachedOrFetch() {\n if (this.opts.cache) {\n const cachedData = await this.opts.cache.get();\n if (cachedData) {\n return cachedData;\n }\n }\n if (this.curFetch) {\n return await this.curFetch;\n }\n console.debug('Plasmic: doing a fresh fetch...');\n this.curFetch = this.doFetch();\n const data = await this.curFetch;\n this.curFetch = undefined;\n return data;\n }\n\n private async doFetch() {\n const data = await this.api.fetchLoaderData(\n this.opts.projects.map((p) =>\n p.version ? `${p.id}@${p.version}` : p.id\n ),\n {\n platform: this.opts.platform,\n preview: this.opts.preview,\n i18nKeyScheme: this.opts.i18nKeyScheme,\n browserOnly: isBrowser,\n }\n );\n if (this.opts.cache) {\n await this.opts.cache.set(data);\n }\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(', ')}`\n );\n return data;\n }\n\n private cacheBundleInNodeServer(bundle: LoaderBundleOutput) {\n if (isBrowser) {\n return;\n }\n\n const global = globalThis as GlobalWithBundles;\n if (global.__PLASMIC_BUNDLES === undefined) {\n global.__PLASMIC_BUNDLES = {};\n }\n global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;\n }\n}\n\nexport function internal_getCachedBundleInNodeServer(\n opts: FetcherOptions\n): LoaderBundleOutput | undefined {\n if (isBrowser) {\n throw new Error(`Should not be consulting Node server cache in browser`);\n }\n\n const global = globalThis as GlobalWithBundles;\n return global.__PLASMIC_BUNDLES?.[getBundleKey(opts)];\n}\n\nfunction getBundleKey({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n}: FetcherOptions) {\n return JSON.stringify({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n });\n}\n\ninterface GlobalWithBundles {\n __PLASMIC_BUNDLES?: { [bundleKey: string]: LoaderBundleOutput };\n}\n"],"names":["VERSION","isBrowser","window","document","Api","constructor","opts","host","fetchLoaderData","projectIds","platform","preview","query","URLSearchParams","map","projectId","browserOnly","i18nKeyScheme","toString","url","resp","fetch","method","headers","makeGetHeaders","status","error","parseJsonResponse","Error","message","statusText","json","text","JSON","parse","err","fetchHtmlData","component","embedHydrate","hydrate","makeAuthHeaders","makePostHeaders","tokens","projects","p","id","token","join","PlasmicModulesFetcher","undefined","api","fetchAllData","bundle","getCachedOrFetch","cacheBundleInNodeServer","cache","cachedData","get","curFetch","console","debug","doFetch","data","version","set","name","global","globalThis","__PLASMIC_BUNDLES","getBundleKey","internal_getCachedBundleInNodeServer","stringify"],"mappings":";;;;;;;;AA0HA,MAAMA,OAAO,GAAG,GAAG;AAEZ,MAAMC,SAAS,GACpB,OAAOC,MAAM,KAAK,WAAW,IAC7BA,MAAM,IAAI,IAAI,IACd,OAAOA,MAAM,CAACC,QAAQ,KAAK,WAAW;MAE3BC,GAAG;EAEdC,YACUC,IAGP;;IAHO,SAAI,GAAJA,IAAI;IAKZ,IAAI,CAACC,IAAI,iBAAGD,IAAI,CAACC,IAAI,yBAAI,6BAA6B;;EAGxD,MAAMC,eAAe,CACnBC,UAAoB,EACpBH,IAKC;IAED,MAAM;MAAEI,QAAQ;MAAEC;KAAS,GAAGL,IAAI;IAClC,MAAMM,KAAK,GAAG,IAAIC,eAAe,CAAC,CAChC,CAAC,UAAU,EAAEH,QAAQ,WAARA,QAAQ,GAAI,OAAO,CAAC,EACjC,GAAGD,UAAU,CAACK,GAAG,CAAEC,SAAS,IAAK,CAAC,WAAW,EAAEA,SAAS,CAAC,CAAC,EAC1D,IAAIT,IAAI,CAACU,WAAW,GAAG,CAAC,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EACtD,IAAIV,IAAI,CAACW,a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B;IACxD,IAAInD,SAAS,EAAE;MACb;;IAGF,MAAMiE,MAAM,GAAGC,UAA+B;IAC9C,IAAID,MAAM,CAACE,iBAAiB,KAAKnB,SAAS,EAAE;MAC1CiB,MAAM,CAACE,iBAAiB,GAAG,EAAE;;IAE/BF,MAAM,CAACE,iBAAiB,CAACC,YAAY,CAAC,IAAI,CAAC/D,IAAI,CAAC,CAAC,GAAG8C,MAAM;;;AAI9D,SAAgBkB,oCAAoC,CAClDhE,IAAoB;;EAEpB,IAAIL,SAAS,EAAE;IACb,MAAM,IAAI2B,KAAK,wDAAwD,CAAC;;EAG1E,MAAMsC,MAAM,GAAGC,UAA+B;EAC9C,gCAAOD,MAAM,CAACE,iBAAiB,qBAAxB,sBAA2BC,YAAY,CAAC/D,IAAI,CAAC,CAAC;AACvD;AAEA,SAAS+D,YAAY,CAAC;EACpB9D,IAAI;EACJG,QAAQ;EACRO,aAAa;EACbN,OAAO;EACPgC;CACe;EACf,OAAOV,IAAI,CAACsC,SAAS,CAAC;IACpBhE,IAAI;IACJG,QAAQ;IACRO,aAAa;IACbN,OAAO;IACPgC;GACD,CAAC;AACJ;;;;;;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=(e=require("@plasmicapp/isomorphic-unfetch"))&&"object"==typeof e&&"default"in e?e.default:e;const
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=(e=require("@plasmicapp/isomorphic-unfetch"))&&"object"==typeof e&&"default"in e?e.default:e;const s="undefined"!=typeof window&&null!=window&&void 0!==window.document;class r{constructor(e){var t;this.opts=e,this.host=null!=(t=e.host)?t:"https://codegen.plasmic.app"}async fetchLoaderData(e,s){const{platform:r,preview:o}=s,a=new URLSearchParams([["platform",null!=r?r:"react"],...e.map(e=>["projectId",e]),...s.browserOnly?[["browserOnly","true"]]:[],...s.i18nKeyScheme?[["i18nKeyScheme",s.i18nKeyScheme]]:[]]).toString(),i=`${this.host}/api/v1/loader/code/${o?"preview":"published"}?${a}`,n=await t(i,{method:"GET",headers:this.makeGetHeaders()});if(n.status>=400){var c,h;const e=await this.parseJsonResponse(n);throw new Error("Error fetching loader data: "+(null!=(c=null==e||null==(h=e.error)?void 0:h.message)?c:n.statusText))}return await this.parseJsonResponse(n)}async parseJsonResponse(e){const t=await e.text();try{return JSON.parse(t)}catch(s){throw new Error(`Error parsing JSON response: ${s}; status: ${e.status}; response: ${t}`)}}async fetchHtmlData(e){const{projectId:s,component:r,embedHydrate:o,hydrate:a}=e,i=new URLSearchParams([["projectId",s],["component",r],["embedHydrate",o?"1":"0"],["hydrate",a?"1":"0"]]).toString(),n=await t(`${this.host}/api/v1/loader/html?${i}`,{method:"GET",headers:this.makeGetHeaders()});return await n.json()}makeGetHeaders(){return{"x-plasmic-loader-version":"9",...this.makeAuthHeaders()}}makePostHeaders(){return{"x-plasmic-loader-version":"9","Content-Type":"application/json",...this.makeAuthHeaders()}}makeAuthHeaders(){return{"x-plasmic-api-project-tokens":this.opts.projects.map(e=>`${e.id}:${e.token}`).join(",")}}}function o({host:e,platform:t,i18nKeyScheme:s,preview:r,projects:o}){return JSON.stringify({host:e,platform:t,i18nKeyScheme:s,preview:r,projects:o})}exports.Api=r,exports.PlasmicModulesFetcher=class{constructor(e){this.opts=e,this.curFetch=void 0,this.api=new r({projects:e.projects,host:e.host})}async fetchAllData(){const e=await this.getCachedOrFetch();return this.cacheBundleInNodeServer(e),e}async getCachedOrFetch(){if(this.opts.cache){const e=await this.opts.cache.get();if(e)return e}if(this.curFetch)return await this.curFetch;console.debug("Plasmic: doing a fresh fetch..."),this.curFetch=this.doFetch();const e=await this.curFetch;return this.curFetch=void 0,e}async doFetch(){const e=await this.api.fetchLoaderData(this.opts.projects.map(e=>e.version?`${e.id}@${e.version}`:e.id),{platform:this.opts.platform,preview:this.opts.preview,i18nKeyScheme:this.opts.i18nKeyScheme,browserOnly:s});return this.opts.cache&&await this.opts.cache.set(e),console.debug("Plasmic: fetched designs for "+e.projects.map(e=>`"${e.name}" (${e.id}@${e.version})`).join(", ")),e}cacheBundleInNodeServer(e){if(s)return;const t=globalThis;void 0===t.__PLASMIC_BUNDLES&&(t.__PLASMIC_BUNDLES={}),t.__PLASMIC_BUNDLES[o(this.opts)]=e}},exports.internal_getCachedBundleInNodeServer=function(e){var t;if(s)throw new Error("Should not be consulting Node server cache in browser");return null==(t=globalThis.__PLASMIC_BUNDLES)?void 0:t[o(e)]};
|
|
2
2
|
//# sourceMappingURL=loader-fetcher.cjs.production.min.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader-fetcher.cjs.production.min.js","sources":["../src/api.ts","../src/fetcher.ts"],"sourcesContent":["import fetch from '@plasmicapp/isomorphic-unfetch';\n\nexport interface ComponentMeta {\n id: string;\n usedComponents: string[];\n projectId: string;\n name: string;\n displayName: string;\n cssFile: string;\n path: string | undefined;\n isPage: boolean;\n plumeType?: string;\n entry: string;\n isCode: boolean;\n isGlobalContextProvider: boolean;\n pageMetadata?: PageMetadata;\n metadata?: Record<string, string>;\n}\n\nexport interface PageMeta extends ComponentMeta {\n isPage: true;\n path: string;\n plumeType: never;\n pageMetadata: PageMetadata;\n}\n\nexport interface PageMetadata {\n path: string;\n title?: string | null;\n description?: string | null;\n openGraphImageUrl?: string | null;\n}\n\nexport interface GlobalGroupMeta {\n id: string;\n projectId: string;\n name: string;\n type: string;\n contextFile: string;\n useName: string;\n}\n\nexport interface ProjectMeta {\n id: string;\n teamId?: string;\n indirect?: boolean;\n name: string;\n version: string;\n remoteFonts: FontMeta[];\n globalContextsProviderFileName: string;\n}\n\nexport interface FontMeta {\n url: string;\n}\n\ninterface GlobalVariantSplitContent {\n type: 'global-variant';\n projectId: string;\n group: string;\n variant: string;\n}\n\ninterface Slice {\n id: string;\n contents: GlobalVariantSplitContent[];\n externalId?: string;\n}\n\nexport interface ExperimentSlice extends Slice {\n prob: number;\n}\n\nexport interface SegmentSlice extends Slice {\n cond: any;\n}\n\nexport interface ExperimentSplit {\n id: string;\n externalId?: string;\n type: 'experiment';\n slices: ExperimentSlice[];\n}\n\nexport interface SegmentSplit {\n id: string;\n externalId?: string;\n type: 'segment';\n slices: SegmentSlice[];\n}\n\nexport type Split = ExperimentSplit | SegmentSplit;\n\nexport interface LoaderBundleOutput {\n modules: {\n browser: (CodeModule | AssetModule)[];\n server: (CodeModule | AssetModule)[];\n };\n external: string[];\n components: ComponentMeta[];\n globalGroups: GlobalGroupMeta[];\n projects: ProjectMeta[];\n activeSplits: Split[];\n}\n\nexport interface LoaderHtmlOutput {\n html: string;\n}\n\nexport interface CodeModule {\n fileName: string;\n code: string;\n imports: string[];\n type: 'code';\n}\n\nexport interface AssetModule {\n fileName: string;\n source: string;\n type: 'asset';\n}\n\nconst VERSION = '9';\n\nexport const isBrowser =\n typeof window !== 'undefined' &&\n window != null &&\n typeof window.document !== 'undefined';\n\nexport class Api {\n private host: string;\n constructor(\n private opts: {\n projects: { id: string; token: string }[];\n host?: string;\n }\n ) {\n this.host = opts.host ?? 'https://codegen.plasmic.app';\n }\n\n async fetchLoaderData(\n projectIds: string[],\n opts: {\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n browserOnly?: boolean;\n i18nKeyScheme?: 'content' | 'hash';\n }\n ) {\n const { platform, preview } = opts;\n const query = new URLSearchParams([\n ['platform', platform ?? 'react'],\n ...projectIds.map((projectId) => ['projectId', projectId]),\n ...(opts.browserOnly ? [['browserOnly', 'true']] : []),\n ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : []),\n ]).toString();\n\n const url = `${this.host}/api/v1/loader/code/${\n preview ? 'preview' : 'published'\n }?${query}`;\n const resp = await fetch(url, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n if (resp.status >= 400) {\n const error = await this.parseJsonResponse(resp);\n throw new Error(\n `Error fetching loader data: ${\n error?.error?.message ?? resp.statusText\n }`\n );\n }\n const json = await this.parseJsonResponse(resp);\n return json as LoaderBundleOutput;\n }\n\n private async parseJsonResponse(resp: Response) {\n const text = await resp.text();\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(`Error parsing JSON response: ${err}; response: ${text}`);\n }\n }\n\n async fetchHtmlData(opts: {\n projectId: string;\n component: string;\n hydrate?: boolean;\n embedHydrate?: boolean;\n }) {\n const { projectId, component, embedHydrate, hydrate } = opts;\n const query = new URLSearchParams([\n ['projectId', projectId],\n ['component', component],\n ['embedHydrate', embedHydrate ? '1' : '0'],\n ['hydrate', hydrate ? '1' : '0'],\n ]).toString();\n const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n const json = await resp.json();\n return json as LoaderHtmlOutput;\n }\n\n private makeGetHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n ...this.makeAuthHeaders(),\n };\n }\n\n // @ts-ignore\n private makePostHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n 'Content-Type': 'application/json',\n ...this.makeAuthHeaders(),\n };\n }\n\n private makeAuthHeaders() {\n const tokens = this.opts.projects\n .map((p) => `${p.id}:${p.token}`)\n .join(',');\n return {\n 'x-plasmic-api-project-tokens': tokens,\n };\n }\n}\n","import { Api, isBrowser, LoaderBundleOutput } from './api';\n\nexport interface FetcherOptions {\n projects: {\n id: string;\n version?: string;\n token: string;\n }[];\n cache?: LoaderBundleCache;\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n host?: string;\n i18nKeyScheme?: 'content' | 'hash';\n}\n\nexport interface LoaderBundleCache {\n set: (data: LoaderBundleOutput) => Promise<void>;\n get: () => Promise<LoaderBundleOutput>;\n}\n\nexport class PlasmicModulesFetcher {\n private api: Api;\n private curFetch: Promise<LoaderBundleOutput> | undefined = undefined;\n constructor(private opts: FetcherOptions) {\n this.api = new Api({\n projects: opts.projects,\n host: opts.host,\n });\n }\n\n async fetchAllData() {\n // getCachedOrFetched uses a cache defined by the user.\n const bundle = await this.getCachedOrFetch();\n\n // For React Server Components (Next.js 13+),\n // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.\n // We don't want to pass them via normal page props because that will be serialized to the browser.\n // Instead, we pass the bundle (including the server modules) via the Node `global` variable.\n //\n // cacheBundleInNodeServer caches a bundle in the Node server process.\n this.cacheBundleInNodeServer(bundle);\n\n return bundle;\n }\n\n private async getCachedOrFetch() {\n if (this.opts.cache) {\n const cachedData = await this.opts.cache.get();\n if (cachedData) {\n return cachedData;\n }\n }\n if (this.curFetch) {\n return await this.curFetch;\n }\n console.debug('Plasmic: doing a fresh fetch...');\n this.curFetch = this.doFetch();\n const data = await this.curFetch;\n this.curFetch = undefined;\n return data;\n }\n\n private async doFetch() {\n const data = await this.api.fetchLoaderData(\n this.opts.projects.map((p) =>\n p.version ? `${p.id}@${p.version}` : p.id\n ),\n {\n platform: this.opts.platform,\n preview: this.opts.preview,\n i18nKeyScheme: this.opts.i18nKeyScheme,\n browserOnly: isBrowser,\n }\n );\n if (this.opts.cache) {\n await this.opts.cache.set(data);\n }\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(', ')}`\n );\n return data;\n }\n\n private cacheBundleInNodeServer(bundle: LoaderBundleOutput) {\n if (isBrowser) {\n return;\n }\n\n if (global.__PLASMIC_BUNDLES === undefined) {\n global.__PLASMIC_BUNDLES = {};\n }\n global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;\n }\n}\n\nexport function internal_getCachedBundleInNodeServer(\n opts: FetcherOptions\n): LoaderBundleOutput | undefined {\n if (isBrowser) {\n throw new Error(`Should not be consulting Node server cache in browser`);\n }\n\n return global.__PLASMIC_BUNDLES?.[getBundleKey(opts)];\n}\n\nfunction getBundleKey({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n}: FetcherOptions) {\n return JSON.stringify({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n });\n}\n\ninterface GlobalWithBundles {\n __PLASMIC_BUNDLES?: { [bundleKey: string]: LoaderBundleOutput };\n}\nconst global = globalThis as GlobalWithBundles;\n"],"names":["isBrowser","window","document","Api","constructor","opts","this","host","[object Object]","projectIds","platform","preview","query","URLSearchParams","map","projectId","browserOnly","i18nKeyScheme","toString","url","resp","fetch","method","headers","makeGetHeaders","status","error","parseJsonResponse","Error","_error$error","message","statusText","text","JSON","parse","err","component","embedHydrate","hydrate","json","x-plasmic-loader-version","makeAuthHeaders","makePostHeaders","Content-Type","x-plasmic-api-project-tokens","projects","p","id","token","join","getBundleKey","stringify","global","globalThis","undefined","api","bundle","getCachedOrFetch","cacheBundleInNodeServer","cache","cachedData","get","curFetch","console","debug","doFetch","data","fetchLoaderData","version","set","name","__PLASMIC_BUNDLES","_global$__PLASMIC_BUN"],"mappings":"yKA0HA,MAEaA,EACO,oBAAXC,QACG,MAAVA,aAC2B,IAApBA,OAAOC,eAEHC,EAEXC,YACUC,SAAAC,UAAAD,EAKRC,KAAKC,cAAOF,EAAKE,QAAQ,8BAG3BC,sBACEC,EACAJ,GAOA,MAAMK,SAAEA,EAAQC,QAAEA,GAAYN,EACxBO,EAAQ,IAAIC,gBAAgB,CAChC,CAAC,iBAAYH,EAAAA,EAAY,YACtBD,EAAWK,IAAKC,GAAc,CAAC,YAAaA,OAC3CV,EAAKW,YAAc,CAAC,CAAC,cAAe,SAAW,MAC/CX,EAAKY,cAAgB,CAAC,CAAC,gBAAiBZ,EAAKY,gBAAkB,KAClEC,WAEGC,KAASb,KAAKC,2BAClBI,EAAU,UAAY,eACpBC,IACEQ,QAAaC,EAAMF,EAAK,CAC5BG,OAAQ,MACRC,QAASjB,KAAKkB,mBAEhB,GAAIJ,EAAKK,QAAU,IAAK,CAAA,QACtB,MAAMC,QAAcpB,KAAKqB,kBAAkBP,GAC3C,MAAM,IAAIQ,qDAENF,YAAAA,EAAOA,cAAPG,EAAcC,WAAWV,EAAKW,aAKpC,aADmBzB,KAAKqB,kBAAkBP,G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,GAAItD,KAAKwD,SACP,aAAaxD,KAAKwD,SAEpBC,QAAQC,MAAM,mCACd1D,KAAKwD,SAAWxD,KAAK2D,UACrB,MAAMC,QAAa5D,KAAKwD,SAExB,OADAxD,KAAKwD,cAAWR,EACTY,EAGD1D,gBACN,MAAM0D,QAAa5D,KAAKiD,IAAIY,gBAC1B7D,KAAKD,KAAKwC,SAAS/B,IAAKgC,GACtBA,EAAEsB,WAAatB,EAAEC,MAAMD,EAAEsB,UAAYtB,EAAEC,IAEzC,CACErC,SAAUJ,KAAKD,KAAKK,SACpBC,QAASL,KAAKD,KAAKM,QACnBM,cAAeX,KAAKD,KAAKY,cACzBD,YAAahB,IAWjB,OARIM,KAAKD,KAAKsD,aACNrD,KAAKD,KAAKsD,MAAMU,IAAIH,GAE5BH,QAAQC,sCAC0BE,EAAKrB,SAClC/B,IAAKgC,OAAUA,EAAEwB,UAAUxB,EAAEC,MAAMD,EAAEsB,YACrCnB,KAAK,OAEHiB,EAGDR,wBAAwBF,GAC1BxD,SAI6BsD,IAA7BF,EAAOmB,oBACTnB,EAAOmB,kBAAoB,IAE7BnB,EAAOmB,kBAAkBrB,EAAa5C,KAAKD,OAASmD,2DAKtDnD,SAEA,GAAIL,EACF,MAAM,IAAI4B,+DAGZ,gBAAOwB,EAAOmB,0BAAPC,EAA2BtB,EAAa7C"}
|
|
1
|
+
{"version":3,"file":"loader-fetcher.cjs.production.min.js","sources":["../src/api.ts","../src/fetcher.ts"],"sourcesContent":["import fetch from '@plasmicapp/isomorphic-unfetch';\n\nexport interface ComponentMeta {\n id: string;\n usedComponents: string[];\n projectId: string;\n name: string;\n displayName: string;\n cssFile: string;\n path: string | undefined;\n isPage: boolean;\n plumeType?: string;\n entry: string;\n isCode: boolean;\n isGlobalContextProvider: boolean;\n pageMetadata?: PageMetadata;\n metadata?: Record<string, string>;\n}\n\nexport interface PageMeta extends ComponentMeta {\n isPage: true;\n path: string;\n plumeType: never;\n pageMetadata: PageMetadata;\n}\n\nexport interface PageMetadata {\n path: string;\n title?: string | null;\n description?: string | null;\n openGraphImageUrl?: string | null;\n}\n\nexport interface GlobalGroupMeta {\n id: string;\n projectId: string;\n name: string;\n type: string;\n contextFile: string;\n useName: string;\n}\n\nexport interface ProjectMeta {\n id: string;\n teamId?: string;\n indirect?: boolean;\n name: string;\n version: string;\n remoteFonts: FontMeta[];\n globalContextsProviderFileName: string;\n}\n\nexport interface FontMeta {\n url: string;\n}\n\ninterface GlobalVariantSplitContent {\n type: 'global-variant';\n projectId: string;\n group: string;\n variant: string;\n}\n\ninterface Slice {\n id: string;\n contents: GlobalVariantSplitContent[];\n externalId?: string;\n}\n\nexport interface ExperimentSlice extends Slice {\n prob: number;\n}\n\nexport interface SegmentSlice extends Slice {\n cond: any;\n}\n\nexport interface ExperimentSplit {\n id: string;\n externalId?: string;\n type: 'experiment';\n slices: ExperimentSlice[];\n}\n\nexport interface SegmentSplit {\n id: string;\n externalId?: string;\n type: 'segment';\n slices: SegmentSlice[];\n}\n\nexport type Split = ExperimentSplit | SegmentSplit;\n\nexport interface LoaderBundleOutput {\n modules: {\n browser: (CodeModule | AssetModule)[];\n server: (CodeModule | AssetModule)[];\n };\n external: string[];\n components: ComponentMeta[];\n globalGroups: GlobalGroupMeta[];\n projects: ProjectMeta[];\n activeSplits: Split[];\n}\n\nexport interface LoaderHtmlOutput {\n html: string;\n}\n\nexport interface CodeModule {\n fileName: string;\n code: string;\n imports: string[];\n type: 'code';\n}\n\nexport interface AssetModule {\n fileName: string;\n source: string;\n type: 'asset';\n}\n\nconst VERSION = '9';\n\nexport const isBrowser =\n typeof window !== 'undefined' &&\n window != null &&\n typeof window.document !== 'undefined';\n\nexport class Api {\n private host: string;\n constructor(\n private opts: {\n projects: { id: string; token: string }[];\n host?: string;\n }\n ) {\n this.host = opts.host ?? 'https://codegen.plasmic.app';\n }\n\n async fetchLoaderData(\n projectIds: string[],\n opts: {\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n browserOnly?: boolean;\n i18nKeyScheme?: 'content' | 'hash';\n }\n ) {\n const { platform, preview } = opts;\n const query = new URLSearchParams([\n ['platform', platform ?? 'react'],\n ...projectIds.map((projectId) => ['projectId', projectId]),\n ...(opts.browserOnly ? [['browserOnly', 'true']] : []),\n ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : []),\n ]).toString();\n\n const url = `${this.host}/api/v1/loader/code/${\n preview ? 'preview' : 'published'\n }?${query}`;\n const resp = await fetch(url, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n if (resp.status >= 400) {\n const error = await this.parseJsonResponse(resp);\n throw new Error(\n `Error fetching loader data: ${\n error?.error?.message ?? resp.statusText\n }`\n );\n }\n const json = await this.parseJsonResponse(resp);\n return json as LoaderBundleOutput;\n }\n\n private async parseJsonResponse(resp: Response) {\n const text = await resp.text();\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(\n `Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`\n );\n }\n }\n\n async fetchHtmlData(opts: {\n projectId: string;\n component: string;\n hydrate?: boolean;\n embedHydrate?: boolean;\n }) {\n const { projectId, component, embedHydrate, hydrate } = opts;\n const query = new URLSearchParams([\n ['projectId', projectId],\n ['component', component],\n ['embedHydrate', embedHydrate ? '1' : '0'],\n ['hydrate', hydrate ? '1' : '0'],\n ]).toString();\n const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n const json = await resp.json();\n return json as LoaderHtmlOutput;\n }\n\n private makeGetHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n ...this.makeAuthHeaders(),\n };\n }\n\n // @ts-ignore\n private makePostHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n 'Content-Type': 'application/json',\n ...this.makeAuthHeaders(),\n };\n }\n\n private makeAuthHeaders() {\n const tokens = this.opts.projects\n .map((p) => `${p.id}:${p.token}`)\n .join(',');\n return {\n 'x-plasmic-api-project-tokens': tokens,\n };\n }\n}\n","import { Api, isBrowser, LoaderBundleOutput } from './api';\n\nexport interface FetcherOptions {\n projects: {\n id: string;\n version?: string;\n token: string;\n }[];\n cache?: LoaderBundleCache;\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n host?: string;\n i18nKeyScheme?: 'content' | 'hash';\n}\n\nexport interface LoaderBundleCache {\n set: (data: LoaderBundleOutput) => Promise<void>;\n get: () => Promise<LoaderBundleOutput>;\n}\n\nexport class PlasmicModulesFetcher {\n private api: Api;\n private curFetch: Promise<LoaderBundleOutput> | undefined = undefined;\n constructor(private opts: FetcherOptions) {\n this.api = new Api({\n projects: opts.projects,\n host: opts.host,\n });\n }\n\n async fetchAllData() {\n // getCachedOrFetched uses a cache defined by the user.\n const bundle = await this.getCachedOrFetch();\n\n // For React Server Components (Next.js 13+),\n // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.\n // We don't want to pass them via normal page props because that will be serialized to the browser.\n // Instead, we pass the bundle (including the server modules) via the Node `global` variable.\n //\n // cacheBundleInNodeServer caches a bundle in the Node server process.\n this.cacheBundleInNodeServer(bundle);\n\n return bundle;\n }\n\n private async getCachedOrFetch() {\n if (this.opts.cache) {\n const cachedData = await this.opts.cache.get();\n if (cachedData) {\n return cachedData;\n }\n }\n if (this.curFetch) {\n return await this.curFetch;\n }\n console.debug('Plasmic: doing a fresh fetch...');\n this.curFetch = this.doFetch();\n const data = await this.curFetch;\n this.curFetch = undefined;\n return data;\n }\n\n private async doFetch() {\n const data = await this.api.fetchLoaderData(\n this.opts.projects.map((p) =>\n p.version ? `${p.id}@${p.version}` : p.id\n ),\n {\n platform: this.opts.platform,\n preview: this.opts.preview,\n i18nKeyScheme: this.opts.i18nKeyScheme,\n browserOnly: isBrowser,\n }\n );\n if (this.opts.cache) {\n await this.opts.cache.set(data);\n }\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(', ')}`\n );\n return data;\n }\n\n private cacheBundleInNodeServer(bundle: LoaderBundleOutput) {\n if (isBrowser) {\n return;\n }\n\n const global = globalThis as GlobalWithBundles;\n if (global.__PLASMIC_BUNDLES === undefined) {\n global.__PLASMIC_BUNDLES = {};\n }\n global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;\n }\n}\n\nexport function internal_getCachedBundleInNodeServer(\n opts: FetcherOptions\n): LoaderBundleOutput | undefined {\n if (isBrowser) {\n throw new Error(`Should not be consulting Node server cache in browser`);\n }\n\n const global = globalThis as GlobalWithBundles;\n return global.__PLASMIC_BUNDLES?.[getBundleKey(opts)];\n}\n\nfunction getBundleKey({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n}: FetcherOptions) {\n return JSON.stringify({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n });\n}\n\ninterface GlobalWithBundles {\n __PLASMIC_BUNDLES?: { [bundleKey: string]: LoaderBundleOutput };\n}\n"],"names":["isBrowser","window","document","Api","constructor","opts","this","host","[object Object]","projectIds","platform","preview","query","URLSearchParams","map","projectId","browserOnly","i18nKeyScheme","toString","url","resp","fetch","method","headers","makeGetHeaders","status","error","parseJsonResponse","Error","_error$error","message","statusText","text","JSON","parse","err","component","embedHydrate","hydrate","json","x-plasmic-loader-version","makeAuthHeaders","makePostHeaders","Content-Type","x-plasmic-api-project-tokens","projects","p","id","token","join","getBundleKey","stringify","undefined","api","bundle","getCachedOrFetch","cacheBundleInNodeServer","cache","cachedData","get","curFetch","console","debug","doFetch","data","fetchLoaderData","version","set","name","global","globalThis","__PLASMIC_BUNDLES","_global$__PLASMIC_BUN"],"mappings":"yKA0HA,MAEaA,EACO,oBAAXC,QACG,MAAVA,aAC2B,IAApBA,OAAOC,eAEHC,EAEXC,YACUC,SAAAC,UAAAD,EAKRC,KAAKC,cAAOF,EAAKE,QAAQ,8BAG3BC,sBACEC,EACAJ,GAOA,MAAMK,SAAEA,EAAQC,QAAEA,GAAYN,EACxBO,EAAQ,IAAIC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EAAa5C,KAAKD,OAASiD,0DAKtDjD,SAEA,GAAIL,EACF,MAAM,IAAI4B,+DAIZ,gBADe0C,WACDC,0BAAPC,EAA2BtB,EAAa7C"}
|
|
@@ -32,7 +32,7 @@ class Api {
|
|
|
32
32
|
try {
|
|
33
33
|
return JSON.parse(text);
|
|
34
34
|
} catch (err) {
|
|
35
|
-
throw new Error(`Error parsing JSON response: ${err}; response: ${text}`);
|
|
35
|
+
throw new Error(`Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`);
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
async fetchHtmlData(opts) {
|
|
@@ -126,6 +126,7 @@ class PlasmicModulesFetcher {
|
|
|
126
126
|
if (isBrowser) {
|
|
127
127
|
return;
|
|
128
128
|
}
|
|
129
|
+
const global = globalThis;
|
|
129
130
|
if (global.__PLASMIC_BUNDLES === undefined) {
|
|
130
131
|
global.__PLASMIC_BUNDLES = {};
|
|
131
132
|
}
|
|
@@ -137,6 +138,7 @@ function internal_getCachedBundleInNodeServer(opts) {
|
|
|
137
138
|
if (isBrowser) {
|
|
138
139
|
throw new Error(`Should not be consulting Node server cache in browser`);
|
|
139
140
|
}
|
|
141
|
+
const global = globalThis;
|
|
140
142
|
return (_global$__PLASMIC_BUN = global.__PLASMIC_BUNDLES) == null ? void 0 : _global$__PLASMIC_BUN[getBundleKey(opts)];
|
|
141
143
|
}
|
|
142
144
|
function getBundleKey({
|
|
@@ -154,7 +156,6 @@ function getBundleKey({
|
|
|
154
156
|
projects
|
|
155
157
|
});
|
|
156
158
|
}
|
|
157
|
-
const global = globalThis;
|
|
158
159
|
|
|
159
160
|
export { Api, PlasmicModulesFetcher, internal_getCachedBundleInNodeServer };
|
|
160
161
|
//# sourceMappingURL=loader-fetcher.esm.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader-fetcher.esm.js","sources":["../src/api.ts","../src/fetcher.ts"],"sourcesContent":["import fetch from '@plasmicapp/isomorphic-unfetch';\n\nexport interface ComponentMeta {\n id: string;\n usedComponents: string[];\n projectId: string;\n name: string;\n displayName: string;\n cssFile: string;\n path: string | undefined;\n isPage: boolean;\n plumeType?: string;\n entry: string;\n isCode: boolean;\n isGlobalContextProvider: boolean;\n pageMetadata?: PageMetadata;\n metadata?: Record<string, string>;\n}\n\nexport interface PageMeta extends ComponentMeta {\n isPage: true;\n path: string;\n plumeType: never;\n pageMetadata: PageMetadata;\n}\n\nexport interface PageMetadata {\n path: string;\n title?: string | null;\n description?: string | null;\n openGraphImageUrl?: string | null;\n}\n\nexport interface GlobalGroupMeta {\n id: string;\n projectId: string;\n name: string;\n type: string;\n contextFile: string;\n useName: string;\n}\n\nexport interface ProjectMeta {\n id: string;\n teamId?: string;\n indirect?: boolean;\n name: string;\n version: string;\n remoteFonts: FontMeta[];\n globalContextsProviderFileName: string;\n}\n\nexport interface FontMeta {\n url: string;\n}\n\ninterface GlobalVariantSplitContent {\n type: 'global-variant';\n projectId: string;\n group: string;\n variant: string;\n}\n\ninterface Slice {\n id: string;\n contents: GlobalVariantSplitContent[];\n externalId?: string;\n}\n\nexport interface ExperimentSlice extends Slice {\n prob: number;\n}\n\nexport interface SegmentSlice extends Slice {\n cond: any;\n}\n\nexport interface ExperimentSplit {\n id: string;\n externalId?: string;\n type: 'experiment';\n slices: ExperimentSlice[];\n}\n\nexport interface SegmentSplit {\n id: string;\n externalId?: string;\n type: 'segment';\n slices: SegmentSlice[];\n}\n\nexport type Split = ExperimentSplit | SegmentSplit;\n\nexport interface LoaderBundleOutput {\n modules: {\n browser: (CodeModule | AssetModule)[];\n server: (CodeModule | AssetModule)[];\n };\n external: string[];\n components: ComponentMeta[];\n globalGroups: GlobalGroupMeta[];\n projects: ProjectMeta[];\n activeSplits: Split[];\n}\n\nexport interface LoaderHtmlOutput {\n html: string;\n}\n\nexport interface CodeModule {\n fileName: string;\n code: string;\n imports: string[];\n type: 'code';\n}\n\nexport interface AssetModule {\n fileName: string;\n source: string;\n type: 'asset';\n}\n\nconst VERSION = '9';\n\nexport const isBrowser =\n typeof window !== 'undefined' &&\n window != null &&\n typeof window.document !== 'undefined';\n\nexport class Api {\n private host: string;\n constructor(\n private opts: {\n projects: { id: string; token: string }[];\n host?: string;\n }\n ) {\n this.host = opts.host ?? 'https://codegen.plasmic.app';\n }\n\n async fetchLoaderData(\n projectIds: string[],\n opts: {\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n browserOnly?: boolean;\n i18nKeyScheme?: 'content' | 'hash';\n }\n ) {\n const { platform, preview } = opts;\n const query = new URLSearchParams([\n ['platform', platform ?? 'react'],\n ...projectIds.map((projectId) => ['projectId', projectId]),\n ...(opts.browserOnly ? [['browserOnly', 'true']] : []),\n ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : []),\n ]).toString();\n\n const url = `${this.host}/api/v1/loader/code/${\n preview ? 'preview' : 'published'\n }?${query}`;\n const resp = await fetch(url, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n if (resp.status >= 400) {\n const error = await this.parseJsonResponse(resp);\n throw new Error(\n `Error fetching loader data: ${\n error?.error?.message ?? resp.statusText\n }`\n );\n }\n const json = await this.parseJsonResponse(resp);\n return json as LoaderBundleOutput;\n }\n\n private async parseJsonResponse(resp: Response) {\n const text = await resp.text();\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(`Error parsing JSON response: ${err}; response: ${text}`);\n }\n }\n\n async fetchHtmlData(opts: {\n projectId: string;\n component: string;\n hydrate?: boolean;\n embedHydrate?: boolean;\n }) {\n const { projectId, component, embedHydrate, hydrate } = opts;\n const query = new URLSearchParams([\n ['projectId', projectId],\n ['component', component],\n ['embedHydrate', embedHydrate ? '1' : '0'],\n ['hydrate', hydrate ? '1' : '0'],\n ]).toString();\n const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n const json = await resp.json();\n return json as LoaderHtmlOutput;\n }\n\n private makeGetHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n ...this.makeAuthHeaders(),\n };\n }\n\n // @ts-ignore\n private makePostHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n 'Content-Type': 'application/json',\n ...this.makeAuthHeaders(),\n };\n }\n\n private makeAuthHeaders() {\n const tokens = this.opts.projects\n .map((p) => `${p.id}:${p.token}`)\n .join(',');\n return {\n 'x-plasmic-api-project-tokens': tokens,\n };\n }\n}\n","import { Api, isBrowser, LoaderBundleOutput } from './api';\n\nexport interface FetcherOptions {\n projects: {\n id: string;\n version?: string;\n token: string;\n }[];\n cache?: LoaderBundleCache;\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n host?: string;\n i18nKeyScheme?: 'content' | 'hash';\n}\n\nexport interface LoaderBundleCache {\n set: (data: LoaderBundleOutput) => Promise<void>;\n get: () => Promise<LoaderBundleOutput>;\n}\n\nexport class PlasmicModulesFetcher {\n private api: Api;\n private curFetch: Promise<LoaderBundleOutput> | undefined = undefined;\n constructor(private opts: FetcherOptions) {\n this.api = new Api({\n projects: opts.projects,\n host: opts.host,\n });\n }\n\n async fetchAllData() {\n // getCachedOrFetched uses a cache defined by the user.\n const bundle = await this.getCachedOrFetch();\n\n // For React Server Components (Next.js 13+),\n // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.\n // We don't want to pass them via normal page props because that will be serialized to the browser.\n // Instead, we pass the bundle (including the server modules) via the Node `global` variable.\n //\n // cacheBundleInNodeServer caches a bundle in the Node server process.\n this.cacheBundleInNodeServer(bundle);\n\n return bundle;\n }\n\n private async getCachedOrFetch() {\n if (this.opts.cache) {\n const cachedData = await this.opts.cache.get();\n if (cachedData) {\n return cachedData;\n }\n }\n if (this.curFetch) {\n return await this.curFetch;\n }\n console.debug('Plasmic: doing a fresh fetch...');\n this.curFetch = this.doFetch();\n const data = await this.curFetch;\n this.curFetch = undefined;\n return data;\n }\n\n private async doFetch() {\n const data = await this.api.fetchLoaderData(\n this.opts.projects.map((p) =>\n p.version ? `${p.id}@${p.version}` : p.id\n ),\n {\n platform: this.opts.platform,\n preview: this.opts.preview,\n i18nKeyScheme: this.opts.i18nKeyScheme,\n browserOnly: isBrowser,\n }\n );\n if (this.opts.cache) {\n await this.opts.cache.set(data);\n }\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(', ')}`\n );\n return data;\n }\n\n private cacheBundleInNodeServer(bundle: LoaderBundleOutput) {\n if (isBrowser) {\n return;\n }\n\n if (global.__PLASMIC_BUNDLES === undefined) {\n global.__PLASMIC_BUNDLES = {};\n }\n global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;\n }\n}\n\nexport function internal_getCachedBundleInNodeServer(\n opts: FetcherOptions\n): LoaderBundleOutput | undefined {\n if (isBrowser) {\n throw new Error(`Should not be consulting Node server cache in browser`);\n }\n\n return global.__PLASMIC_BUNDLES?.[getBundleKey(opts)];\n}\n\nfunction getBundleKey({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n}: FetcherOptions) {\n return JSON.stringify({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n });\n}\n\ninterface GlobalWithBundles {\n __PLASMIC_BUNDLES?: { [bundleKey: string]: LoaderBundleOutput };\n}\nconst global = globalThis as GlobalWithBundles;\n"],"names":["VERSION","isBrowser","window","document","Api","constructor","opts","host","fetchLoaderData","projectIds","platform","preview","query","URLSearchParams","map","projectId","browserOnly","i18nKeyScheme","toString","url","resp","fetch","method","headers","makeGetHeaders","status","error","parseJsonResponse","Error","message","statusText","json","text","JSON","parse","err","fetchHtmlData","component","embedHydrate","hydrate","makeAuthHeaders","makePostHeaders","tokens","projects","p","id","token","join","PlasmicModulesFetcher","undefined","api","fetchAllData","bundle","getCachedOrFetch","cacheBundleInNodeServer","cache","cachedData","get","curFetch","console","debug","doFetch","data","version","set","name","global","__PLASMIC_BUNDLES","getBundleKey","internal_getCachedBundleInNodeServer","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OAAOV,IAAI,CAACqC,SAAS,CAAC;IACpB/D,IAAI;IACJG,QAAQ;IACRO,aAAa;IACbN,OAAO;IACPgC;GACD,CAAC;AACJ;AAKA,MAAMuB,MAAM,GAAGK,UAA+B;;;;"}
|
|
1
|
+
{"version":3,"file":"loader-fetcher.esm.js","sources":["../src/api.ts","../src/fetcher.ts"],"sourcesContent":["import fetch from '@plasmicapp/isomorphic-unfetch';\n\nexport interface ComponentMeta {\n id: string;\n usedComponents: string[];\n projectId: string;\n name: string;\n displayName: string;\n cssFile: string;\n path: string | undefined;\n isPage: boolean;\n plumeType?: string;\n entry: string;\n isCode: boolean;\n isGlobalContextProvider: boolean;\n pageMetadata?: PageMetadata;\n metadata?: Record<string, string>;\n}\n\nexport interface PageMeta extends ComponentMeta {\n isPage: true;\n path: string;\n plumeType: never;\n pageMetadata: PageMetadata;\n}\n\nexport interface PageMetadata {\n path: string;\n title?: string | null;\n description?: string | null;\n openGraphImageUrl?: string | null;\n}\n\nexport interface GlobalGroupMeta {\n id: string;\n projectId: string;\n name: string;\n type: string;\n contextFile: string;\n useName: string;\n}\n\nexport interface ProjectMeta {\n id: string;\n teamId?: string;\n indirect?: boolean;\n name: string;\n version: string;\n remoteFonts: FontMeta[];\n globalContextsProviderFileName: string;\n}\n\nexport interface FontMeta {\n url: string;\n}\n\ninterface GlobalVariantSplitContent {\n type: 'global-variant';\n projectId: string;\n group: string;\n variant: string;\n}\n\ninterface Slice {\n id: string;\n contents: GlobalVariantSplitContent[];\n externalId?: string;\n}\n\nexport interface ExperimentSlice extends Slice {\n prob: number;\n}\n\nexport interface SegmentSlice extends Slice {\n cond: any;\n}\n\nexport interface ExperimentSplit {\n id: string;\n externalId?: string;\n type: 'experiment';\n slices: ExperimentSlice[];\n}\n\nexport interface SegmentSplit {\n id: string;\n externalId?: string;\n type: 'segment';\n slices: SegmentSlice[];\n}\n\nexport type Split = ExperimentSplit | SegmentSplit;\n\nexport interface LoaderBundleOutput {\n modules: {\n browser: (CodeModule | AssetModule)[];\n server: (CodeModule | AssetModule)[];\n };\n external: string[];\n components: ComponentMeta[];\n globalGroups: GlobalGroupMeta[];\n projects: ProjectMeta[];\n activeSplits: Split[];\n}\n\nexport interface LoaderHtmlOutput {\n html: string;\n}\n\nexport interface CodeModule {\n fileName: string;\n code: string;\n imports: string[];\n type: 'code';\n}\n\nexport interface AssetModule {\n fileName: string;\n source: string;\n type: 'asset';\n}\n\nconst VERSION = '9';\n\nexport const isBrowser =\n typeof window !== 'undefined' &&\n window != null &&\n typeof window.document !== 'undefined';\n\nexport class Api {\n private host: string;\n constructor(\n private opts: {\n projects: { id: string; token: string }[];\n host?: string;\n }\n ) {\n this.host = opts.host ?? 'https://codegen.plasmic.app';\n }\n\n async fetchLoaderData(\n projectIds: string[],\n opts: {\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n browserOnly?: boolean;\n i18nKeyScheme?: 'content' | 'hash';\n }\n ) {\n const { platform, preview } = opts;\n const query = new URLSearchParams([\n ['platform', platform ?? 'react'],\n ...projectIds.map((projectId) => ['projectId', projectId]),\n ...(opts.browserOnly ? [['browserOnly', 'true']] : []),\n ...(opts.i18nKeyScheme ? [['i18nKeyScheme', opts.i18nKeyScheme]] : []),\n ]).toString();\n\n const url = `${this.host}/api/v1/loader/code/${\n preview ? 'preview' : 'published'\n }?${query}`;\n const resp = await fetch(url, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n if (resp.status >= 400) {\n const error = await this.parseJsonResponse(resp);\n throw new Error(\n `Error fetching loader data: ${\n error?.error?.message ?? resp.statusText\n }`\n );\n }\n const json = await this.parseJsonResponse(resp);\n return json as LoaderBundleOutput;\n }\n\n private async parseJsonResponse(resp: Response) {\n const text = await resp.text();\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new Error(\n `Error parsing JSON response: ${err}; status: ${resp.status}; response: ${text}`\n );\n }\n }\n\n async fetchHtmlData(opts: {\n projectId: string;\n component: string;\n hydrate?: boolean;\n embedHydrate?: boolean;\n }) {\n const { projectId, component, embedHydrate, hydrate } = opts;\n const query = new URLSearchParams([\n ['projectId', projectId],\n ['component', component],\n ['embedHydrate', embedHydrate ? '1' : '0'],\n ['hydrate', hydrate ? '1' : '0'],\n ]).toString();\n const resp = await fetch(`${this.host}/api/v1/loader/html?${query}`, {\n method: 'GET',\n headers: this.makeGetHeaders(),\n });\n const json = await resp.json();\n return json as LoaderHtmlOutput;\n }\n\n private makeGetHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n ...this.makeAuthHeaders(),\n };\n }\n\n // @ts-ignore\n private makePostHeaders() {\n return {\n 'x-plasmic-loader-version': VERSION,\n 'Content-Type': 'application/json',\n ...this.makeAuthHeaders(),\n };\n }\n\n private makeAuthHeaders() {\n const tokens = this.opts.projects\n .map((p) => `${p.id}:${p.token}`)\n .join(',');\n return {\n 'x-plasmic-api-project-tokens': tokens,\n };\n }\n}\n","import { Api, isBrowser, LoaderBundleOutput } from './api';\n\nexport interface FetcherOptions {\n projects: {\n id: string;\n version?: string;\n token: string;\n }[];\n cache?: LoaderBundleCache;\n platform?: 'react' | 'nextjs' | 'gatsby';\n preview?: boolean;\n host?: string;\n i18nKeyScheme?: 'content' | 'hash';\n}\n\nexport interface LoaderBundleCache {\n set: (data: LoaderBundleOutput) => Promise<void>;\n get: () => Promise<LoaderBundleOutput>;\n}\n\nexport class PlasmicModulesFetcher {\n private api: Api;\n private curFetch: Promise<LoaderBundleOutput> | undefined = undefined;\n constructor(private opts: FetcherOptions) {\n this.api = new Api({\n projects: opts.projects,\n host: opts.host,\n });\n }\n\n async fetchAllData() {\n // getCachedOrFetched uses a cache defined by the user.\n const bundle = await this.getCachedOrFetch();\n\n // For React Server Components (Next.js 13+),\n // we need to pass server modules in LoaderBundleOutput from Server Components to Client Components.\n // We don't want to pass them via normal page props because that will be serialized to the browser.\n // Instead, we pass the bundle (including the server modules) via the Node `global` variable.\n //\n // cacheBundleInNodeServer caches a bundle in the Node server process.\n this.cacheBundleInNodeServer(bundle);\n\n return bundle;\n }\n\n private async getCachedOrFetch() {\n if (this.opts.cache) {\n const cachedData = await this.opts.cache.get();\n if (cachedData) {\n return cachedData;\n }\n }\n if (this.curFetch) {\n return await this.curFetch;\n }\n console.debug('Plasmic: doing a fresh fetch...');\n this.curFetch = this.doFetch();\n const data = await this.curFetch;\n this.curFetch = undefined;\n return data;\n }\n\n private async doFetch() {\n const data = await this.api.fetchLoaderData(\n this.opts.projects.map((p) =>\n p.version ? `${p.id}@${p.version}` : p.id\n ),\n {\n platform: this.opts.platform,\n preview: this.opts.preview,\n i18nKeyScheme: this.opts.i18nKeyScheme,\n browserOnly: isBrowser,\n }\n );\n if (this.opts.cache) {\n await this.opts.cache.set(data);\n }\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(', ')}`\n );\n return data;\n }\n\n private cacheBundleInNodeServer(bundle: LoaderBundleOutput) {\n if (isBrowser) {\n return;\n }\n\n const global = globalThis as GlobalWithBundles;\n if (global.__PLASMIC_BUNDLES === undefined) {\n global.__PLASMIC_BUNDLES = {};\n }\n global.__PLASMIC_BUNDLES[getBundleKey(this.opts)] = bundle;\n }\n}\n\nexport function internal_getCachedBundleInNodeServer(\n opts: FetcherOptions\n): LoaderBundleOutput | undefined {\n if (isBrowser) {\n throw new Error(`Should not be consulting Node server cache in browser`);\n }\n\n const global = globalThis as GlobalWithBundles;\n return global.__PLASMIC_BUNDLES?.[getBundleKey(opts)];\n}\n\nfunction getBundleKey({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n}: FetcherOptions) {\n return JSON.stringify({\n host,\n platform,\n i18nKeyScheme,\n preview,\n projects,\n });\n}\n\ninterface GlobalWithBundles {\n __PLASMIC_BUNDLES?: { [bundleKey: string]: LoaderBundleOutput };\n}\n"],"names":["VERSION","isBrowser","window","document","Api","constructor","opts","host","fetchLoaderData","projectIds","platform","preview","query","URLSearchParams","map","projectId","browserOnly","i18nKeyScheme","toString","url","resp","fetch","method","headers","makeGetHeaders","status","error","parseJsonResponse","Error","message","statusText","json","text","JSON","parse","err","fetchHtmlData","component","embedHydrate","hydrate","makeAuthHeaders","makePostHeaders","tokens","projects","p","id","token","join","PlasmicModulesFetcher","undefined","api","fetchAllData","bundle","getCachedOrFetch","cacheBundleInNodeServer","cache","cachedData","get","curFetch","console","debug","doFetch","data","version","set","name","global","globalThis","__PLASMIC_BUNDLES","getBundleKey","internal_getCachedBundleInNodeServer","stringify"],"mappings":";;AA0HA,MAAMA,OAAO,GAAG,GAAG;AAEZ,MAAMC,SAAS,GACpB,OAAOC,MAAM,KAAK,WAAW,IAC7BA,MAAM,IAAI,IAAI,IACd,OAAOA,MAAM,CAACC,QAAQ,KAAK,WAAW;MAE3BC,GAAG;EAEdC,YACUC,IAGP;;IAHO,SAAI,GAAJA,IAAI;IAKZ,IAAI,CAACC,IAAI,iBAAGD,IAAI,CAACC,IAAI,yBAAI,6BAA6B;;EAGxD,MAAMC,eAAe,CACnBC,UAAoB,EACpBH,IAKC;IAED,MAAM;MAAEI,QAAQ;MAAEC;KAAS,GAAGL,IAAI;IAClC,MAAMM,KAAK,GAAG,IAAIC,eAAe,CAAC,CAChC,CAAC,UAAU,EAAEH,QAAQ,WAARA,QAAQ,GAAI,OAAO,CAAC,EACjC,GAAGD,UAAU,CAACK,GAAG,CAAEC,SAAS,IAAK,CAAC,WAAW,EAAEA,SAAS,CAAC,CAAC,EAC1D,IAAIT,IAAI,CAACU,WAAW,GAAG,CAAC,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC,GAAG,EAAE,CAAC,EACtD,IAAIV,IAAI,CAACW,aAAa,GAAG,CAAC,CAAC,eAAe,EAAEX,IAAI,CAACW,aAAa,CAAC,CAAC,GAAG,EAAE,CAAC,CACvE,CAAC,CAACC,QAAQ,EAAE;IAEb,MAAMC,GAAG,MAAM,IAAI,CAACZ,2BAClBI,OAAO,GAAG,SAAS,GAAG,eACpBC,OAAO;IACX,MAAMQ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C,IAAI,CAAC/D,IAAI,CAAC,CAAC,GAAG8C,MAAM;;;AAI9D,SAAgBkB,oCAAoC,CAClDhE,IAAoB;;EAEpB,IAAIL,SAAS,EAAE;IACb,MAAM,IAAI2B,KAAK,wDAAwD,CAAC;;EAG1E,MAAMsC,MAAM,GAAGC,UAA+B;EAC9C,gCAAOD,MAAM,CAACE,iBAAiB,qBAAxB,sBAA2BC,YAAY,CAAC/D,IAAI,CAAC,CAAC;AACvD;AAEA,SAAS+D,YAAY,CAAC;EACpB9D,IAAI;EACJG,QAAQ;EACRO,aAAa;EACbN,OAAO;EACPgC;CACe;EACf,OAAOV,IAAI,CAACsC,SAAS,CAAC;IACpBhE,IAAI;IACJG,QAAQ;IACRO,aAAa;IACbN,OAAO;IACPgC;GACD,CAAC;AACJ;;;;"}
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "1.0.
|
|
2
|
+
"version": "1.0.21",
|
|
3
3
|
"license": "MIT",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"typings": "dist/index.d.ts",
|
|
@@ -58,5 +58,5 @@
|
|
|
58
58
|
"publishConfig": {
|
|
59
59
|
"access": "public"
|
|
60
60
|
},
|
|
61
|
-
"gitHead": "
|
|
61
|
+
"gitHead": "d0bc53cc0a418b2cb27dd62c4a2a6d56a2b0cd6c"
|
|
62
62
|
}
|