@born05/sveltekit-cache-control 1.5.1 → 1.5.3

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/index.js CHANGED
@@ -1,21 +1,5 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.createCacheControlResponse = createCacheControlResponse;
16
- exports.cacheControlHandle = cacheControlHandle;
17
- const ioredis_1 = __importDefault(require("ioredis"));
18
- const sveltekit_1 = require("@sentry/sveltekit");
1
+ import { captureException } from '@sentry/sveltekit';
2
+ import Redis from 'ioredis';
19
3
  const CACHE_STRATEGY_PRIVATE_ONLY = 'private-only';
20
4
  const CACHE_STRATEGY_PRIVATE_AND_PUBLIC = 'private-and-public';
21
5
  const CACHE_STRATEGY_FORCE_PUBLIC = 'force-public';
@@ -28,101 +12,109 @@ const DEFAULT_HEADER_OPTIONS = {
28
12
  etagCacheKey: 'cache-control-etag',
29
13
  noCacheSearchParams: ['preview'],
30
14
  };
31
- const DEFAULT_HANDLE_OPTIONS = Object.assign(Object.assign({}, DEFAULT_HEADER_OPTIONS), { routes: ['.*'], methods: ['GET'] });
15
+ const DEFAULT_HANDLE_OPTIONS = {
16
+ ...DEFAULT_HEADER_OPTIONS,
17
+ routes: ['.*'],
18
+ methods: ['GET'],
19
+ };
32
20
  let redis = null;
33
21
  if (process.env.REDIS_URL) {
34
22
  initRedis(process.env.REDIS_URL);
35
23
  }
36
24
  function initRedis(redisUrl) {
37
- redis = new ioredis_1.default(redisUrl);
25
+ redis = new Redis(redisUrl);
38
26
  redis.on('error', (error) => {
39
27
  console.error(error);
40
- (0, sveltekit_1.captureException)(error);
28
+ captureException(error);
41
29
  });
42
30
  redis.on('connect', () => {
43
31
  console.log('Redis connected');
44
32
  });
45
33
  }
