@enonic/nextjs-adapter 0.13.0 → 1.0.0-RC1

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.
@@ -0,0 +1,314 @@
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 __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ var path_1 = __importDefault(require("path"));
43
+ var lru_cache_1 = __importDefault(require("lru-cache"));
44
+ var memoryCache;
45
+ var ClearableFileCache = /** @class */ (function () {
46
+ function ClearableFileCache(ctx) {
47
+ this.fs = ctx.fs;
48
+ this.flushToDisk = ctx.flushToDisk;
49
+ this.serverDistDir = ctx.serverDistDir;
50
+ this.appDir = !!ctx._appDir;
51
+ if (ctx.maxMemoryCacheSize && !memoryCache) {
52
+ var config = {
53
+ max: ctx.maxMemoryCacheSize,
54
+ maxSize: 10 * ctx.maxMemoryCacheSize,
55
+ sizeCalculation: function (_a) {
56
+ var _b;
57
+ var value = _a.value;
58
+ if (!value) {
59
+ return 25;
60
+ }
61
+ else if (value.kind === 'REDIRECT') {
62
+ return JSON.stringify(value.props).length;
63
+ }
64
+ else if (value.kind === 'IMAGE') {
65
+ throw new Error('invariant image should not be incremental-cache');
66
+ }
67
+ else if (value.kind === 'FETCH') {
68
+ return JSON.stringify(value.data || '').length;
69
+ }
70
+ else if (value.kind === 'ROUTE') {
71
+ return value.body.length;
72
+ }
73
+ // rough estimate of size of cache value
74
+ return (value.html.length + (((_b = JSON.stringify(value.pageData)) === null || _b === void 0 ? void 0 : _b.length) || 0));
75
+ },
76
+ };
77
+ memoryCache = new lru_cache_1.default(config);
78
+ }
79
+ }
80
+ ClearableFileCache.prototype.clear = function () {
81
+ memoryCache === null || memoryCache === void 0 ? void 0 : memoryCache.clear();
82
+ };
83
+ ClearableFileCache.prototype.delete = function (path) {
84
+ return memoryCache === null || memoryCache === void 0 ? void 0 : memoryCache.delete(path);
85
+ };
86
+ ClearableFileCache.prototype.get = function (key, fetchCache) {
87
+ return __awaiter(this, void 0, void 0, function () {
88
+ var data, filePath, fileData, mtime, meta, _a, _b, cacheEntry, _1, _c, filePath, isAppPath, fileData, mtime, lastModified, pageData, _d, _e, _f, _g, _h, _j, _k, _2;
89
+ return __generator(this, function (_l) {
90
+ switch (_l.label) {
91
+ case 0:
92
+ data = memoryCache === null || memoryCache === void 0 ? void 0 : memoryCache.get(key);
93
+ if (!(!data && process.env.NEXT_RUNTIME !== 'edge')) return [3 /*break*/, 21];
94
+ _l.label = 1;
95
+ case 1:
96
+ _l.trys.push([1, 6, , 7]);
97
+ return [4 /*yield*/, this.getFsPath({
98
+ pathname: "".concat(key, ".body"),
99
+ appDir: true,
100
+ })];
101
+ case 2:
102
+ filePath = (_l.sent()).filePath;
103
+ return [4 /*yield*/, this.fs.readFile(filePath)];
104
+ case 3:
105
+ fileData = _l.sent();
106
+ return [4 /*yield*/, this.fs.stat(filePath)];
107
+ case 4:
108
+ mtime = (_l.sent()).mtime;
109
+ _b = (_a = JSON).parse;
110
+ return [4 /*yield*/, this.fs.readFile(filePath.replace(/\.body$/, '.meta'))];
111
+ case 5:
112
+ meta = _b.apply(_a, [_l.sent()]);
113
+ cacheEntry = {
114
+ lastModified: mtime.getTime(),
115
+ value: {
116
+ kind: 'ROUTE',
117
+ body: Buffer.from(fileData),
118
+ headers: meta.headers,
119
+ status: meta.status,
120
+ },
121
+ };
122
+ return [2 /*return*/, cacheEntry];
123
+ case 6:
124
+ _1 = _l.sent();
125
+ return [3 /*break*/, 7];
126
+ case 7:
127
+ _l.trys.push([7, 20, , 21]);
128
+ return [4 /*yield*/, this.getFsPath({
129
+ pathname: fetchCache ? key : "".concat(key, ".html"),
130
+ fetchCache: fetchCache,
131
+ })];
132
+ case 8:
133
+ _c = _l.sent(), filePath = _c.filePath, isAppPath = _c.isAppPath;
134
+ return [4 /*yield*/, this.fs.readFile(filePath)];
135
+ case 9:
136
+ fileData = _l.sent();
137
+ return [4 /*yield*/, this.fs.stat(filePath)];
138
+ case 10:
139
+ mtime = (_l.sent()).mtime;
140
+ if (!fetchCache) return [3 /*break*/, 11];
141
+ lastModified = mtime.getTime();
142
+ data = {
143
+ lastModified: lastModified,
144
+ value: JSON.parse(fileData),
145
+ };
146
+ return [3 /*break*/, 19];
147
+ case 11:
148
+ if (!isAppPath) return [3 /*break*/, 14];
149
+ _f = (_e = this.fs).readFile;
150
+ return [4 /*yield*/, this.getFsPath({ pathname: "".concat(key, ".rsc"), appDir: true })];
151
+ case 12: return [4 /*yield*/, _f.apply(_e, [(_l.sent()).filePath])];
152
+ case 13:
153
+ _d = _l.sent();
154
+ return [3 /*break*/, 18];
155
+ case 14:
156
+ _h = (_g = JSON).parse;
157
+ _k = (_j = this.fs).readFile;
158
+ return [4 /*yield*/, this.getFsPath({
159
+ pathname: "".concat(key, ".json"),
160
+ appDir: false,
161
+ })];
162
+ case 15:
163
+ // eslint-disable-next-line @typescript-eslint/await-thenable
164
+ return [4 /*yield*/, (_l.sent()).filePath];
165
+ case 16: return [4 /*yield*/, _k.apply(_j, [
166
+ // eslint-disable-next-line @typescript-eslint/await-thenable
167
+ _l.sent()])];
168
+ case 17:
169
+ _d = _h.apply(_g, [_l.sent()]);
170
+ _l.label = 18;
171
+ case 18:
172
+ pageData = _d;
173
+ data = {
174
+ lastModified: mtime.getTime(),
175
+ value: {
176
+ kind: 'PAGE',
177
+ html: fileData,
178
+ pageData: pageData,
179
+ },
180
+ };
181
+ _l.label = 19;
182
+ case 19:
183
+ if (data) {
184
+ memoryCache === null || memoryCache === void 0 ? void 0 : memoryCache.set(key, data);
185
+ }
186
+ return [3 /*break*/, 21];
187
+ case 20:
188
+ _2 = _l.sent();
189
+ return [3 /*break*/, 21];
190
+ case 21: return [2 /*return*/, data || null];
191
+ }
192
+ });
193
+ });
194
+ };
195
+ ClearableFileCache.prototype.set = function (key, data) {
196
+ return __awaiter(this, void 0, void 0, function () {
197
+ var filePath, isAppPath, htmlPath, _a, _b, filePath;
198
+ return __generator(this, function (_c) {
199
+ switch (_c.label) {
200
+ case 0:
201
+ memoryCache === null || memoryCache === void 0 ? void 0 : memoryCache.set(key, {
202
+ value: data,
203
+ lastModified: Date.now(),
204
+ });
205
+ if (!this.flushToDisk)
206
+ return [2 /*return*/];
207
+ if (!((data === null || data === void 0 ? void 0 : data.kind) === 'ROUTE')) return [3 /*break*/, 5];
208
+ return [4 /*yield*/, this.getFsPath({
209
+ pathname: "".concat(key, ".body"),
210
+ appDir: true,
211
+ })];
212
+ case 1:
213
+ filePath = (_c.sent()).filePath;
214
+ return [4 /*yield*/, this.fs.mkdir(path_1.default.dirname(filePath))];
215
+ case 2:
216
+ _c.sent();
217
+ return [4 /*yield*/, this.fs.writeFile(filePath, data.body)];
218
+ case 3:
219
+ _c.sent();
220
+ return [4 /*yield*/, this.fs.writeFile(filePath.replace(/\.body$/, '.meta'), JSON.stringify({ headers: data.headers, status: data.status }))];
221
+ case 4:
222
+ _c.sent();
223
+ return [2 /*return*/];
224
+ case 5:
225
+ if (!((data === null || data === void 0 ? void 0 : data.kind) === 'PAGE')) return [3 /*break*/, 11];
226
+ isAppPath = typeof data.pageData === 'string';
227
+ return [4 /*yield*/, this.getFsPath({
228
+ pathname: "".concat(key, ".html"),
229
+ appDir: isAppPath,
230
+ })];
231
+ case 6:
232
+ htmlPath = (_c.sent()).filePath;
233
+ return [4 /*yield*/, this.fs.mkdir(path_1.default.dirname(htmlPath))];
234
+ case 7:
235
+ _c.sent();
236
+ return [4 /*yield*/, this.fs.writeFile(htmlPath, data.html)];
237
+ case 8:
238
+ _c.sent();
239
+ _b = (_a = this.fs).writeFile;
240
+ return [4 /*yield*/, this.getFsPath({
241
+ pathname: "".concat(key, ".").concat(isAppPath ? 'rsc' : 'json'),
242
+ appDir: isAppPath,
243
+ })];
244
+ case 9: return [4 /*yield*/, _b.apply(_a, [(_c.sent()).filePath,
245
+ isAppPath ? data.pageData : JSON.stringify(data.pageData)])];
246
+ case 10:
247
+ _c.sent();
248
+ return [3 /*break*/, 15];
249
+ case 11:
250
+ if (!((data === null || data === void 0 ? void 0 : data.kind) === 'FETCH')) return [3 /*break*/, 15];
251
+ return [4 /*yield*/, this.getFsPath({
252
+ pathname: key,
253
+ fetchCache: true,
254
+ })];
255
+ case 12:
256
+ filePath = (_c.sent()).filePath;
257
+ return [4 /*yield*/, this.fs.mkdir(path_1.default.dirname(filePath))];
258
+ case 13:
259
+ _c.sent();
260
+ return [4 /*yield*/, this.fs.writeFile(filePath, JSON.stringify(data))];
261
+ case 14:
262
+ _c.sent();
263
+ _c.label = 15;
264
+ case 15: return [2 /*return*/];
265
+ }
266
+ });
267
+ });
268
+ };
269
+ ClearableFileCache.prototype.getFsPath = function (_a) {
270
+ var pathname = _a.pathname, appDir = _a.appDir, fetchCache = _a.fetchCache;
271
+ return __awaiter(this, void 0, void 0, function () {
272
+ var isAppPath, filePath, err_1;
273
+ return __generator(this, function (_b) {
274
+ switch (_b.label) {
275
+ case 0:
276
+ if (fetchCache) {
277
+ // we store in .next/cache/fetch-cache so it can be persisted
278
+ // across deploys
279
+ return [2 /*return*/, {
280
+ filePath: path_1.default.join(this.serverDistDir, '..', 'cache', 'fetch-cache', pathname),
281
+ isAppPath: false,
282
+ }];
283
+ }
284
+ isAppPath = false;
285
+ filePath = path_1.default.join(this.serverDistDir, 'pages', pathname);
286
+ if (!this.appDir || appDir === false)
287
+ return [2 /*return*/, {
288
+ filePath: filePath,
289
+ isAppPath: isAppPath,
290
+ }];
291
+ _b.label = 1;
292
+ case 1:
293
+ _b.trys.push([1, 3, , 4]);
294
+ return [4 /*yield*/, this.fs.readFile(filePath)];
295
+ case 2:
296
+ _b.sent();
297
+ return [2 /*return*/, {
298
+ filePath: filePath,
299
+ isAppPath: isAppPath,
300
+ }];
301
+ case 3:
302
+ err_1 = _b.sent();
303
+ return [2 /*return*/, {
304
+ filePath: path_1.default.join(this.serverDistDir, 'app', pathname),
305
+ isAppPath: true,
306
+ }];
307
+ case 4: return [2 /*return*/];
308
+ }
309
+ });
310
+ });
311
+ };
312
+ return ClearableFileCache;
313
+ }());
314
+ exports.default = ClearableFileCache;
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __generator = (this && this.__generator) || function (thisArg, body) {
35
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
+ function verb(n) { return function (v) { return step([n, v]); }; }
38
+ function step(op) {
39
+ if (f) throw new TypeError("Generator is already executing.");
40
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
41
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
42
+ if (y = 0, t) op = [op[0] & 2, t.value];
43
+ switch (op[0]) {
44
+ case 0: case 1: t = op; break;
45
+ case 4: _.label++; return { value: op[1], done: false };
46
+ case 5: _.label++; y = op[1]; op = [0]; continue;
47
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
+ default:
49
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
+ if (t[2]) _.ops.pop();
54
+ _.trys.pop(); continue;
55
+ }
56
+ op = body.call(thisArg, _);
57
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
+ }
60
+ };
61
+ Object.defineProperty(exports, "__esModule", { value: true });
62
+ exports.purgeCache = void 0;
63
+ var fs = __importStar(require("fs"));
64
+ var getCacheHandler = function (cache) {
65
+ return cache.cacheHandler;
66
+ };
67
+ var purgeCache = function (cache, pathname) { return __awaiter(void 0, void 0, void 0, function () {
68
+ return __generator(this, function (_a) {
69
+ if (pathname) {
70
+ return [2 /*return*/, purgePath(cache, pathname)];
71
+ }
72
+ else {
73
+ return [2 /*return*/, purgeAll(cache)];
74
+ }
75
+ return [2 /*return*/];
76
+ });
77
+ }); };
78
+ exports.purgeCache = purgeCache;
79
+ var purgePath = function (cache, pathname) { return __awaiter(void 0, void 0, void 0, function () {
80
+ var handler, fullPathname;
81
+ return __generator(this, function (_a) {
82
+ switch (_a.label) {
83
+ case 0:
84
+ handler = getCacheHandler(cache);
85
+ return [4 /*yield*/, handler.getFsPath({ pathname: pathname })];
86
+ case 1:
87
+ fullPathname = _a.sent();
88
+ try {
89
+ /* Delete entry in cache */
90
+ handler.delete(pathname);
91
+ /* Delete files from disc */
92
+ fs.unlinkSync("".concat(fullPathname, ".html"));
93
+ fs.unlinkSync("".concat(fullPathname, ".json"));
94
+ console.info("\nCache deleted for '".concat(fullPathname, "'\n"));
95
+ }
96
+ catch (err) {
97
+ console.error("Could not delete cache of '".concat(fullPathname, "':"), err);
98
+ }
99
+ return [2 /*return*/];
100
+ }
101
+ });
102
+ }); };
103
+ var purgeAll = function (cache) { return __awaiter(void 0, void 0, void 0, function () {
104
+ var handler, pagesRoot, err_1;
105
+ return __generator(this, function (_a) {
106
+ switch (_a.label) {
107
+ case 0:
108
+ handler = getCacheHandler(cache);
109
+ _a.label = 1;
110
+ case 1:
111
+ _a.trys.push([1, 3, , 4]);
112
+ /* Purge cache */
113
+ handler.clear();
114
+ return [4 /*yield*/, handler.getFsPath({ pathname: '' })];
115
+ case 2:
116
+ pagesRoot = (_a.sent()).filePath;
117
+ if (fs.existsSync(pagesRoot)) {
118
+ fs.rmSync(pagesRoot, { recursive: true });
119
+ }
120
+ console.info('\nCache was successfully purged\n');
121
+ return [3 /*break*/, 4];
122
+ case 3:
123
+ err_1 = _a.sent();
124
+ console.error('Could not purge cache:', err_1);
125
+ return [3 /*break*/, 4];
126
+ case 4: return [2 /*return*/];
127
+ }
128
+ });
129
+ }); };
@@ -0,0 +1,114 @@
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 __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.withEnonicCache = exports.PURGE_CACHE_URL = void 0;
43
+ var http_1 = require("http");
44
+ var cache_1 = require("./cache");
45
+ var path_1 = __importDefault(require("path"));
46
+ var host = process.env.HOST || '127.0.0.1';
47
+ var dev = process.env.NODE_ENV !== 'production';
48
+ var port = process.env.PORT && parseInt(process.env.PORT, 10) || (dev ? 3000 : 4242);
49
+ exports.PURGE_CACHE_URL = '/_/enonic/cache/purge';
50
+ var withEnonicCache = function (config) {
51
+ var exp = config.experimental || {};
52
+ exp.isrMemoryCacheSize = exp.isrMemoryCacheSize || 1000000;
53
+ exp.incrementalCacheHandlerPath = path_1.default.resolve(__dirname, 'ClearableFileCache.js');
54
+ config.experimental = exp;
55
+ return config;
56
+ };
57
+ exports.withEnonicCache = withEnonicCache;
58
+ // Not typed to prevent collision of local types with end-user ones
59
+ exports.default = (function (next) { return __awaiter(void 0, void 0, void 0, function () {
60
+ var nextServer, nextHandler;
61
+ return __generator(this, function (_a) {
62
+ switch (_a.label) {
63
+ case 0:
64
+ nextServer = next({ dev: dev });
65
+ nextHandler = nextServer.getRequestHandler();
66
+ return [4 /*yield*/, nextServer.prepare().then(function () {
67
+ var nextNodeServer = nextServer['server'];
68
+ var opts = nextNodeServer['serverOptions'].conf;
69
+ var purgeUrl = ((opts === null || opts === void 0 ? void 0 : opts.basePath) || '') + exports.PURGE_CACHE_URL;
70
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
71
+ var server = (0, http_1.createServer)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
72
+ var parsedUrl, tokenParam, cache, pathParam;
73
+ return __generator(this, function (_a) {
74
+ switch (_a.label) {
75
+ case 0:
76
+ parsedUrl = new URL("http://".concat(host, ":").concat(port).concat(req.url || ''));
77
+ if (!(parsedUrl.pathname !== purgeUrl)) return [3 /*break*/, 2];
78
+ return [4 /*yield*/, nextHandler(req, res)];
79
+ case 1:
80
+ _a.sent();
81
+ return [3 /*break*/, 4];
82
+ case 2:
83
+ tokenParam = parsedUrl.searchParams.get('token');
84
+ if (tokenParam !== process.env.API_TOKEN) {
85
+ // XP hijacks 401 to show login page, so send 407 instead
86
+ res.statusCode = 407;
87
+ res.end(JSON.stringify({ message: 'Invalid token' }));
88
+ return [2 /*return*/];
89
+ }
90
+ cache = nextNodeServer.getIncrementalCache({
91
+ requestHeaders: Object.assign({}, req.headers),
92
+ });
93
+ pathParam = parsedUrl.searchParams.get('path') || undefined;
94
+ return [4 /*yield*/, (0, cache_1.purgeCache)(cache, pathParam)];
95
+ case 3:
96
+ _a.sent();
97
+ res.setHeader('Content-Type', 'application/json');
98
+ res.end(JSON.stringify({ purged: true }));
99
+ _a.label = 4;
100
+ case 4: return [2 /*return*/];
101
+ }
102
+ });
103
+ }); }).listen(port, host, function () {
104
+ console.info("Server ready on ".concat(host, ":").concat(port));
105
+ }).on('error', function (e) {
106
+ console.error('Server error:', e);
107
+ server.close();
108
+ });
109
+ return nextServer;
110
+ })];
111
+ case 1: return [2 /*return*/, _a.sent()];
112
+ }
113
+ });
114
+ }); });
package/utils.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Import config values from .env, .env.development and .env.production */
2
- import { Context, MinimalContext } from './guillotine/fetchContent';
2
+ import { MinimalContext } from './guillotine/fetchContent';
3
3
  export declare const IS_DEV_MODE: boolean;
4
4
  /** Optional utility value - defining in one place the name of the target app (the app that defines the content types, the app name is therefore part of the content type strings used both in typeselector and in query introspections) */
5
5
  export declare const APP_NAME: string;
@@ -8,9 +8,7 @@ export declare const APP_NAME_UNDERSCORED: string;
8
8
  /** Optional utility value - derived from APP_NAME, only with dashes instead of dots */
9
9
  export declare const APP_NAME_DASHED: string;
10
10
  export declare const SITE_KEY: string;
11
- export declare const FROM_XP_PARAM = "__fromxp__";
12
11
  export declare const XP_BASE_URL_HEADER = "xpbaseurl";
13
- export declare const COMPONENT_SUBPATH_HEADER = "xp-component-path";
14
12
  export declare const RENDER_MODE_HEADER = "content-studio-mode";
15
13
  export declare const JSESSIONID_HEADER = "jsessionid";
16
14
  export declare const PORTAL_COMPONENT_ATTRIBUTE = "data-portal-component-type";
@@ -40,11 +38,9 @@ export declare enum XP_COMPONENT_TYPE {
40
38
  FRAGMENT = "fragment",
41
39
  PAGE = "page"
42
40
  }
43
- /** Returns true if the context object (from next.js in [[...contentPath]].jsx ) stems from a request that comes from XP in a CS-preview, i.e. has the URI param FROM_XP_PARAM (defined as '__fromXp__' above).
44
- * False if no context, query or FROM_XP_PARAM param */
45
- export declare const isRequestFromXP: (context?: Context) => boolean;
46
- export declare const getXPRequestType: (context?: Context) => XP_REQUEST_TYPE;
41
+ export declare const getRenderMode: (context?: MinimalContext) => RENDER_MODE;
47
42
  export declare function getContentApiUrl(context?: MinimalContext): string;
