@plasmicapp/loader-fetcher 1.0.25 → 1.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -173,6 +173,7 @@ var PlasmicModulesFetcher = class {
173
173
  }
174
174
  getCachedOrFetch() {
175
175
  return __async(this, null, function* () {
176
+ var _a;
176
177
  if (this.opts.cache) {
177
178
  const cachedData = yield this.opts.cache.get();
178
179
  if (cachedData) {
@@ -182,7 +183,7 @@ var PlasmicModulesFetcher = class {
182
183
  if (this.curFetch) {
183
184
  return yield this.curFetch;
184
185
  }
185
- if (!process.env.PLASMIC_QUIET) {
186
+ if (typeof process === "undefined" || !((_a = process.env) == null ? void 0 : _a.PLASMIC_QUIET)) {
186
187
  console.debug("Plasmic: doing a fresh fetch...");
187
188
  }
188
189
  this.curFetch = this.doFetch();
@@ -193,6 +194,7 @@ var PlasmicModulesFetcher = class {
193
194
  }
194
195
  doFetch() {
195
196
  return __async(this, null, function* () {
197
+ var _a;
196
198
  const data = yield this.api.fetchLoaderData(
197
199
  this.opts.projects.map(
198
200
  (p) => p.version ? `${p.id}@${p.version}` : p.id
@@ -207,7 +209,7 @@ var PlasmicModulesFetcher = class {
207
209
  if (this.opts.cache) {
208
210
  yield this.opts.cache.set(data);
209
211
  }
210
- if (!process.env.PLASMIC_QUIET) {
212
+ if (typeof process === "undefined" || !((_a = process.env) == null ? void 0 : _a.PLASMIC_QUIET)) {
211
213
  console.debug(
212
214
  `Plasmic: fetched designs for ${data.projects.map((p) => `"${p.name}" (${p.id}@${p.version})`).join(", ")}`
213
215
  );
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/api.ts", "../src/fetcher.ts"],
4
- "sourcesContent": ["export type {\n AssetModule,\n CodeModule,\n ComponentMeta,\n ExperimentSlice,\n FontMeta,\n GlobalGroupMeta,\n LoaderBundleOutput,\n LoaderHtmlOutput,\n PageMeta,\n PageMetadata,\n ProjectMeta,\n SegmentSlice,\n Split,\n} from \"./api\";\nexport { Api } from \"./api\";\nexport type { FetcherOptions, LoaderBundleCache } from \"./fetcher\";\nexport {\n internal_getCachedBundleInNodeServer,\n PlasmicModulesFetcher,\n} from \"./fetcher\";\n", "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 = '10';\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 if (!process.env.PLASMIC_QUIET) {\n console.debug(\"Plasmic: doing a fresh fetch...\");\n }\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 if (!process.env.PLASMIC_QUIET) {\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(\", \")}`\n );\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"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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CAAC;AAAA,IAC9B;AACA,WAAO,kBAAkB,aAAa,KAAK,IAAI,CAAC,IAAI;AAAA,EACtD;AACF;AAEO,SAAS,qCACd,MACgC;AAxGlC;AAyGE,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AAEA,QAAM,SAAS;AACf,UAAO,YAAO,sBAAP,mBAA2B,aAAa,IAAI;AACrD;AAEA,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAmB;AACjB,SAAO,KAAK,UAAU;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;",
4
+ "sourcesContent": ["export type {\n AssetModule,\n CodeModule,\n ComponentMeta,\n ExperimentSlice,\n FontMeta,\n GlobalGroupMeta,\n LoaderBundleOutput,\n LoaderHtmlOutput,\n PageMeta,\n PageMetadata,\n ProjectMeta,\n SegmentSlice,\n Split,\n} from \"./api\";\nexport { Api } from \"./api\";\nexport type { FetcherOptions, LoaderBundleCache } from \"./fetcher\";\nexport {\n internal_getCachedBundleInNodeServer,\n PlasmicModulesFetcher,\n} from \"./fetcher\";\n", "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 = '10';\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 if (typeof process === \"undefined\" || !process.env?.PLASMIC_QUIET) {\n console.debug(\"Plasmic: doing a fresh fetch...\");\n }\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 if (typeof process === \"undefined\" || !process.env?.PLASMIC_QUIET) {\n console.debug(\n `Plasmic: fetched designs for ${data.projects\n .map((p) => `\"${p.name}\" (${p.id}@${p.version})`)\n .join(\", \")}`\n );\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"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,gCAAkB;AA0HlB,IAAM,UAAU;AAET,IAAM,YACX,OAAO,WAAW,eAClB,UAAU,QACV,OAAO,OAAO,aAAa;AAEtB,IAAM,MAAN,MAAU;AAAA,EAEf,YACU,MAIR;AAJQ;AApIZ;AAyII,SAAK,QAAO,UAAK,SAAL,YAAa;AAAA,EAC3B;AAAA,EAEM,gBACJ,YACA,MAMA;AAAA;AApJJ;AAqJI,YAAM,EAAE,UAAU,QAAQ,IAAI;AAC9B,YAAM,QAAQ,IAAI,gBAAgB;AAAA,QAChC,CAAC,YAAY,8BAAY,OAAO;AAAA,QAChC,GAAG,WAAW,IAAI,CAAC,cAAc,CAAC,aAAa,SAAS,CAAC;AAAA,QACzD,GAAI,KAAK,cAAc,CAAC,CAAC,eAAe,MAAM,CAAC,IAAI,CAAC;AAAA,QACpD,GAAI,KAAK,gBAAgB,CAAC,CAAC,iBAAiB,KAAK,aAA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AAE,UAAU,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE;AAAA,QACzC;AAAA,QACA;AAAA,UACE,UAAU,KAAK,KAAK;AAAA,UACpB,SAAS,KAAK,KAAK;AAAA,UACnB,eAAe,KAAK,KAAK;AAAA,UACzB,aAAa;AAAA,QACf;AAAA,MACF;AACA,UAAI,KAAK,KAAK,OAAO;AACnB,cAAM,KAAK,KAAK,MAAM,IAAI,IAAI;AAAA,MAChC;AACA,UAAI,OAAO,YAAY,eAAe,GAAC,aAAQ,QAAR,mBAAa,gBAAe;AACjE,gBAAQ;AAAA,UACN,gCAAgC,KAAK,SAClC,IAAI,CAAC,MAAM,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAC/C,KAAK,IAAI;AAAA,QACd;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA;AAAA,EAEQ,wBAAwB,QAA4B;AAC1D,QAAI,WAAW;AACb;AAAA,IACF;AAEA,UAAM,SAAS;AACf,QAAI,OAAO,sBAAsB,QAAW;AAC1C,aAAO,oBAAoB,CAAC;AAAA,IAC9B;AACA,WAAO,kBAAkB,aAAa,KAAK,IAAI,CAAC,IAAI;AAAA,EACtD;AACF;AAEO,SAAS,qCACd,MACgC;AAxGlC;AAyGE,MAAI,WAAW;AACb,UAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AAEA,QAAM,SAAS;AACf,UAAO,YAAO,sBAAP,mBAA2B,aAAa,IAAI;AACrD;AAEA,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAmB;AACjB,SAAO,KAAK,UAAU;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;",
6
6
  "names": ["fetch"]
7
7
  }
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.25",
2
+ "version": "1.0.27",
3
3
  "license": "MIT",
4
4
  "types": "./dist/index.d.ts",
5
5
  "main": "./dist/index.js",
@@ -41,5 +41,5 @@
41
41
  "publishConfig": {
42
42
  "access": "public"
43
43
  },
44
- "gitHead": "9f7e1bff70ae5f945027b4718d85d2a17f89501e"
44
+ "gitHead": "5885bbd51f5aa2e88adc8581b96a4547ef48a369"
45
45
  }