@preprio/prepr-nextjs 2.0.3 → 2.0.4
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/{chunk-QZTUT4DH.js → chunk-XZGZV5UR.js} +2 -2
- package/dist/chunk-XZGZV5UR.js.map +1 -0
- package/dist/middleware/index.cjs +1 -1
- package/dist/middleware/index.cjs.map +1 -1
- package/dist/middleware/index.js +1 -1
- package/dist/server/index.cjs +2 -2
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-26CXDAG7.mjs +0 -72
- package/dist/chunk-26CXDAG7.mjs.map +0 -1
- package/dist/chunk-2BRZNIOK.js +0 -2
- package/dist/chunk-2BRZNIOK.js.map +0 -1
- package/dist/chunk-32XGP2RS.mjs +0 -4218
- package/dist/chunk-32XGP2RS.mjs.map +0 -1
- package/dist/chunk-6FNC3XMI.js +0 -45
- package/dist/chunk-C6L3X6KZ.js +0 -201
- package/dist/chunk-C6L3X6KZ.js.map +0 -1
- package/dist/chunk-DI26GYQY.js +0 -201
- package/dist/chunk-IL3U74YL.js +0 -2
- package/dist/chunk-IL3U74YL.js.map +0 -1
- package/dist/chunk-J3Y65EMB.js +0 -2
- package/dist/chunk-J3Y65EMB.js.map +0 -1
- package/dist/chunk-JPRRZPBL.js +0 -43
- package/dist/chunk-JPRRZPBL.js.map +0 -1
- package/dist/chunk-MKSF2TOK.js +0 -2
- package/dist/chunk-MKSF2TOK.js.map +0 -1
- package/dist/chunk-MZGTV4KW.js +0 -2
- package/dist/chunk-MZGTV4KW.js.map +0 -1
- package/dist/chunk-NWRQFDMF.js +0 -2
- package/dist/chunk-NWRQFDMF.js.map +0 -1
- package/dist/chunk-QZTUT4DH.js.map +0 -1
- package/dist/chunk-YKY3OKYG.js +0 -2
- package/dist/chunk-YKY3OKYG.js.map +0 -1
- package/dist/middleware/index.mjs +0 -4
- package/dist/middleware/index.mjs.map +0 -1
- package/dist/pages/react/index.cjs +0 -8
- package/dist/pages/react/index.cjs.map +0 -1
- package/dist/pages/react/index.d.cts +0 -99
- package/dist/pages/react/index.d.ts +0 -99
- package/dist/pages/react/index.js +0 -8
- package/dist/pages/react/index.js.map +0 -1
- package/dist/pages/server/index.cjs +0 -7
- package/dist/pages/server/index.cjs.map +0 -1
- package/dist/pages/server/index.d.cts +0 -83
- package/dist/pages/server/index.d.ts +0 -83
- package/dist/pages/server/index.js +0 -7
- package/dist/pages/server/index.js.map +0 -1
- package/dist/react/index.mjs +0 -10179
- package/dist/react/index.mjs.map +0 -1
- package/dist/server/index.mjs +0 -1569
- package/dist/server/index.mjs.map +0 -1
- package/dist/types/index.mjs +0 -3
- package/dist/types/index.mjs.map +0 -1
- package/dist/utils/index.mjs +0 -3307
- package/dist/utils/index.mjs.map +0 -1
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
import { GetServerSidePropsContext, GetStaticPropsContext } from 'next';
|
|
2
|
-
import { PreprErrorCode, PreprSegment, PreprToolbarProps } from '../../types/index.js';
|
|
3
|
-
export { default as createPreprMiddleware } from '../../middleware/index.js';
|
|
4
|
-
import 'next/server';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Custom error class for Prepr-related errors
|
|
8
|
-
*/
|
|
9
|
-
declare class PreprError extends Error {
|
|
10
|
-
readonly code: PreprErrorCode;
|
|
11
|
-
readonly context?: string | undefined;
|
|
12
|
-
readonly originalError?: Error | undefined;
|
|
13
|
-
constructor(message: string, code: PreprErrorCode, context?: string | undefined, originalError?: Error | undefined);
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Returns the Prepr Customer ID from the context headers
|
|
17
|
-
* @param context - The Next.js context object
|
|
18
|
-
* @returns Prepr Customer ID
|
|
19
|
-
*/
|
|
20
|
-
declare function getPreprUUID(context: GetServerSidePropsContext | GetStaticPropsContext): string | null;
|
|
21
|
-
/**
|
|
22
|
-
* Returns the active segment from the context headers
|
|
23
|
-
* @param context - The Next.js context object
|
|
24
|
-
* @returns Active segment
|
|
25
|
-
*/
|
|
26
|
-
declare function getActiveSegment(context: GetServerSidePropsContext | GetStaticPropsContext): string | null;
|
|
27
|
-
/**
|
|
28
|
-
* Returns the active variant from the context headers
|
|
29
|
-
* @param context - The Next.js context object
|
|
30
|
-
* @returns Active variant
|
|
31
|
-
*/
|
|
32
|
-
declare function getActiveVariant(context: GetServerSidePropsContext | GetStaticPropsContext): string | null;
|
|
33
|
-
/**
|
|
34
|
-
* Helper function to retrieve all Prepr headers from context
|
|
35
|
-
* @param context - The Next.js context object
|
|
36
|
-
* @returns Object with Prepr headers
|
|
37
|
-
*/
|
|
38
|
-
declare function getPreprHeaders(context: GetServerSidePropsContext | GetStaticPropsContext): Record<string, string>;
|
|
39
|
-
/**
|
|
40
|
-
* Validates a Prepr GraphQL token
|
|
41
|
-
* @param token - The token to validate
|
|
42
|
-
* @returns Validation result with error details if invalid
|
|
43
|
-
*/
|
|
44
|
-
declare function validatePreprToken(token: string): {
|
|
45
|
-
valid: boolean;
|
|
46
|
-
error?: string;
|
|
47
|
-
};
|
|
48
|
-
/**
|
|
49
|
-
* Checks if the current environment is in preview mode
|
|
50
|
-
* @returns True if in preview mode
|
|
51
|
-
*/
|
|
52
|
-
declare function isPreviewMode(): boolean;
|
|
53
|
-
/**
|
|
54
|
-
* Extracts the access token from a Prepr GraphQL URL
|
|
55
|
-
* @param graphqlUrl - The full Prepr GraphQL URL
|
|
56
|
-
* @returns The access token or null if invalid
|
|
57
|
-
* @example
|
|
58
|
-
* ```typescript
|
|
59
|
-
* const token = extractAccessToken('https://graphql.prepr.io/abc123')
|
|
60
|
-
* // Returns: 'abc123'
|
|
61
|
-
* ```
|
|
62
|
-
*/
|
|
63
|
-
declare function extractAccessToken(graphqlUrl: string): string | null;
|
|
64
|
-
/**
|
|
65
|
-
* Fetches the segments from the Prepr API
|
|
66
|
-
* @param token Prepr GraphQL URL with scope 'segments'
|
|
67
|
-
* @returns Array of PreprSegment
|
|
68
|
-
* @throws PreprError if the request fails
|
|
69
|
-
*/
|
|
70
|
-
declare function getPreprEnvironmentSegments(token: string): Promise<PreprSegment[]>;
|
|
71
|
-
/**
|
|
72
|
-
* Fetches all the necessary toolbar props for Pages directory
|
|
73
|
-
* @param token Prepr GraphQL URL with scope 'segments'
|
|
74
|
-
* @param context The Next.js context object from getServerSideProps
|
|
75
|
-
* @returns Object with activeSegment, activeVariant and data
|
|
76
|
-
*/
|
|
77
|
-
declare function getToolbarProps(token: string, context: GetServerSidePropsContext | GetStaticPropsContext): Promise<PreprToolbarProps>;
|
|
78
|
-
/**
|
|
79
|
-
* Alias for getToolbarProps for consistency with App Router API
|
|
80
|
-
*/
|
|
81
|
-
declare const getPreviewBarProps: typeof getToolbarProps;
|
|
82
|
-
|
|
83
|
-
export { PreprError, extractAccessToken, getActiveSegment, getActiveVariant, getPreprEnvironmentSegments, getPreprHeaders, getPreprUUID, getPreviewBarProps, getToolbarProps, isPreviewMode, validatePreprToken };
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import {a as a$1}from'../../chunk-2BRZNIOK.js';export{b as createPreprMiddleware}from'../../chunk-2BRZNIOK.js';import {c}from'../../chunk-E7ATRJ2F.js';var s=class extends Error{constructor(e,t,o,p){super(e);this.code=t;this.context=o;this.originalError=p;this.name="PreprError";}};function a(r,n){if("req"in r&&r.req){let t=r.req.headers[n.toLowerCase()];return typeof t=="string"?t:(t==null?void 0:t[0])||null}return null}function x(r){return a(r,"prepr-customer-id")}function P(r){return a(r,"Prepr-Segments")}function g(r){return a(r,"Prepr-ABtesting")}function v(r){let n={};if("req"in r&&r.req){let e=r.req.headers;Object.entries(e).forEach(([t,o])=>{t.toLowerCase().startsWith("prepr")&&(n[t]=typeof o=="string"?o:(o==null?void 0:o[0])||"");});}return n}function d(r){return r?r.startsWith("https://")?{valid:true}:{valid:false,error:"Token must be a valid HTTPS URL"}:{valid:false,error:"Token is required"}}function u(){return process.env.PREPR_ENV==="preview"}function w(r){if(!r)return null;try{let n=new URL(r);if(n.hostname!=="graphql.prepr.io")return null;let e=n.pathname.split("/"),t=e[e.length-1];return t&&t.length>0?t:null}catch(n){return null}}function m(r){return c(this,null,function*(){let n=d(r);if(!n.valid)throw new s(n.error,"INVALID_TOKEN","getPreprEnvironmentSegments");try{let e=yield fetch(r,{headers:{"User-Agent":`Prepr-Preview-Bar/${S()}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify({query:`{
|
|
2
|
-
_Segments {
|
|
3
|
-
_id
|
|
4
|
-
name
|
|
5
|
-
}
|
|
6
|
-
}`})});if(!e.ok)throw new s(`HTTP ${e.status}: ${e.statusText}`,"HTTP_ERROR","getPreprEnvironmentSegments");let t=yield e.json();if(!t||!t.data||!t.data._Segments)throw new s("Invalid response format from Prepr API","INVALID_RESPONSE","getPreprEnvironmentSegments");return t.data._Segments}catch(e){throw e instanceof s?e:new s("Failed to fetch segments from Prepr API","FETCH_ERROR","getPreprEnvironmentSegments",e instanceof Error?e:new Error(String(e)))}})}function f(r,n){return c(this,null,function*(){let e=[],t=null,o=null;if(u())try{e=yield m(r),t=P(n),o=g(n);}catch(p){console.error("Failed to fetch toolbar props:",p),e=[];}return {activeSegment:t,activeVariant:o,data:e}})}var C=f;function S(){return a$1.version}export{s as PreprError,w as extractAccessToken,P as getActiveSegment,g as getActiveVariant,m as getPreprEnvironmentSegments,v as getPreprHeaders,x as getPreprUUID,C as getPreviewBarProps,f as getToolbarProps,u as isPreviewMode,d as validatePreprToken};//# sourceMappingURL=index.js.map
|
|
7
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/pages/server/index.ts"],"names":["PreprError","message","code","context","originalError","getPreprHeaderFromContext","name","headerValue","getPreprUUID","getActiveSegment","getActiveVariant","getPreprHeaders","preprHeaders","headers","key","value","validatePreprToken","token","isPreviewMode","extractAccessToken","graphqlUrl","url","pathParts","e","getPreprEnvironmentSegments","__async","validation","response","getPackageVersion","json","error","getToolbarProps","data","activeSegment","activeVariant","getPreviewBarProps","package_default"],"mappings":"uJAYO,IAAMA,CAAAA,CAAN,cAAyB,KAAM,CACpC,WAAA,CACEC,CAAAA,CACgBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAChB,CACA,KAAA,CAAMH,CAAO,EAJG,IAAA,CAAA,IAAA,CAAAC,CAAAA,CACA,IAAA,CAAA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAA,aAAA,CAAAC,CAAAA,CAGhB,IAAA,CAAK,IAAA,CAAO,aACd,CACF,EAQA,SAASC,CAAAA,CACPF,CAAAA,CACAG,CAAAA,CACe,CACf,GAAI,KAAA,GAASH,CAAAA,EAAWA,CAAAA,CAAQ,GAAA,CAAK,CAEnC,IAAMI,CAAAA,CADUJ,CAAAA,CAAQ,GAAA,CAAI,OAAA,CACAG,CAAAA,CAAK,WAAA,EAAa,CAAA,CAC9C,OAAO,OAAOC,GAAgB,QAAA,CAC1BA,CAAAA,CAAAA,CACAA,CAAAA,EAAA,IAAA,CAAA,MAAA,CAAAA,CAAAA,CAAc,CAAA,CAAA,GAAM,IAC1B,CACA,OAAO,IACT,CAOO,SAASC,CAAAA,CACdL,CAAAA,CACe,CACf,OAAOE,CAAAA,CAA0BF,EAAS,mBAAmB,CAC/D,CAOO,SAASM,CAAAA,CACdN,CAAAA,CACe,CACf,OAAOE,CAAAA,CAA0BF,CAAAA,CAAS,gBAAgB,CAC5D,CAOO,SAASO,CAAAA,CACdP,CAAAA,CACe,CACf,OAAOE,CAAAA,CAA0BF,CAAAA,CAAS,iBAAiB,CAC7D,CAOO,SAASQ,CAAAA,CACdR,EACwB,CACxB,IAAMS,CAAAA,CAAuC,EAAC,CAE9C,GAAI,KAAA,GAAST,CAAAA,EAAWA,EAAQ,GAAA,CAAK,CACnC,IAAMU,CAAAA,CAAUV,CAAAA,CAAQ,GAAA,CAAI,OAAA,CAC5B,MAAA,CAAO,OAAA,CAAQU,CAAO,CAAA,CAAE,O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Ad,CAAAA,CAC4B,CAAA,OAAAsB,CAAAA,CAAA,IAAA,CAAA,IAAA,CAAA,WAAA,CAC5B,IAAIO,CAAAA,CAAuB,EAAC,CACxBC,CAAAA,CAA+B,IAAA,CAC/BC,CAAAA,CAA+B,IAAA,CAGnC,GAAIhB,CAAAA,EAAc,CAChB,GAAI,CACFc,CAAAA,CAAO,MAAMR,CAAAA,CAA4BP,CAAK,CAAA,CAC9CgB,CAAAA,CAAgBxB,CAAAA,CAAiBN,CAAO,CAAA,CACxC+B,CAAAA,CAAgBxB,CAAAA,CAAiBP,CAAO,EAC1C,CAAA,MAAS2B,CAAAA,CAAO,CAEd,OAAA,CAAQ,KAAA,CAAM,gCAAA,CAAkCA,CAAK,CAAA,CAErDE,CAAAA,CAAO,GACT,CAGF,OAAO,CACL,aAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,IAAA,CAAAF,CACF,CACF,CAAA,CAAA,CAKO,IAAMG,CAAAA,CAAqBJ,EAElC,SAASH,CAAAA,EAAoB,CAC3B,OAAOQ,IAAM,OACf","file":"index.js","sourcesContent":["import { GetServerSidePropsContext, GetStaticPropsContext } from 'next';\nimport {\n PreprToolbarProps,\n PreprSegment,\n PreprHeaderName,\n PreprErrorCode,\n} from '../../types';\nimport pjson from '../../../package.json';\n\n/**\n * Custom error class for Prepr-related errors\n */\nexport class PreprError extends Error {\n constructor(\n message: string,\n public readonly code: PreprErrorCode,\n public readonly context?: string,\n public readonly originalError?: Error\n ) {\n super(message);\n this.name = 'PreprError';\n }\n}\n\n/**\n * Internal helper to get a specific Prepr header value from context\n * @param context - The Next.js context object from getServerSideProps or getStaticProps\n * @param name - The header name to retrieve\n * @returns The header value or null if not found\n */\nfunction getPreprHeaderFromContext(\n context: GetServerSidePropsContext | GetStaticPropsContext,\n name: PreprHeaderName\n): string | null {\n if ('req' in context && context.req) {\n const headers = context.req.headers;\n const headerValue = headers[name.toLowerCase()];\n return typeof headerValue === 'string'\n ? headerValue\n : headerValue?.[0] || null;\n }\n return null;\n}\n\n/**\n * Returns the Prepr Customer ID from the context headers\n * @param context - The Next.js context object\n * @returns Prepr Customer ID\n */\nexport function getPreprUUID(\n context: GetServerSidePropsContext | GetStaticPropsContext\n): string | null {\n return getPreprHeaderFromContext(context, 'prepr-customer-id');\n}\n\n/**\n * Returns the active segment from the context headers\n * @param context - The Next.js context object\n * @returns Active segment\n */\nexport function getActiveSegment(\n context: GetServerSidePropsContext | GetStaticPropsContext\n): string | null {\n return getPreprHeaderFromContext(context, 'Prepr-Segments');\n}\n\n/**\n * Returns the active variant from the context headers\n * @param context - The Next.js context object\n * @returns Active variant\n */\nexport function getActiveVariant(\n context: GetServerSidePropsContext | GetStaticPropsContext\n): string | null {\n return getPreprHeaderFromContext(context, 'Prepr-ABtesting');\n}\n\n/**\n * Helper function to retrieve all Prepr headers from context\n * @param context - The Next.js context object\n * @returns Object with Prepr headers\n */\nexport function getPreprHeaders(\n context: GetServerSidePropsContext | GetStaticPropsContext\n): Record<string, string> {\n const preprHeaders: Record<string, string> = {};\n\n if ('req' in context && context.req) {\n const headers = context.req.headers;\n Object.entries(headers).forEach(([key, value]) => {\n if (key.toLowerCase().startsWith('prepr')) {\n preprHeaders[key] =\n typeof value === 'string' ? value : value?.[0] || '';\n }\n });\n }\n\n return preprHeaders;\n}\n\n/**\n * Validates a Prepr GraphQL token\n * @param token - The token to validate\n * @returns Validation result with error details if invalid\n */\nexport function validatePreprToken(token: string): {\n valid: boolean;\n error?: string;\n} {\n if (!token) {\n return { valid: false, error: 'Token is required' };\n }\n if (!token.startsWith('https://')) {\n return { valid: false, error: 'Token must be a valid HTTPS URL' };\n }\n return { valid: true };\n}\n\n/**\n * Checks if the current environment is in preview mode\n * @returns True if in preview mode\n */\nexport function isPreviewMode(): boolean {\n return process.env.PREPR_ENV === 'preview';\n}\n\n/**\n * Extracts the access token from a Prepr GraphQL URL\n * @param graphqlUrl - The full Prepr GraphQL URL\n * @returns The access token or null if invalid\n * @example\n * ```typescript\n * const token = extractAccessToken('https://graphql.prepr.io/abc123')\n * // Returns: 'abc123'\n * ```\n */\nexport function extractAccessToken(graphqlUrl: string): string | null {\n if (!graphqlUrl) return null;\n\n try {\n const url = new URL(graphqlUrl);\n if (url.hostname !== 'graphql.prepr.io') return null;\n\n const pathParts = url.pathname.split('/');\n const token = pathParts[pathParts.length - 1];\n\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Fetches the segments from the Prepr API\n * @param token Prepr GraphQL URL with scope 'segments'\n * @returns Array of PreprSegment\n * @throws PreprError if the request fails\n */\nexport async function getPreprEnvironmentSegments(\n token: string\n): Promise<PreprSegment[]> {\n const validation = validatePreprToken(token);\n if (!validation.valid) {\n throw new PreprError(\n validation.error!,\n 'INVALID_TOKEN',\n 'getPreprEnvironmentSegments'\n );\n }\n\n try {\n const response = await fetch(token, {\n headers: {\n 'User-Agent': `Prepr-Preview-Bar/${getPackageVersion()}`,\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: JSON.stringify({\n query: `{\n _Segments {\n _id\n name\n }\n }`,\n }),\n });\n\n if (!response.ok) {\n throw new PreprError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'HTTP_ERROR',\n 'getPreprEnvironmentSegments'\n );\n }\n\n const json = await response.json();\n\n if (!json || !json.data || !json.data._Segments) {\n throw new PreprError(\n 'Invalid response format from Prepr API',\n 'INVALID_RESPONSE',\n 'getPreprEnvironmentSegments'\n );\n }\n\n return json.data._Segments as PreprSegment[];\n } catch (error) {\n if (error instanceof PreprError) {\n throw error;\n }\n throw new PreprError(\n 'Failed to fetch segments from Prepr API',\n 'FETCH_ERROR',\n 'getPreprEnvironmentSegments',\n error instanceof Error ? error : new Error(String(error))\n );\n }\n}\n\n/**\n * Fetches all the necessary toolbar props for Pages directory\n * @param token Prepr GraphQL URL with scope 'segments'\n * @param context The Next.js context object from getServerSideProps\n * @returns Object with activeSegment, activeVariant and data\n */\nexport async function getToolbarProps(\n token: string,\n context: GetServerSidePropsContext | GetStaticPropsContext\n): Promise<PreprToolbarProps> {\n let data: PreprSegment[] = [];\n let activeSegment: string | null = null;\n let activeVariant: string | null = null;\n\n // Prevent unnecessary function calling in production\n if (isPreviewMode()) {\n try {\n data = await getPreprEnvironmentSegments(token);\n activeSegment = getActiveSegment(context);\n activeVariant = getActiveVariant(context);\n } catch (error) {\n // In preview mode, we should still return props even if API fails\n console.error('Failed to fetch toolbar props:', error);\n // Return empty data to prevent toolbar from crashing\n data = [];\n }\n }\n\n return {\n activeSegment,\n activeVariant,\n data,\n };\n}\n\n/**\n * Alias for getToolbarProps for consistency with App Router API\n */\nexport const getPreviewBarProps = getToolbarProps;\n\nfunction getPackageVersion() {\n return pjson.version;\n}\n\n// Re-export the middleware for convenience\nexport { default as createPreprMiddleware } from '../../middleware';\n"]}
|