43
+ export declare function getJsessionHeaders(context?: MinimalContext): Object;
48
44
  export declare const getXpBaseUrl: (context?: MinimalContext) => string;
49
45
  export declare const commonChars: (s1?: string, s2?: string) => string;
50
46
  export declare const sanitizeGraphqlName: (text: string) => string;
@@ -54,12 +50,7 @@ declare const adapterConstants: {
54
50
  APP_NAME_UNDERSCORED: string;
55
51
  APP_NAME_DASHED: string;
56
52
  SITE_KEY: string;
57
- FROM_XP_PARAM: string;
58
- COMPONENT_SUBPATH_HEADER: string;
59
53
  PORTAL_COMPONENT_ATTRIBUTE: string;
60
54
  PORTAL_REGION_ATTRIBUTE: string;
61
- getXPRequestType: (context?: Context) => XP_REQUEST_TYPE;
62
- getSingleComponentPath: (context?: Context) => string | undefined;
63
- getRenderMode: (context?: MinimalContext) => RENDER_MODE;
64
55
  };
65
56
  export default adapterConstants;
package/utils.js CHANGED
@@ -12,9 +12,7 @@ export const APP_NAME_DASHED = (APP_NAME || '').replace(/\./g, '-');
12
12
  export const SITE_KEY = (process.env.SITE_KEY || process.env.NEXT_PUBLIC_SITE_KEY);