46
- function createCacheControlResponse(redisUrl_1, opt_1, request_1) {
47
- return __awaiter(this, arguments, void 0, function* (redisUrl, opt, request, response = null) {
48
- const options = Object.assign(Object.assign({}, DEFAULT_HEADER_OPTIONS), opt);
49
- const headers = {};
50
- if (options.enabled) {
51
- if (!redis) {
52
- initRedis(redisUrl);
34
+ export async function createCacheControlResponse(redisUrl, opt, request, response = null) {
35
+ const options = {
36
+ ...DEFAULT_HEADER_OPTIONS,
37
+ ...opt,
38
+ };
39
+ const headers = {};
40
+ if (options.enabled) {
41
+ if (!redis) {
42
+ initRedis(redisUrl);
43
+ }
44
+ if (options.noCacheSearchParams.every((param) => !new URL(request.url).searchParams.has(param))) {
45
+ const joinParts = (p) => p.filter(Boolean).join(', ');
46
+ // Private only cache control
47
+ if (options.strategy === CACHE_STRATEGY_PRIVATE_ONLY ||
48
+ (options.strategy === CACHE_STRATEGY_PRIVATE_AND_PUBLIC &&
49
+ request.headers.has('Authorization'))) {
50
+ headers['Cache-Control'] = joinParts([
51
+ 'private',
52
+ options.maxAge !== null && `max-age=${options.maxAge}`,
53
+ ]);
53
54
  }
54
- if (options.noCacheSearchParams.every((param) => !new URL(request.url).searchParams.has(param))) {
55
- const joinParts = (p) => p.filter(Boolean).join(', ');
56
- // Private only cache control
57
- if (options.strategy === CACHE_STRATEGY_PRIVATE_ONLY ||
58
- (options.strategy === CACHE_STRATEGY_PRIVATE_AND_PUBLIC &&
59
- request.headers.has('Authorization'))) {
60
- headers['Cache-Control'] = joinParts([
61
- 'private',
62
- options.maxAge !== null && `max-age=${options.maxAge}`,
63
- ]);
64
- }
65
- // Private and public cache control (default)
66
- else if (options.strategy === CACHE_STRATEGY_PRIVATE_AND_PUBLIC) {
67
- headers['Cache-Control'] = joinParts([
68
- options.maxAge !== null && `max-age=${options.maxAge}`,
69
- options.sMaxAge !== null && `s-maxage=${options.sMaxAge}`,
70
- ]);
71
- }
72
- // Force public cache control
73
- else if (options.strategy === CACHE_STRATEGY_FORCE_PUBLIC) {
74
- headers['Cache-Control'] = joinParts([
75
- 'public',
76
- options.maxAge !== null && `max-age=${options.maxAge}`,
77
- options.sMaxAge !== null && `s-maxage=${options.sMaxAge}`,
78
- ]);
79
- }
80
- // No cache control
81
- else if (options.strategy === CACHE_STRATEGY_NO_CACHE) {
82
- headers['Cache-Control'] = 'no-cache';
83
- }
84
- if (options.etagCacheKey && redis) {
85
- const etag = yield redis.get(options.etagCacheKey);
86
- if (etag) {
87
- headers.ETag = etag;
88
- const requestEtag = request.headers.get('If-None-Match');
89
- if (requestEtag === etag) {
90
- return new Response(null, {
91
- status: 304,
92
- statusText: 'Not Modified',
93
- headers,
94
- });
95
- }
55
+ // Private and public cache control (default)
56
+ else if (options.strategy === CACHE_STRATEGY_PRIVATE_AND_PUBLIC) {
57
+ headers['Cache-Control'] = joinParts([
58
+ options.maxAge !== null && `max-age=${options.maxAge}`,
59
+ options.sMaxAge !== null && `s-maxage=${options.sMaxAge}`,
60
+ ]);
61
+ }
62
+ // Force public cache control
63
+ else if (options.strategy === CACHE_STRATEGY_FORCE_PUBLIC) {
64
+ headers['Cache-Control'] = joinParts([
65
+ 'public',
66
+ options.maxAge !== null && `max-age=${options.maxAge}`,
67
+ options.sMaxAge !== null && `s-maxage=${options.sMaxAge}`,
68
+ ]);
69
+ }
70
+ // No cache control
71
+ else if (options.strategy === CACHE_STRATEGY_NO_CACHE) {
72
+ headers['Cache-Control'] = 'no-cache';
73
+ }
74
+ if (options.etagCacheKey && redis) {
75
+ const etag = await redis.get(options.etagCacheKey);
76
+ if (etag) {
77
+ headers.ETag = etag;
78
+ const requestEtag = request.headers.get('If-None-Match');
79
+ if (requestEtag === etag) {
80
+ return new Response(null, {
81
+ status: 304,
82
+ statusText: 'Not Modified',
83
+ headers,
84
+ });
96
85
  }
97
86
  }
98
87
  }
99
88
  }
100
- const resp = !response
101
- ? new Response()
102
- : typeof response === 'function'
103
- ? yield response()
104
- : response;
105
- if (resp.status !== 200)
106
- return resp;
107
- Object.entries(headers).forEach(([key, value]) => {
108
- resp.headers.set(key, value);
109
- });
89
+ }
90
+ const resp = !response
91
+ ? new Response()
92
+ : typeof response === 'function'
93
+ ? await response()
94
+ : response;
95
+ if (resp.status !== 200)
110
96
  return resp;
97
+ Object.entries(headers).forEach(([key, value]) => {
98
+ resp.headers.set(key, value);
111
99
  });
100
+ return resp;
112
101
  }
113
- function cacheControlHandle(redisUrl, opt) {
114
- const options = Object.assign(Object.assign({}, DEFAULT_HANDLE_OPTIONS), opt);
102
+ export function cacheControlHandle(redisUrl, opt) {
103
+ const options = {
104
+ ...DEFAULT_HANDLE_OPTIONS,
105
+ ...opt,
106
+ };
115
107
  if (!options.enabled) {
116
- return (_a) => __awaiter(this, [_a], void 0, function* ({ event, resolve }) { return resolve(event); });
108
+ return async ({ event, resolve }) => resolve(event);
117
109
  }
118
110
  if (!redis) {
119
111
  initRedis(redisUrl);
120
112
  }
121
- return (_a) => __awaiter(this, [_a], void 0, function* ({ event, resolve }) {
113
+ return async ({ event, resolve }) => {
122
114
  if (options.methods.includes(event.request.method) &&
123
115
  options.routes.some((route) => new RegExp(route).test(event.url.pathname))) {
124
- return yield createCacheControlResponse(redisUrl, options, event.request, () => resolve(event));
116
+ return await createCacheControlResponse(redisUrl, options, event.request, () => resolve(event));
125
117
  }
126
118
  return resolve(event);
127
- });
119
+ };
128
120
  }
package/index.ts CHANGED
@@ -1,6 +1,9 @@
1
- import type { Handle } from '@sveltejs/kit';
2
- import Redis from 'ioredis';
3
1
  import { captureException } from '@sentry/sveltekit';
2
+ import type { sequence } from '@sveltejs/kit/hooks';
3
+ import Redis from 'ioredis';
4
+
5
+ type Handle = ReturnType<typeof sequence>;
6
+
4
7
 
5
8
  const CACHE_STRATEGY_PRIVATE_ONLY = 'private-only';
6
9
  const CACHE_STRATEGY_PRIVATE_AND_PUBLIC = 'private-and-public';
package/package.json CHANGED
@@ -34,5 +34,5 @@
34
34
  "@sentry/sveltekit": ">=7.0.0",
35
35
  "@sveltejs/kit": ">=1.0.0"
36
36
  },
37
- "version": "1.5.1"
37
+ "version": "1.5.3"
38
38
  }
package/tsconfig.json CHANGED
@@ -11,7 +11,7 @@
11
11
  // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
12
 
13
13
  /* Language and Environment */
14
- "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
14
+ "target": "es2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15
15
  // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
16
  // "jsx": "preserve", /* Specify what JSX code is generated. */
17
17
  // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
@@ -25,9 +25,9 @@
25
25
  // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
26
 
27
27
  /* Modules */
28
- "module": "commonjs" /* Specify what module code is generated. */,
28
+ "module": "es2020" /* Specify what module code is generated. */,
29
29
  // "rootDir": "./", /* Specify the root folder within your source files. */
30
- // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
30
+ "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
31
31
  // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
32
  // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
33
  // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */