{"version":3,"file":"createCookieStorageAdapterFromNextServerContext.mjs","sources":["../../../src/utils/createCookieStorageAdapterFromNextServerContext.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { NextResponse } from 'next/server.js';\nimport { AmplifyServerContextError, } from 'aws-amplify/adapter-core/internals';\nimport { isServerSideAuthAllowedCookie } from '../auth/utils';\nimport { ensureEncodedForJSCookie, serializeCookie } from './cookie';\nexport const DATE_IN_THE_PAST = new Date(0);\nexport const createCookieStorageAdapterFromNextServerContext = async (context, ignoreNonServerSideCookies = false) => {\n    const { request: req, response: res } = context;\n    // When the server context is from `getServerSideProps`, the `req` is an instance\n    // of IncomingMessage, and the `res` is an instance of ServerResponse.\n    // We cannot import these two classes here from `http` as it breaks in Next\n    // Edge Runtime. Hence, we check the methods that we need to use for creating\n    // cookie adapter.\n    if (req &&\n        res &&\n        Object.prototype.toString.call(req.cookies) === '[object Object]' &&\n        typeof res.setHeader === 'function') {\n        return createCookieStorageAdapterFromGetServerSidePropsContext(req, res, ignoreNonServerSideCookies);\n    }\n    const { request, response } = context;\n    // When the server context is from `middleware`, the `request` is an instance\n    // of `NextRequest`.\n    // When the server context is from a route handler, the `request` is an `Proxy`\n    // wrapped `Request`.\n    // The `NextRequest` and the `Proxy` are sharing the same interface by Next\n    // implementation. So we don't need to detect the difference.\n    if (request && response) {\n        if (response instanceof NextResponse) {\n            return createCookieStorageAdapterFromNextRequestAndNextResponse(request, response, ignoreNonServerSideCookies);\n        }\n        else {\n            return createCookieStorageAdapterFromNextRequestAndHttpResponse(request, response, ignoreNonServerSideCookies);\n        }\n    }\n    const { cookies } = context;\n    if (typeof cookies === 'function') {\n        return createCookieStorageAdapterFromNextCookies(cookies, ignoreNonServerSideCookies);\n    }\n    // This should not happen normally.\n    throw new AmplifyServerContextError({\n        message: 'Attempted to create cookie storage adapter from an unsupported Next.js server context.',\n    });\n};\nconst createCookieStorageAdapterFromNextRequestAndNextResponse = (request, response, ignoreNonServerSideCookies) => {\n    const readonlyCookieStore = request.cookies;\n    const mutableCookieStore = response.cookies;\n    return {\n        get(name) {\n            return readonlyCookieStore.get(ensureEncodedForJSCookie(name));\n        },\n        getAll: readonlyCookieStore.getAll.bind(readonlyCookieStore),\n        set(name, value, options) {\n            if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {\n                return;\n            }\n            mutableCookieStore.set(ensureEncodedForJSCookie(name), value, options);\n        },\n        delete(name) {\n            if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {\n                return;\n            }\n            mutableCookieStore.delete(ensureEncodedForJSCookie(name));\n        },\n    };\n};\nconst createCookieStorageAdapterFromNextRequestAndHttpResponse = (request, response, ignoreNonServerSideCookies) => {\n    const readonlyCookieStore = request.cookies;\n    const mutableCookieStore = createMutableCookieStoreFromHeaders(response.headers, ignoreNonServerSideCookies);\n    return {\n        get(name) {\n            return readonlyCookieStore.get(ensureEncodedForJSCookie(name));\n        },\n        getAll: readonlyCookieStore.getAll.bind(readonlyCookieStore),\n        ...mutableCookieStore,\n    };\n};\nconst createCookieStorageAdapterFromNextCookies = async (cookies, ignoreNonServerSideCookies) => {\n    const cookieStore = await cookies();\n    // When Next cookies() is called in a server component, it returns a readonly\n    // cookie store. Hence calling set and delete throws an error. However,\n    // cookies() returns a mutable cookie store when called in a server action.\n    // We have no way to detect which one is returned, so we try to call set and delete\n    // and safely ignore the error if it is thrown.\n    const setFunc = (name, value, options) => {\n        if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {\n            return;\n        }\n        try {\n            cookieStore.set(ensureEncodedForJSCookie(name), value, options);\n        }\n        catch {\n            // no-op\n        }\n    };\n    const deleteFunc = name => {\n        if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {\n            return;\n        }\n        try {\n            cookieStore.delete(ensureEncodedForJSCookie(name));\n        }\n        catch {\n            // no-op\n        }\n    };\n    return {\n        get(name) {\n            return cookieStore.get(ensureEncodedForJSCookie(name));\n        },\n        getAll: cookieStore.getAll.bind(cookieStore),\n        set: setFunc,\n        delete: deleteFunc,\n    };\n};\nconst createCookieStorageAdapterFromGetServerSidePropsContext = (request, response, ignoreNonServerSideCookies) => {\n    const cookiesMap = { ...request.cookies };\n    const allCookies = Object.entries(cookiesMap).map(([name, value]) => ({\n        name,\n        value,\n    }));\n    return {\n        get(name) {\n            const value = cookiesMap[ensureEncodedForJSCookie(name)];\n            return value\n                ? {\n                    name,\n                    value,\n                }\n                : undefined;\n        },\n        getAll() {\n            return allCookies;\n        },\n        set(name, value, options) {\n            if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {\n                return;\n            }\n            const encodedName = ensureEncodedForJSCookie(name);\n            const existingValues = getExistingSetCookieValues(response.getHeader('Set-Cookie'));\n            // if the cookies have already been set, we don't need to set them again.\n            if (existingValues.findIndex(cookieValue => cookieValue.startsWith(`${encodedName}=`) &&\n                !cookieValue.startsWith(`${encodedName}=;`)) > -1) {\n                return;\n            }\n            response.appendHeader('Set-Cookie', serializeCookie(name, value, options));\n        },\n        delete(name) {\n            if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {\n                return;\n            }\n            const encodedName = ensureEncodedForJSCookie(name);\n            const setCookieValue = `${encodedName}=;Expires=${DATE_IN_THE_PAST.toUTCString()}`;\n            const existingValues = getExistingSetCookieValues(response.getHeader('Set-Cookie'));\n            // if the value for cookie deletion is already in the Set-Cookie header, we\n            // don't need to add the deletion value again.\n            if (existingValues.includes(setCookieValue)) {\n                return;\n            }\n            response.appendHeader('Set-Cookie', setCookieValue);\n        },\n    };\n};\nconst createMutableCookieStoreFromHeaders = (headers, ignoreNonServerSideCookies) => {\n    const setFunc = (name, value, options) => {\n        if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {\n            return;\n        }\n        headers.append('Set-Cookie', serializeCookie(name, value, options));\n    };\n    const deleteFunc = name => {\n        if (shouldIgnoreCookie(ignoreNonServerSideCookies, name)) {\n            return;\n        }\n        headers.append('Set-Cookie', `${ensureEncodedForJSCookie(name)}=;Expires=${DATE_IN_THE_PAST.toUTCString()}`);\n    };\n    return {\n        set: setFunc,\n        delete: deleteFunc,\n    };\n};\nconst getExistingSetCookieValues = (values) => values === undefined ? [] : Array.isArray(values) ? values : [String(values)];\nconst shouldIgnoreCookie = (ignoreNonServerSideCookies, cookieName) => ignoreNonServerSideCookies && !isServerSideAuthAllowedCookie(cookieName);\n"],"names":[],"mappings":";;;;;;;;AAAA;AACA;AAKY,MAAC,gBAAgB,GAAG,IAAI,IAAI,CAAC,CAAC;AAC9B,MAAC,+CAA+C,GAAG,OAAO,OAAO,EAAE,0BAA0B,GAAG,KAAK,KAAK;AACtH,IAAI,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,GAAG,OAAO;AACnD;AACA;AACA;AACA;AACA;AACA,IAAI,IAAI,GAAG;AACX,QAAQ,GAAG;AACX,QAAQ,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,iBAAiB;AACzE,QAAQ,OAAO,GAAG,CAAC,SAAS,KAAK,UAAU,EAAE;AAC7C,QAAQ,OAAO,uDAAuD,CAAC,GAAG,EAAE,GAAG,EAAE,0BAA0B,CAAC;AAC5G,IAAI;AACJ,IAAI,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO;AACzC;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,IAAI,OAAO,IAAI,QAAQ,EAAE;AAC7B,QAAQ,IAAI,QAAQ,YAAY,YAAY,EAAE;AAC9C,YAAY,OAAO,wDAAwD,CAAC,OAAO,EAAE,QAAQ,EAAE,0BAA0B,CAAC;AAC1H,QAAQ;AACR,aAAa;AACb,YAAY,OAAO,wDAAwD,CAAC,OAAO,EAAE,QAAQ,EAAE,0BAA0B,CAAC;AAC1H,QAAQ;AACR,IAAI;AACJ,IAAI,MAAM,EAAE,OAAO,EAAE,GAAG,OA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