13
13
  // //////////////////////////////////////////////////////////////////////// Hardcode-able constants
14
14
  // URI parameter marking that a request is for a preview for CS. MUST MATCH THE VALUE OF 'FROM_XP_PARAM' on XP side.
15
- export const FROM_XP_PARAM = '__fromxp__';
16
15
  export const XP_BASE_URL_HEADER = 'xpbaseurl';
17
- export const COMPONENT_SUBPATH_HEADER = 'xp-component-path';
18
16
  export const RENDER_MODE_HEADER = 'content-studio-mode';
19
17
  export const JSESSIONID_HEADER = 'jsessionid';
20
18
  export const PORTAL_COMPONENT_ATTRIBUTE = 'data-portal-component-type';
@@ -49,31 +47,25 @@ export var XP_COMPONENT_TYPE;
49
47
  XP_COMPONENT_TYPE["FRAGMENT"] = "fragment";
50
48
  XP_COMPONENT_TYPE["PAGE"] = "page";
51
49
  })(XP_COMPONENT_TYPE || (XP_COMPONENT_TYPE = {}));
52
- /** Returns true if the context object (from next.js in [[...contentPath]].jsx ) stems from a request that comes from XP in a CS-preview, i.e. has the URI param FROM_XP_PARAM (defined as '__fromXp__' above).
53
- * False if no context, query or FROM_XP_PARAM param */
54
- export const isRequestFromXP = (context) => {
55
- return !!getXPRequestType(context);
56
- };
57
- export const getXPRequestType = (context) => {
58
- var _a;
59
- const headerValue = (((_a = context === null || context === void 0 ? void 0 : context.req) === null || _a === void 0 ? void 0 : _a.headers) || {})[FROM_XP_PARAM];
60
- const enumValue = XP_REQUEST_TYPE[headerValue === null || headerValue === void 0 ? void 0 : headerValue.toUpperCase()];
61
- return enumValue || XP_REQUEST_TYPE.PAGE; // need to have some defaults here in case of rendering without XP
62
- };
63
- const getRenderMode = (context) => {
50
+ export const getRenderMode = (context) => {
64
51
  var _a;
65
52
  const value = (((_a = context === null || context === void 0 ? void 0 : context.req) === null || _a === void 0 ? void 0 : _a.headers) || {})[RENDER_MODE_HEADER];
66
53
  const enumValue = RENDER_MODE[value === null || value === void 0 ? void 0 : value.toUpperCase()];
67
54
  return enumValue || RENDER_MODE[process.env.RENDER_MODE] || RENDER_MODE.NEXT;
68
55
  };
69
- const getSingleComponentPath = (context) => {
70
- var _a;
71
- return (((_a = context === null || context === void 0 ? void 0 : context.req) === null || _a === void 0 ? void 0 : _a.headers) || {})[COMPONENT_SUBPATH_HEADER];
72
- };
73
56
  export function getContentApiUrl(context) {
74
57
  const mode = getRenderMode(context);
75
58
  return mode === RENDER_MODE.NEXT ? CONTENT_API_MASTER : CONTENT_API_DRAFT;
76
59
  }
60
+ export function getJsessionHeaders(context) {
61
+ var _a;
62
+ const headers = {};
63
+ const jsessionid = (_a = context === null || context === void 0 ? void 0 : context.req) === null || _a === void 0 ? void 0 : _a.headers[JSESSIONID_HEADER];
64
+ if (jsessionid) {
65
+ headers['Cookie'] = `${JSESSIONID_HEADER}=${jsessionid}`;
66
+ }
67
+ return headers;
68
+ }
77
69
  /** For '<a href="..."' link values in props when clicking the link should navigate to an XP content item page
78
70
  * and the query returns the XP _path to the target content item:
79
71
  * When viewed directly, the header will have a `<base href='/' />` (see src/pages/_app.tsx), and when viewed through an
@@ -129,13 +121,8 @@ const adapterConstants = {
129
121
  APP_NAME_UNDERSCORED,
130
122
  APP_NAME_DASHED,
131
123
  SITE_KEY,
132
- FROM_XP_PARAM,
133
- COMPONENT_SUBPATH_HEADER,
134
124
  PORTAL_COMPONENT_ATTRIBUTE,
135
125
  PORTAL_REGION_ATTRIBUTE,
136
- getXPRequestType,
137
- getSingleComponentPath,
138
- getRenderMode,
139
126
  };
140
127
  // Verify required values
141
128
  const NOT_REQUIRED = ['IS_DEV_MODE'];