@zappie/sdk 0.12.0 → 0.13.0
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/CHANGELOG.md +14 -0
- package/README.md +66 -4
- package/dist/config/index.d.ts +5 -1
- package/dist/debug.js +1 -1
- package/dist/index.js +1 -1
- package/dist/server/chosen-branch.js +24 -2
- package/dist/server/chosen-branch.js.map +1 -1
- package/dist/server/edge-cache.js +392 -0
- package/dist/server/edge-cache.js.map +6 -0
- package/dist/server/index.d.ts +160 -7
- package/dist/server/index.js +24 -0
- package/dist/server/index.js.map +1 -1
- package/dist/site-config/validate.js +8 -11
- package/dist/site-config/validate.js.map +1 -1
- package/dist/vite/index.d.ts +39 -4
- package/dist/vite/index.js +112 -7
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @zappie/sdk
|
|
2
2
|
|
|
3
|
+
## 0.13.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 846083d: A site Worker now answers from its own cache. `cachedApiFetch({ ctx })` from `@zappie/sdk/server` is a fetch for `createZappie` that keeps `GET /store` and `GET /menus` for as long as the API's `Cache-Control` says, answers a stale read at once and refreshes it after the response through `ctx.waitUntil`. Its key holds a hash of the publishable key, never the key. `cachePage(request, render, { ctx, deployId, branchCookie })` keeps anonymous documents, their `.data`, robots and the sitemap, keyed by URL, branch cookie, deploy and site. It renders afresh for drafts, reviews, previews, the closed state, any `Authorization` header or session cookie and anything but a `GET`, keeps only a cookie-free `200`, and gives each cached HTML page a new CSP nonce. `x-zappie-edge-cache` says how each response was answered. `openEdgeCache()` opens the Worker's own cache, because Workers for Platforms disables `caches.default`.
|
|
8
|
+
|
|
9
|
+
`loadStoreAndMenu` starts the menu read beside the store read for a branch named by slug once a store read in the same isolate has given that slug's ID, and its `cookie` option is now optional.
|
|
10
|
+
|
|
11
|
+
`@zappie/sdk/vite` adds `zappieWorker()`, which minifies the Worker, renders it with React's streaming renderer alone and sets `import.meta.env.ZAPPIE_DEPLOY_ID` for each build. `zappieSource` now pre-bundles every browser entry of `@zappie/sdk` and `@zappie/foundations` and scans `app/` on every dev server, so a new page never re-bundles and reloads a Studio preview.
|
|
12
|
+
|
|
13
|
+
`prerender` in `zappie.config.ts` did nothing, because Zappie hosting prerenders no page. `validateConfig` now warns `unused_setting` when it is set, and the type marks it deprecated.
|
|
14
|
+
|
|
15
|
+
The starter caches its pages and API reads in the Worker, reads the store and menu side by side, answers robots and the sitemap with a 5-minute shared lifetime, builds with `zappieWorker()` and drops `prerender`. Its server build is 214 KB instead of 715 KB. Set `ZAPPIE_EDGE_CACHE=off` to turn the cache off.
|
|
16
|
+
|
|
3
17
|
## 0.12.0
|
|
4
18
|
|
|
5
19
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -322,10 +322,72 @@ When the link, the cookie or the fallback names the branch by ID (`br_…`),
|
|
|
322
322
|
the menu read starts alongside the store read, so the page waits for one round
|
|
323
323
|
trip instead of two. You get the menu once the store confirms that branch,
|
|
324
324
|
with the same errors as `store.get` followed by `menu.get`. A branch named by
|
|
325
|
-
slug
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
325
|
+
slug starts early too once a store read in the same Worker isolate has given
|
|
326
|
+
that slug's ID. The first such request reads the menu after the store, because
|
|
327
|
+
the API takes branch IDs only. `cookie` is optional for a site that keeps no
|
|
328
|
+
branch cookie. `requestedBranch(request, options)` returns the raw value a
|
|
329
|
+
request names, link first, before you have the store.
|
|
330
|
+
|
|
331
|
+
### Edge cache in a site Worker
|
|
332
|
+
|
|
333
|
+
On Zappie hosting each site runs as a Worker in a Workers for Platforms
|
|
334
|
+
dispatch namespace. There `caches.default` is disabled, and each Worker's
|
|
335
|
+
`caches.open()` cache is its own. `@zappie/sdk/server` keeps two kinds of
|
|
336
|
+
response in that cache, through `openEdgeCache()`.
|
|
337
|
+
|
|
338
|
+
`cachedApiFetch({ ctx })` is a fetch for `createZappie` on the server. It keeps
|
|
339
|
+
`GET /store` and `GET /menus` for as long as the API's own `Cache-Control`
|
|
340
|
+
says (`s-maxage`, then `stale-while-revalidate`). A stale read answers at once
|
|
341
|
+
and refreshes after the response through `ctx.waitUntil`, with the menu's ETag.
|
|
342
|
+
Its key is the URL, the API version and a hash of the publishable key, never
|
|
343
|
+
the key itself. A customer's, cart's, order's or quote's call, and any call
|
|
344
|
+
signed in as a shopper or carrying a cookie, goes straight to the API.
|
|
345
|
+
|
|
346
|
+
`cachePage(request, render, { ctx, deployId, branchCookie })` answers a site
|
|
347
|
+
Worker's anonymous pages from the cache: documents, their `.data`, robots and
|
|
348
|
+
the sitemap, for as long as each response's `Cache-Control` says. Its key is
|
|
349
|
+
the full URL, the branch cookie's value, the deploy, and the site the host
|
|
350
|
+
names. It renders afresh for a request that isn't a `GET`, a draft, review or
|
|
351
|
+
preview, the closed state, an `Authorization` header and a session or sign-in
|
|
352
|
+
cookie. It keeps only a `200` that sets no cookie and isn't the closed page. A
|
|
353
|
+
cached HTML page gets a new CSP nonce in its policy and its markup for each
|
|
354
|
+
shopper. `x-zappie-edge-cache` says how each response was answered: `HIT`,
|
|
355
|
+
`STALE`, `MISS` or `BYPASS`.
|
|
356
|
+
|
|
357
|
+
```ts
|
|
358
|
+
import { cachePage, cachedApiFetch } from "@zappie/sdk/server";
|
|
359
|
+
|
|
360
|
+
const client = createZappie({
|
|
361
|
+
store,
|
|
362
|
+
key,
|
|
363
|
+
baseUrl,
|
|
364
|
+
fetch: cachedApiFetch({ ctx }),
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
export default {
|
|
368
|
+
fetch: (request, env, ctx) =>
|
|
369
|
+
cachePage(request, (fresh) => handle(fresh, siteContext(env, ctx)), {
|
|
370
|
+
ctx,
|
|
371
|
+
deployId: import.meta.env.ZAPPIE_DEPLOY_ID,
|
|
372
|
+
branchCookie: "site_branch",
|
|
373
|
+
}),
|
|
374
|
+
};
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
### Vite plugins
|
|
378
|
+
|
|
379
|
+
`@zappie/sdk/vite` holds the build and dev plugins a site uses.
|
|
380
|
+
|
|
381
|
+
- `zappieSource({ previewHost })` marks elements with their source on the
|
|
382
|
+
Studio dev server. On every dev server it also pre-bundles each browser
|
|
383
|
+
entry of the installed `@zappie/sdk` and `@zappie/foundations`, and scans
|
|
384
|
+
every module under `app/`, so opening a page that imports an entry the
|
|
385
|
+
session hasn't seen never re-bundles and reloads the preview.
|
|
386
|
+
- `zappieWorker()` minifies the site's Worker, renders it with React's
|
|
387
|
+
streaming renderer alone, and sets `import.meta.env.ZAPPIE_DEPLOY_ID` to a
|
|
388
|
+
new id for each build. The browser's code is unchanged.
|
|
389
|
+
- `zappieHoistImports()` lists each route's chunks in its own file.
|
|
390
|
+
- `zappieUploads({ host })` serves the site's uploads on a local dev server.
|
|
329
391
|
|
|
330
392
|
### Checkout defaults
|
|
331
393
|
|
package/dist/config/index.d.ts
CHANGED
|
@@ -18,6 +18,10 @@ type ZappieSiteConfig = {
|
|
|
18
18
|
store: string;
|
|
19
19
|
branches?: string[];
|
|
20
20
|
theme: string;
|
|
21
|
+
/**
|
|
22
|
+
* @deprecated Zappie hosting prerenders no page: every page renders in your Worker, and its page cache keeps the
|
|
23
|
+
* anonymous ones. `validateConfig` warns when it is set. Remove it.
|
|
24
|
+
*/
|
|
21
25
|
prerender?: string[];
|
|
22
26
|
menu?: {
|
|
23
27
|
hiddenCategories?: string[];
|
|
@@ -96,7 +100,7 @@ type ZappieSiteConfig = {
|
|
|
96
100
|
*/
|
|
97
101
|
type ConfigIssue = {
|
|
98
102
|
path: string;
|
|
99
|
-
code: "invalid_type" | "missing_required" | "unknown_key" | "invalid_format" | "duplicate" | "redundant_allowlist" | "budget_override";
|
|
103
|
+
code: "invalid_type" | "missing_required" | "unknown_key" | "invalid_format" | "duplicate" | "redundant_allowlist" | "budget_override" | "unused_setting";
|
|
100
104
|
message: string;
|
|
101
105
|
severity: "error" | "warning";
|
|
102
106
|
};
|
package/dist/debug.js
CHANGED
package/dist/index.js
CHANGED
|
@@ -11,7 +11,7 @@ import { ZappieError, isZappieError } from "./errors.js";
|
|
|
11
11
|
export * from "./models.js";
|
|
12
12
|
import { format, money } from "./money.js";
|
|
13
13
|
import { RestTransport } from "./transport/rest.js";
|
|
14
|
-
var VERSION = true ? "0.
|
|
14
|
+
var VERSION = true ? "0.13.0" : "0.0.0-development";
|
|
15
15
|
export {
|
|
16
16
|
API_VERSION,
|
|
17
17
|
RestTransport,
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
// src/server/chosen-branch.ts
|
|
2
2
|
var find = (store, wanted) => wanted ? store.branches.find((b) => b.id === wanted || b.slug === wanted) : void 0;
|
|
3
3
|
function readCookie(request, name) {
|
|
4
|
+
if (!name) {
|
|
5
|
+
return void 0;
|
|
6
|
+
}
|
|
4
7
|
for (const part of (request.headers.get("cookie") ?? "").split(";")) {
|
|
5
8
|
const index = part.indexOf("=");
|
|
6
9
|
if (index > 0 && part.slice(0, index).trim() === name) {
|
|
@@ -29,17 +32,36 @@ var ignore = () => {
|
|
|
29
32
|
};
|
|
30
33
|
async function loadStoreAndMenu(client, request, options) {
|
|
31
34
|
const named = requestedBranch(request, options);
|
|
32
|
-
const
|
|
35
|
+
const learned = slugs(client);
|
|
36
|
+
const guess = named?.startsWith("br_") ? named : named && learned.get(named);
|
|
37
|
+
const early = guess && !client.store.peek() ? client._internal.readMenu(guess, {}) : void 0;
|
|
33
38
|
early?.catch(ignore);
|
|
34
39
|
const store = await client.store.get();
|
|
40
|
+
for (const entry of store.branches) {
|
|
41
|
+
learned.set(entry.slug, entry.id);
|
|
42
|
+
}
|
|
35
43
|
const resolved = resolveBranch(store, request, options);
|
|
36
44
|
const { branch } = resolved;
|
|
37
45
|
if (!branch) {
|
|
38
46
|
return { store, ...resolved, menu: void 0 };
|
|
39
47
|
}
|
|
40
|
-
const menu = await (early && branch.id ===
|
|
48
|
+
const menu = await (early && branch.id === guess ? early : client.menu.get({ branch: branch.id }));
|
|
41
49
|
return { store, ...resolved, menu };
|
|
42
50
|
}
|
|
51
|
+
var learnedSlugs = /* @__PURE__ */ new Map();
|
|
52
|
+
function slugs(client) {
|
|
53
|
+
const { config } = client;
|
|
54
|
+
const id = JSON.stringify([config.baseUrl ?? "", config.store, config.key]);
|
|
55
|
+
let found = learnedSlugs.get(id);
|
|
56
|
+
if (!found) {
|
|
57
|
+
if (learnedSlugs.size >= 100) {
|
|
58
|
+
learnedSlugs.clear();
|
|
59
|
+
}
|
|
60
|
+
found = /* @__PURE__ */ new Map();
|
|
61
|
+
learnedSlugs.set(id, found);
|
|
62
|
+
}
|
|
63
|
+
return found;
|
|
64
|
+
}
|
|
43
65
|
export {
|
|
44
66
|
loadStoreAndMenu,
|
|
45
67
|
requestedBranch,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/server/chosen-branch.ts"],
|
|
4
|
-
"mappings": ";AA0BA,IAAM,OAAO,CAAC,OAAc,WAC1B,SACI,MAAM,SAAS,KAAK,CAAC,MAAM,EAAE,OAAO,UAAU,EAAE,SAAS,MAAM,IAC/D;AAEN,SAAS,WAAW,SAAkB,
|
|
4
|
+
"mappings": ";AA0BA,IAAM,OAAO,CAAC,OAAc,WAC1B,SACI,MAAM,SAAS,KAAK,CAAC,MAAM,EAAE,OAAO,UAAU,EAAE,SAAS,MAAM,IAC/D;AAEN,SAAS,WAAW,SAAkB,MAA0B;AAC9D,MAAI,CAAC,MAAM;AACT,WAAO;AAAA,EACT;AACA,aAAW,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KAAK,IAAI,MAAM,GAAG,GAAG;AACnE,UAAM,QAAQ,KAAK,QAAQ,GAAG;AAC9B,QAAI,QAAQ,KAAK,KAAK,MAAM,GAAG,KAAK,EAAE,KAAK,MAAM,MAAM;AACrD,UAAI;AACF,eAAO,mBAAmB,KAAK,MAAM,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AAI;AACnB,MAAI,CAAC,QAAQ;AACX,WAAO,EAAE,OAAO,GAAG,UAAU,MAAM,OAAU;AAAA,EAC/C;AACA,QAAM,OAAO,OAAO,SAAS,OAAO,OAAO,QACvC,QACA,OAAO,KAAK,IAAI,EAAE,QAAQ,OAAO,GAAG,CAAC;AACzC,SAAO,EAAE,OAAO,GAAG,UAAU,KAAK;AACpC;AAIA,IAAM,eAAe,oBAAI,IAAiC;AAE1D,SAAS,MAAM,QAAgB;AAC7B,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,KAAK,KAAK,UAAU,CAAC,OAAO,WAAW,IAAI,OAAO,OAAO,OAAO,GAAG,CAAC;AAC1E,MAAI,QAAQ,aAAa,IAAI,EAAE;AAC/B,MAAI,CAAC,OAAO;AAEV,QAAI,aAAa,QAAQ,KAAK;AAC5B,mBAAa,MAAM;AAAA,IACrB;AACA,YAAQ,oBAAI,IAAI;AAChB,iBAAa,IAAI,IAAI,KAAK;AAAA,EAC5B;AACA,SAAO;AACT;",
|
|
5
5
|
"names": []
|
|
6
6
|
}
|
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
// src/server/edge-cache.ts
|
|
2
|
+
import { createSecurityNonce } from "./security.js";
|
|
3
|
+
var EDGE_CACHE_HEADER = "x-zappie-edge-cache";
|
|
4
|
+
var STORED_AT = "x-zappie-stored-at";
|
|
5
|
+
var FRESH_FOR = "x-zappie-fresh-for";
|
|
6
|
+
var STALE_FOR = "x-zappie-stale-for";
|
|
7
|
+
var ORIGIN_CACHE_CONTROL = "x-zappie-origin-cache-control";
|
|
8
|
+
var CACHE_NAME = "zappie";
|
|
9
|
+
var opened;
|
|
10
|
+
function openEdgeCache() {
|
|
11
|
+
opened ?? (opened = (async () => {
|
|
12
|
+
try {
|
|
13
|
+
return typeof caches === "undefined" ? void 0 : await caches.open(CACHE_NAME);
|
|
14
|
+
} catch {
|
|
15
|
+
return void 0;
|
|
16
|
+
}
|
|
17
|
+
})());
|
|
18
|
+
return opened;
|
|
19
|
+
}
|
|
20
|
+
async function sha256(value) {
|
|
21
|
+
const digest = await crypto.subtle.digest(
|
|
22
|
+
"SHA-256",
|
|
23
|
+
new TextEncoder().encode(value)
|
|
24
|
+
);
|
|
25
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
26
|
+
}
|
|
27
|
+
function sharedFreshness(cacheControl) {
|
|
28
|
+
if (!cacheControl || /\b(?:private|no-store|no-cache)\b/i.test(cacheControl)) {
|
|
29
|
+
return void 0;
|
|
30
|
+
}
|
|
31
|
+
const seconds = (name) => {
|
|
32
|
+
const match = new RegExp(`(?:^|[,\\s])${name}=(\\d+)`, "i").exec(
|
|
33
|
+
cacheControl
|
|
34
|
+
);
|
|
35
|
+
return match ? Number(match[1]) : void 0;
|
|
36
|
+
};
|
|
37
|
+
const fresh = seconds("s-maxage") ?? seconds("max-age") ?? 0;
|
|
38
|
+
if (fresh <= 0) {
|
|
39
|
+
return void 0;
|
|
40
|
+
}
|
|
41
|
+
return { fresh, stale: seconds("stale-while-revalidate") ?? 0 };
|
|
42
|
+
}
|
|
43
|
+
function storable(response, life, now) {
|
|
44
|
+
const headers = new Headers(response.headers);
|
|
45
|
+
headers.delete("set-cookie");
|
|
46
|
+
headers.delete(EDGE_CACHE_HEADER);
|
|
47
|
+
const origin = response.headers.get("cache-control");
|
|
48
|
+
if (origin) {
|
|
49
|
+
headers.set(ORIGIN_CACHE_CONTROL, origin);
|
|
50
|
+
}
|
|
51
|
+
headers.set(STORED_AT, String(now));
|
|
52
|
+
headers.set(FRESH_FOR, String(life.fresh));
|
|
53
|
+
headers.set(STALE_FOR, String(life.stale));
|
|
54
|
+
headers.set("cache-control", `public, max-age=${life.fresh + life.stale}`);
|
|
55
|
+
return new Response(response.body, { status: response.status, headers });
|
|
56
|
+
}
|
|
57
|
+
function served(cached, status, age) {
|
|
58
|
+
const headers = new Headers(cached.headers);
|
|
59
|
+
const origin = headers.get(ORIGIN_CACHE_CONTROL);
|
|
60
|
+
if (origin) {
|
|
61
|
+
headers.set("cache-control", origin);
|
|
62
|
+
} else {
|
|
63
|
+
headers.delete("cache-control");
|
|
64
|
+
}
|
|
65
|
+
for (const name of [STORED_AT, FRESH_FOR, STALE_FOR, ORIGIN_CACHE_CONTROL]) {
|
|
66
|
+
headers.delete(name);
|
|
67
|
+
}
|
|
68
|
+
headers.set("age", String(Math.max(0, Math.floor(age))));
|
|
69
|
+
headers.set(EDGE_CACHE_HEADER, status);
|
|
70
|
+
return new Response(cached.body, { status: cached.status, headers });
|
|
71
|
+
}
|
|
72
|
+
function discard(response) {
|
|
73
|
+
response.body?.cancel().catch(() => {
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
function marked(response, status) {
|
|
77
|
+
const out = new Response(response.body, response);
|
|
78
|
+
out.headers.set(EDGE_CACHE_HEADER, status);
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
async function lookup(cache, key, now) {
|
|
82
|
+
const cached = await cache.match(key);
|
|
83
|
+
if (!cached) {
|
|
84
|
+
return void 0;
|
|
85
|
+
}
|
|
86
|
+
const storedAt = Number(cached.headers.get(STORED_AT));
|
|
87
|
+
const life = {
|
|
88
|
+
fresh: Number(cached.headers.get(FRESH_FOR)),
|
|
89
|
+
stale: Number(cached.headers.get(STALE_FOR))
|
|
90
|
+
};
|
|
91
|
+
if (!Number.isFinite(storedAt) || !Number.isFinite(life.fresh) || !Number.isFinite(life.stale)) {
|
|
92
|
+
discard(cached);
|
|
93
|
+
return void 0;
|
|
94
|
+
}
|
|
95
|
+
return { response: cached, age: (now - storedAt) / 1e3, life };
|
|
96
|
+
}
|
|
97
|
+
var refreshing = /* @__PURE__ */ new Map();
|
|
98
|
+
function refreshOnce(ctx, key, refresh) {
|
|
99
|
+
if (refreshing.has(key.url)) {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const running = refresh().catch(() => {
|
|
103
|
+
}).finally(() => refreshing.delete(key.url));
|
|
104
|
+
refreshing.set(key.url, running);
|
|
105
|
+
ctx.waitUntil(running);
|
|
106
|
+
}
|
|
107
|
+
var SHARED_READS = /\/(?:store|menus)$/;
|
|
108
|
+
function apiCacheBypass(request) {
|
|
109
|
+
if (request.method !== "GET") {
|
|
110
|
+
return "method";
|
|
111
|
+
}
|
|
112
|
+
if (!SHARED_READS.test(new URL(request.url).pathname)) {
|
|
113
|
+
return "path";
|
|
114
|
+
}
|
|
115
|
+
if (!/^Bearer pk_(?:test|live)_/.test(
|
|
116
|
+
request.headers.get("authorization") ?? ""
|
|
117
|
+
)) {
|
|
118
|
+
return "credentials";
|
|
119
|
+
}
|
|
120
|
+
if (request.headers.has("cookie")) {
|
|
121
|
+
return "cookie";
|
|
122
|
+
}
|
|
123
|
+
if (request.headers.has("if-none-match")) {
|
|
124
|
+
return "conditional";
|
|
125
|
+
}
|
|
126
|
+
return void 0;
|
|
127
|
+
}
|
|
128
|
+
async function apiCacheKey(request) {
|
|
129
|
+
const key = (request.headers.get("authorization") ?? "").replace(
|
|
130
|
+
/^Bearer\s+/,
|
|
131
|
+
""
|
|
132
|
+
);
|
|
133
|
+
const url = new URL(request.url);
|
|
134
|
+
const identity = await sha256(
|
|
135
|
+
JSON.stringify([key, request.headers.get("zappie-version") ?? ""])
|
|
136
|
+
);
|
|
137
|
+
return new Request(
|
|
138
|
+
`https://zappie-api-cache.internal/${identity.slice(0, 40)}/${url.host}${url.pathname}${url.search}`
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
function cachedApiFetch(options = {}) {
|
|
142
|
+
const upstream = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
143
|
+
const now = options.now ?? Date.now;
|
|
144
|
+
const source = () => options.cache ?? openEdgeCache();
|
|
145
|
+
return async (input, init) => {
|
|
146
|
+
const request = new Request(input, init);
|
|
147
|
+
if (apiCacheBypass(request)) {
|
|
148
|
+
return upstream(request);
|
|
149
|
+
}
|
|
150
|
+
let cache;
|
|
151
|
+
let key;
|
|
152
|
+
let hit;
|
|
153
|
+
try {
|
|
154
|
+
cache = await source();
|
|
155
|
+
if (cache) {
|
|
156
|
+
key = await apiCacheKey(request);
|
|
157
|
+
hit = await lookup(cache, key, now());
|
|
158
|
+
}
|
|
159
|
+
} catch {
|
|
160
|
+
cache = void 0;
|
|
161
|
+
}
|
|
162
|
+
if (!cache) {
|
|
163
|
+
return upstream(request);
|
|
164
|
+
}
|
|
165
|
+
const store = async (response) => {
|
|
166
|
+
const life = sharedFreshness(response.headers.get("cache-control"));
|
|
167
|
+
if (response.status !== 200 || !life || response.headers.has("set-cookie")) {
|
|
168
|
+
return response;
|
|
169
|
+
}
|
|
170
|
+
const copy = response.clone();
|
|
171
|
+
const put = cache.put(key, storable(copy, life, now())).catch(() => {
|
|
172
|
+
});
|
|
173
|
+
if (options.ctx) {
|
|
174
|
+
options.ctx.waitUntil(put);
|
|
175
|
+
} else {
|
|
176
|
+
await put;
|
|
177
|
+
}
|
|
178
|
+
return response;
|
|
179
|
+
};
|
|
180
|
+
if (hit && hit.age < hit.life.fresh) {
|
|
181
|
+
return served(hit.response, "HIT", hit.age);
|
|
182
|
+
}
|
|
183
|
+
if (hit && options.ctx && hit.age < hit.life.fresh + hit.life.stale) {
|
|
184
|
+
const etag = hit.response.headers.get("etag");
|
|
185
|
+
const kept = hit.response.clone();
|
|
186
|
+
refreshOnce(options.ctx, key, async () => {
|
|
187
|
+
const headers = new Headers(request.headers);
|
|
188
|
+
if (etag) {
|
|
189
|
+
headers.set("if-none-match", etag);
|
|
190
|
+
}
|
|
191
|
+
const response = await upstream(
|
|
192
|
+
new Request(request.url, {
|
|
193
|
+
method: "GET",
|
|
194
|
+
headers,
|
|
195
|
+
redirect: "manual"
|
|
196
|
+
})
|
|
197
|
+
);
|
|
198
|
+
if (response.status === 304) {
|
|
199
|
+
discard(response);
|
|
200
|
+
const life2 = sharedFreshness(response.headers.get("cache-control")) ?? hit.life;
|
|
201
|
+
const restamped = served(kept, "HIT", 0);
|
|
202
|
+
restamped.headers.delete("age");
|
|
203
|
+
restamped.headers.delete(EDGE_CACHE_HEADER);
|
|
204
|
+
await cache.put(key, storable(restamped, life2, now()));
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const life = sharedFreshness(response.headers.get("cache-control"));
|
|
208
|
+
if (response.status === 200 && life && !response.headers.has("set-cookie")) {
|
|
209
|
+
await cache.put(key, storable(response, life, now()));
|
|
210
|
+
} else {
|
|
211
|
+
discard(response);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
return served(hit.response, "STALE", hit.age);
|
|
215
|
+
}
|
|
216
|
+
if (hit) {
|
|
217
|
+
discard(hit.response);
|
|
218
|
+
}
|
|
219
|
+
return store(await upstream(request));
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
var SESSION_COOKIE = /^(?:__Host-zappie_|__Host-zp_)|(?:^|[_-])(?:session|sess|sid|auth|token|jwt)(?:$|[_-])/i;
|
|
223
|
+
function cookieNames(request) {
|
|
224
|
+
return (request.headers.get("cookie") ?? "").split(";").map((part) => part.slice(0, part.indexOf("=") >>> 0).trim()).filter(Boolean);
|
|
225
|
+
}
|
|
226
|
+
function cookieValue(request, name) {
|
|
227
|
+
for (const part of (request.headers.get("cookie") ?? "").split(";")) {
|
|
228
|
+
const index = part.indexOf("=");
|
|
229
|
+
if (index > 0 && part.slice(0, index).trim() === name) {
|
|
230
|
+
return part.slice(index + 1).trim();
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return "";
|
|
234
|
+
}
|
|
235
|
+
function pageCacheBypass(request, options = {}) {
|
|
236
|
+
if (request.method !== "GET") {
|
|
237
|
+
return "method";
|
|
238
|
+
}
|
|
239
|
+
if (["x-zappie-draft", "x-zappie-review", "x-zappie-preview"].some(
|
|
240
|
+
(name) => request.headers.has(name)
|
|
241
|
+
) || new URL(request.url).searchParams.has("preview")) {
|
|
242
|
+
return "preview";
|
|
243
|
+
}
|
|
244
|
+
if (request.headers.has("x-zappie-site-state")) {
|
|
245
|
+
return "closed";
|
|
246
|
+
}
|
|
247
|
+
if (request.headers.has("authorization")) {
|
|
248
|
+
return "authorization";
|
|
249
|
+
}
|
|
250
|
+
const own = new Set(options.privateCookies ?? []);
|
|
251
|
+
if (cookieNames(request).some(
|
|
252
|
+
(name) => own.has(name) || SESSION_COOKIE.test(name)
|
|
253
|
+
)) {
|
|
254
|
+
return "session";
|
|
255
|
+
}
|
|
256
|
+
return void 0;
|
|
257
|
+
}
|
|
258
|
+
async function pageCacheKey(request, options) {
|
|
259
|
+
const identity = await sha256(
|
|
260
|
+
JSON.stringify([
|
|
261
|
+
request.url,
|
|
262
|
+
options.branchCookie ? cookieValue(request, options.branchCookie) : "",
|
|
263
|
+
options.deployId,
|
|
264
|
+
request.headers.get("x-zappie-site") ?? "",
|
|
265
|
+
request.headers.get("x-zappie-key") ?? ""
|
|
266
|
+
])
|
|
267
|
+
);
|
|
268
|
+
return new Request(`https://zappie-page-cache.internal/${identity}`);
|
|
269
|
+
}
|
|
270
|
+
function pageStoreBypass(response, fallback) {
|
|
271
|
+
if (response.status !== 200) {
|
|
272
|
+
return "status";
|
|
273
|
+
}
|
|
274
|
+
if (response.headers.has("set-cookie")) {
|
|
275
|
+
return "set-cookie";
|
|
276
|
+
}
|
|
277
|
+
if (response.headers.has("x-zappie-closed-page")) {
|
|
278
|
+
return "closed";
|
|
279
|
+
}
|
|
280
|
+
if (/(?:^|,)\s*\*\s*(?:,|$)/.test(response.headers.get("vary") ?? "")) {
|
|
281
|
+
return "vary";
|
|
282
|
+
}
|
|
283
|
+
if (!sharedFreshness(response.headers.get("cache-control") ?? fallback ?? null)) {
|
|
284
|
+
return "cache-control";
|
|
285
|
+
}
|
|
286
|
+
return void 0;
|
|
287
|
+
}
|
|
288
|
+
var NONCE = /'nonce-([A-Za-z0-9_+/=-]+)'/;
|
|
289
|
+
var POLICY_HEADERS = [
|
|
290
|
+
"content-security-policy",
|
|
291
|
+
"content-security-policy-report-only"
|
|
292
|
+
];
|
|
293
|
+
async function rotatePageNonce(response, nonce = createSecurityNonce()) {
|
|
294
|
+
const old = POLICY_HEADERS.map(
|
|
295
|
+
(name) => NONCE.exec(response.headers.get(name) ?? "")?.[1]
|
|
296
|
+
).find(Boolean);
|
|
297
|
+
if (!old || !/^text\/html/i.test(response.headers.get("content-type") ?? "")) {
|
|
298
|
+
return response;
|
|
299
|
+
}
|
|
300
|
+
const headers = new Headers(response.headers);
|
|
301
|
+
for (const name of POLICY_HEADERS) {
|
|
302
|
+
const value = headers.get(name);
|
|
303
|
+
if (value) {
|
|
304
|
+
headers.set(name, value.replaceAll(`'nonce-${old}'`, `'nonce-${nonce}'`));
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
headers.delete("content-length");
|
|
308
|
+
const body = (await response.text()).replaceAll(`nonce="${old}"`, `nonce="${nonce}"`).replaceAll(`nonce=${old}`, `nonce=${nonce}`);
|
|
309
|
+
return new Response(body, { status: response.status, headers });
|
|
310
|
+
}
|
|
311
|
+
async function cachePage(request, render, options) {
|
|
312
|
+
if (pageCacheBypass(request, options)) {
|
|
313
|
+
return marked(await render(request), "BYPASS");
|
|
314
|
+
}
|
|
315
|
+
const now = options.now ?? Date.now;
|
|
316
|
+
let cache;
|
|
317
|
+
let key;
|
|
318
|
+
let hit;
|
|
319
|
+
try {
|
|
320
|
+
cache = await (options.cache ?? openEdgeCache());
|
|
321
|
+
if (cache) {
|
|
322
|
+
key = await pageCacheKey(request, options);
|
|
323
|
+
hit = await lookup(cache, key, now());
|
|
324
|
+
}
|
|
325
|
+
} catch {
|
|
326
|
+
cache = void 0;
|
|
327
|
+
}
|
|
328
|
+
if (!cache || !key) {
|
|
329
|
+
return marked(await render(request), "BYPASS");
|
|
330
|
+
}
|
|
331
|
+
const fallback = () => options.cacheControl?.(new URL(request.url));
|
|
332
|
+
const keep = async (response) => {
|
|
333
|
+
const control = response.headers.get("cache-control") ?? fallback();
|
|
334
|
+
if (pageStoreBypass(response, control)) {
|
|
335
|
+
return void 0;
|
|
336
|
+
}
|
|
337
|
+
const life = sharedFreshness(control ?? null);
|
|
338
|
+
const shared = new Response(response.body, response);
|
|
339
|
+
if (control && !shared.headers.has("cache-control")) {
|
|
340
|
+
shared.headers.set("cache-control", control);
|
|
341
|
+
}
|
|
342
|
+
return { shared, life };
|
|
343
|
+
};
|
|
344
|
+
if (hit && hit.age < hit.life.fresh) {
|
|
345
|
+
return rotatePageNonce(served(hit.response, "HIT", hit.age));
|
|
346
|
+
}
|
|
347
|
+
if (hit && options.ctx && hit.age < hit.life.fresh + hit.life.stale) {
|
|
348
|
+
refreshOnce(options.ctx, key, async () => {
|
|
349
|
+
const kept2 = await keep(
|
|
350
|
+
await render(
|
|
351
|
+
new Request(request.url, { method: "GET", headers: request.headers })
|
|
352
|
+
)
|
|
353
|
+
);
|
|
354
|
+
if (kept2) {
|
|
355
|
+
await cache.put(key, storable(kept2.shared, kept2.life, now()));
|
|
356
|
+
} else {
|
|
357
|
+
await cache.delete(key);
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
return rotatePageNonce(served(hit.response, "STALE", hit.age));
|
|
361
|
+
}
|
|
362
|
+
if (hit) {
|
|
363
|
+
discard(hit.response);
|
|
364
|
+
}
|
|
365
|
+
const rendered = await render(request);
|
|
366
|
+
const kept = await keep(rendered);
|
|
367
|
+
if (!kept) {
|
|
368
|
+
return marked(rendered, "MISS");
|
|
369
|
+
}
|
|
370
|
+
const put = cache.put(key, storable(kept.shared.clone(), kept.life, now())).catch(() => {
|
|
371
|
+
});
|
|
372
|
+
if (options.ctx) {
|
|
373
|
+
options.ctx.waitUntil(put);
|
|
374
|
+
} else {
|
|
375
|
+
await put;
|
|
376
|
+
}
|
|
377
|
+
return marked(kept.shared, "MISS");
|
|
378
|
+
}
|
|
379
|
+
export {
|
|
380
|
+
EDGE_CACHE_HEADER,
|
|
381
|
+
apiCacheBypass,
|
|
382
|
+
apiCacheKey,
|
|
383
|
+
cachePage,
|
|
384
|
+
cachedApiFetch,
|
|
385
|
+
openEdgeCache,
|
|
386
|
+
pageCacheBypass,
|
|
387
|
+
pageCacheKey,
|
|
388
|
+
pageStoreBypass,
|
|
389
|
+
rotatePageNonce,
|
|
390
|
+
sharedFreshness
|
|
391
|
+
};
|
|
392
|
+
//# sourceMappingURL=edge-cache.js.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/server/edge-cache.ts"],
|
|
4
|
+
"mappings": ";AAAA,SAAS,2BAA2B;AAS7B,IAAM,oBAAoB;AAEjC,IAAM,YAAY;AAClB,IAAM,YAAY;AAClB,IAAM,YAAY;AAClB,IAAM,uBAAuB;AAC7B,IAAM,aAAa;AASnB,IAAI;AAOG,SAAS,gBAAgD;AAC9D,uBAAY,YAAY;AACtB,QAAI;AACF,aAAO,OAAO,WAAW,cACrB,SACA,MAAM,OAAO,KAAK,UAAU;AAAA,IAClC,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF,GAAG;AACH,SAAO;AACT;AAGA,eAAe,OAAO,OAAgC;AACpD,QAAM,SAAS,MAAM,OAAO,OAAO;AAAA,IACjC;AAAA,IACA,IAAI,YAAY,EAAE,OAAO,KAAK;AAAA,EAChC;AACA,SAAO,CAAC,GAAG,IAAI,WAAW,MAAM,CAAC,EAC9B,IAAI,CAAC,SAAS,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAChD,KAAK,EAAE;AACZ;AAUO,SAAS,gBACd,cACuB;AACvB,MACE,CAAC,gBACD,qCAAqC,KAAK,YAAY,GACtD;AACA,WAAO;AAAA,EACT;AACA,QAAM,UAAU,CAAC,SAAiB;AAChC,UAAM,QAAQ,IAAI,OAAO,eAAe,IAAI,WAAW,GAAG,EAAE;AAAA,MAC1D;AAAA,IACF;AACA,WAAO,QAAQ,OAAO,MAAM,CAAC,CAAC,IAAI;AAAA,EACpC;AACA,QAAM,QAAQ,QAAQ,UAAU,KAAK,QAAQ,S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AAI,KAAK;AACP,YAAQ,IAAI,QAAQ;AAAA,EACtB;AACA,QAAM,WAAW,MAAM,OAAO,OAAO;AACrC,QAAM,OAAO,MAAM,KAAK,QAAQ;AAChC,MAAI,CAAC,MAAM;AACT,WAAO,OAAO,UAAU,MAAM;AAAA,EAChC;AACA,QAAM,MAAM,MACT,IAAI,KAAK,SAAS,KAAK,OAAO,MAAM,GAAG,KAAK,MAAM,IAAI,CAAC,CAAC,EACxD,MAAM,MAAM;AAAA,EAAC,CAAC;AACjB,MAAI,QAAQ,KAAK;AACf,YAAQ,IAAI,UAAU,GAAG;AAAA,EAC3B,OAAO;AACL,UAAM;AAAA,EACR;AACA,SAAO,OAAO,KAAK,QAAQ,MAAM;AACnC;",
|
|
5
|
+
"names": ["life", "kept"]
|
|
6
|
+
}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -363,8 +363,8 @@ declare function cookieSessionStore(options: CookieSessionStoreOptions): Session
|
|
|
363
363
|
|
|
364
364
|
/** Where a site keeps the shopper's branch choice. */
|
|
365
365
|
type ResolveBranchOptions = {
|
|
366
|
-
/** The cookie that remembers the shopper's branch, by id or slug. */
|
|
367
|
-
cookie
|
|
366
|
+
/** The cookie that remembers the shopper's branch, by id or slug. Leave it out when the site keeps no branch cookie. */
|
|
367
|
+
cookie?: string;
|
|
368
368
|
/** The branch to show when the shopper hasn't chosen one, by id or slug. Defaults to the store's default branch. */
|
|
369
369
|
fallback?: string;
|
|
370
370
|
/** The query parameter that names a branch in a link. Defaults to `branch`. */
|
|
@@ -418,9 +418,10 @@ type StoreAndMenu = ResolvedBranch & {
|
|
|
418
418
|
* the branch by ID (`br_…`), the menu read starts alongside the store read,
|
|
419
419
|
* so a page render waits for one round trip instead of two. The menu counts
|
|
420
420
|
* only once the store confirms that branch, so you get the same menu and the
|
|
421
|
-
* same errors as `store.get` followed by `menu.get`. A branch named by slug
|
|
422
|
-
*
|
|
423
|
-
*
|
|
421
|
+
* same errors as `store.get` followed by `menu.get`. A branch named by slug
|
|
422
|
+
* starts early too once a store read in the same Worker isolate has given
|
|
423
|
+
* that slug's ID. The first such request, or one naming no branch, reads the
|
|
424
|
+
* menu after the store, because the API takes branch IDs only.
|
|
424
425
|
*
|
|
425
426
|
* @example
|
|
426
427
|
* const { store, branch, chosen, mustChoose, menu } = await loadStoreAndMenu(client, request, {
|
|
@@ -435,6 +436,154 @@ type StoreAndMenu = ResolvedBranch & {
|
|
|
435
436
|
*/
|
|
436
437
|
declare function loadStoreAndMenu(client: Zappie, request: Request, options: ResolveBranchOptions): Promise<StoreAndMenu>;
|
|
437
438
|
|
|
439
|
+
/** The part of a Worker's `ExecutionContext` the edge cache uses: work that may finish after the response. */
|
|
440
|
+
type EdgeContext = {
|
|
441
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
442
|
+
};
|
|
443
|
+
/** How a response came from the edge cache, in the `x-zappie-edge-cache` response header. */
|
|
444
|
+
type EdgeCacheStatus = "HIT" | "STALE" | "MISS" | "BYPASS";
|
|
445
|
+
/** The response header that says how the edge cache answered. */
|
|
446
|
+
declare const EDGE_CACHE_HEADER = "x-zappie-edge-cache";
|
|
447
|
+
/** The part of the Cache API the edge cache uses: a Worker's `caches.open()` cache, or a stand-in in tests. */
|
|
448
|
+
type EdgeCache = {
|
|
449
|
+
match(request: Request): Promise<Response | undefined>;
|
|
450
|
+
put(request: Request, response: Response): Promise<void>;
|
|
451
|
+
delete(request: Request): Promise<boolean>;
|
|
452
|
+
};
|
|
453
|
+
/**
|
|
454
|
+
* Open the Worker's own cache, once per isolate. On Zappie hosting each site runs as a user Worker in a Workers for
|
|
455
|
+
* Platforms dispatch namespace, where `caches.default` is disabled and each Worker's `caches.open()` cache is its own.
|
|
456
|
+
* Outside a Worker, where there is no Cache API, it resolves to `undefined` and nothing is cached.
|
|
457
|
+
*/
|
|
458
|
+
declare function openEdgeCache(): Promise<EdgeCache | undefined>;
|
|
459
|
+
/** How long a response may be served fresh and then stale, in seconds, from its `Cache-Control`. */
|
|
460
|
+
type Freshness = {
|
|
461
|
+
fresh: number;
|
|
462
|
+
stale: number;
|
|
463
|
+
};
|
|
464
|
+
/**
|
|
465
|
+
* How long a shared cache may keep a response, from its `Cache-Control`: `s-maxage` (or `max-age`) fresh, then
|
|
466
|
+
* `stale-while-revalidate` stale. `undefined` when it may not be shared: `private`, `no-store`, `no-cache`, or no
|
|
467
|
+
* fresh lifetime.
|
|
468
|
+
*/
|
|
469
|
+
declare function sharedFreshness(cacheControl: string | null): Freshness | undefined;
|
|
470
|
+
type CacheSource = EdgeCache | undefined | Promise<EdgeCache | undefined>;
|
|
471
|
+
/** Options for {@link cachedApiFetch}. */
|
|
472
|
+
type CachedApiFetchOptions = {
|
|
473
|
+
/** The Worker's execution context. Without it a stale read is fetched again instead of refreshed after the response. */
|
|
474
|
+
ctx?: EdgeContext;
|
|
475
|
+
/** The cache to keep reads in. Defaults to {@link openEdgeCache}. */
|
|
476
|
+
cache?: CacheSource;
|
|
477
|
+
/** The fetch that reaches the API. Defaults to the global fetch. */
|
|
478
|
+
fetch?: typeof fetch;
|
|
479
|
+
/** The clock, in milliseconds. */
|
|
480
|
+
now?: () => number;
|
|
481
|
+
};
|
|
482
|
+
/**
|
|
483
|
+
* Why an API request can't come from the shared cache, or `undefined` when it can. Only a `GET` of the store or a
|
|
484
|
+
* menu, sent with a publishable key and no cookie, is shared. A customer's, cart's, order's or quote's call, or one
|
|
485
|
+
* signed in as a shopper, is never cached.
|
|
486
|
+
*
|
|
487
|
+
* @param request - The request the SDK is about to send to the storefront API.
|
|
488
|
+
*/
|
|
489
|
+
declare function apiCacheBypass(request: Request): string | undefined;
|
|
490
|
+
/**
|
|
491
|
+
* The cache key for a shared API read: the URL, the API version and a hash of the publishable key, so two stores
|
|
492
|
+
* never share an entry and the key itself is never stored.
|
|
493
|
+
*
|
|
494
|
+
* @param request - A request {@link apiCacheBypass} accepts.
|
|
495
|
+
*/
|
|
496
|
+
declare function apiCacheKey(request: Request): Promise<Request>;
|
|
497
|
+
/**
|
|
498
|
+
* A fetch for `createZappie` on the server that keeps the storefront API's store and menu reads in the Worker's
|
|
499
|
+
* cache, for as long as the API's own `Cache-Control` allows (`s-maxage`, then `stale-while-revalidate`). A stale
|
|
500
|
+
* read answers at once and refreshes after the response through `ctx.waitUntil`, with the menu's ETag when it has
|
|
501
|
+
* one. Every other call goes straight to the API. A cache that fails never fails the read.
|
|
502
|
+
*
|
|
503
|
+
* @example
|
|
504
|
+
* ```ts
|
|
505
|
+
* const client = createZappie({ store, key, baseUrl, fetch: cachedApiFetch({ ctx }) });
|
|
506
|
+
* ```
|
|
507
|
+
*
|
|
508
|
+
* @param options - The Worker's execution context, and optionally the cache, fetch and clock.
|
|
509
|
+
* @returns A fetch to pass as `createZappie({ fetch })`.
|
|
510
|
+
*/
|
|
511
|
+
declare function cachedApiFetch(options?: CachedApiFetchOptions): typeof fetch;
|
|
512
|
+
/** Options for {@link cachePage}. */
|
|
513
|
+
type PageCacheOptions = {
|
|
514
|
+
/** The Worker's execution context. Without it a stale page is rendered again instead of refreshed after the response. */
|
|
515
|
+
ctx?: EdgeContext;
|
|
516
|
+
/** Changes with every build, so a deploy never answers with the last deploy's pages. */
|
|
517
|
+
deployId: string;
|
|
518
|
+
/** The cookie that remembers the shopper's branch. Its value is part of the cache key. */
|
|
519
|
+
branchCookie?: string;
|
|
520
|
+
/** More cookie names that make a request the shopper's own, on top of Zappie's session cookies. */
|
|
521
|
+
privateCookies?: string[];
|
|
522
|
+
/**
|
|
523
|
+
* The `Cache-Control` for a response that sets none, such as a route's `.data`. Return `undefined` to keep it out
|
|
524
|
+
* of the cache.
|
|
525
|
+
*/
|
|
526
|
+
cacheControl?: (url: URL) => string | undefined;
|
|
527
|
+
/** The cache to keep pages in. Defaults to {@link openEdgeCache}. */
|
|
528
|
+
cache?: CacheSource;
|
|
529
|
+
/** The clock, in milliseconds. */
|
|
530
|
+
now?: () => number;
|
|
531
|
+
};
|
|
532
|
+
/**
|
|
533
|
+
* Why a page request can't come from the shared cache, or `undefined` when it can. A request that isn't a `GET`, a
|
|
534
|
+
* draft, review or preview, the closed page, one with an `Authorization` header and one with a session or sign-in
|
|
535
|
+
* cookie all render afresh.
|
|
536
|
+
*
|
|
537
|
+
* @param request - The request the site Worker received.
|
|
538
|
+
* @param options - The site's own private cookies.
|
|
539
|
+
*/
|
|
540
|
+
declare function pageCacheBypass(request: Request, options?: Pick<PageCacheOptions, "privateCookies">): string | undefined;
|
|
541
|
+
/**
|
|
542
|
+
* The cache key for a shared page: the full URL, query included, the branch cookie's value, the deploy, and which
|
|
543
|
+
* site the host says this is (its id and a hash of its publishable key), so a Worker that serves several sites keeps
|
|
544
|
+
* each one's pages apart.
|
|
545
|
+
*
|
|
546
|
+
* @param request - A request {@link pageCacheBypass} accepts.
|
|
547
|
+
* @param options - The deploy id and the branch cookie.
|
|
548
|
+
*/
|
|
549
|
+
declare function pageCacheKey(request: Request, options: Pick<PageCacheOptions, "deployId" | "branchCookie">): Promise<Request>;
|
|
550
|
+
/**
|
|
551
|
+
* Why a rendered page can't be shared, or `undefined` when it can: it must be a `200` that sets no cookie, isn't the
|
|
552
|
+
* closed page, and whose `Cache-Control` (or `fallback`, when it sets none) lets a shared cache keep it.
|
|
553
|
+
*
|
|
554
|
+
* @param response - What the site rendered.
|
|
555
|
+
* @param fallback - The `Cache-Control` to use when the response sets none.
|
|
556
|
+
*/
|
|
557
|
+
declare function pageStoreBypass(response: Response, fallback?: string): string | undefined;
|
|
558
|
+
/**
|
|
559
|
+
* A cached HTML page with a new CSP nonce, in both its policy and its markup, so no two shoppers get the same nonce
|
|
560
|
+
* and an enforced policy stays as strong as on a page rendered for them. A page without a nonce is returned as is.
|
|
561
|
+
*
|
|
562
|
+
* @param response - A page from the cache.
|
|
563
|
+
* @param nonce - The new nonce. Defaults to a fresh one from `createSecurityNonce`.
|
|
564
|
+
*/
|
|
565
|
+
declare function rotatePageNonce(response: Response, nonce?: string): Promise<Response>;
|
|
566
|
+
/**
|
|
567
|
+
* Answer a site Worker's anonymous pages from the Worker's cache: documents, their `.data`, robots and the sitemap.
|
|
568
|
+
* A page is kept for as long as its own `Cache-Control` says (`s-maxage`, then `stale-while-revalidate`). A stale
|
|
569
|
+
* page answers at once and renders again after the response through `ctx.waitUntil`. Requests
|
|
570
|
+
* {@link pageCacheBypass} refuses, and responses {@link pageStoreBypass} refuses, are never shared. Each cached HTML
|
|
571
|
+
* page gets a new CSP nonce. Every response says how it was answered in `x-zappie-edge-cache`.
|
|
572
|
+
*
|
|
573
|
+
* @example
|
|
574
|
+
* ```ts
|
|
575
|
+
* export default {
|
|
576
|
+
* fetch: (request, env, ctx) =>
|
|
577
|
+
* cachePage(request, (fresh) => handle(fresh, siteContext(env, ctx)), { ctx, deployId }),
|
|
578
|
+
* };
|
|
579
|
+
* ```
|
|
580
|
+
*
|
|
581
|
+
* @param request - The request the Worker received.
|
|
582
|
+
* @param render - Renders the page. It may be called again after the response to refresh a stale page.
|
|
583
|
+
* @param options - The execution context, deploy id, branch cookie and cache rules.
|
|
584
|
+
*/
|
|
585
|
+
declare function cachePage(request: Request, render: (request: Request) => Promise<Response>, options: PageCacheOptions): Promise<Response>;
|
|
586
|
+
|
|
438
587
|
/**
|
|
439
588
|
* A branch catalogue as the edge keeps it: the SDK `Menu` that `menu.get()`
|
|
440
589
|
* returns, with the facts a snapshot writer and reader need around it.
|
|
@@ -566,6 +715,10 @@ type ZappieSiteConfig = {
|
|
|
566
715
|
store: string;
|
|
567
716
|
branches?: string[];
|
|
568
717
|
theme: string;
|
|
718
|
+
/**
|
|
719
|
+
* @deprecated Zappie hosting prerenders no page: every page renders in your Worker, and its page cache keeps the
|
|
720
|
+
* anonymous ones. `validateConfig` warns when it is set. Remove it.
|
|
721
|
+
*/
|
|
569
722
|
prerender?: string[];
|
|
570
723
|
menu?: {
|
|
571
724
|
hiddenCategories?: string[];
|
|
@@ -754,5 +907,5 @@ declare function createZappieServer({ secretKey, ...config }: ZappieServerConfig
|
|
|
754
907
|
};
|
|
755
908
|
}>;
|
|
756
909
|
|
|
757
|
-
export { STOREFRONT_QUERY_PARAMETERS, STOREFRONT_V1_QUERY_PARAMETERS, ZappieTokenError, ZappieWebhookSignatureError, applyAvailability, buildStorefrontUrl, canonicalJson, cookieSessionStore, createAvailabilityPatch, createMenuSnapshot, createPkce, createSecurityNonce, createStoreSnapshot, createTokenVerifier, createZappieServer, inlineScriptHashes, isMenuSnapshot, loadStoreAndMenu, menuSnapshotFromPayload, openSealedValue, parseStorefrontUrl, randomToken, requestedBranch, resolveBranch, sealValue, securityHeaders, signInRedirect, snapshotHash, snapshotKeys, storefrontRedirect, verifyWebhook };
|
|
758
|
-
export type { AvailabilityPatch, AvailabilityPatchInput, CookieSessionStoreOptions, EdgeSnapshotReader, IdTokenChecks, IdTokenClaims, MenuSnapshot, MenuSnapshotInput, MenuSnapshotPayloadInput, PkcePair, ResolveBranchOptions, ResolvedBranch, SealOptions, SealSecret, SecurityHeadersOptions, SessionData, SessionStore, SnapshotVersionRecord, StoreAndMenu, StoreSnapshot, StorefrontInstallation, StorefrontPageState, StorefrontQuery, StorefrontRoute, StorefrontUrlInput, StorefrontUrlOptions, TokenAlgorithm, TokenClaims, TokenErrorReason, TokenVerifier, TokenVerifierOptions, VerifyTokenChecks, VerifyWebhookOptions, WebhookEvent, WebhookEventType, ZappieServerConfig };
|
|
910
|
+
export { EDGE_CACHE_HEADER, STOREFRONT_QUERY_PARAMETERS, STOREFRONT_V1_QUERY_PARAMETERS, ZappieTokenError, ZappieWebhookSignatureError, apiCacheBypass, apiCacheKey, applyAvailability, buildStorefrontUrl, cachePage, cachedApiFetch, canonicalJson, cookieSessionStore, createAvailabilityPatch, createMenuSnapshot, createPkce, createSecurityNonce, createStoreSnapshot, createTokenVerifier, createZappieServer, inlineScriptHashes, isMenuSnapshot, loadStoreAndMenu, menuSnapshotFromPayload, openEdgeCache, openSealedValue, pageCacheBypass, pageCacheKey, pageStoreBypass, parseStorefrontUrl, randomToken, requestedBranch, resolveBranch, rotatePageNonce, sealValue, securityHeaders, sharedFreshness, signInRedirect, snapshotHash, snapshotKeys, storefrontRedirect, verifyWebhook };
|
|
911
|
+
export type { AvailabilityPatch, AvailabilityPatchInput, CachedApiFetchOptions, CookieSessionStoreOptions, EdgeCache, EdgeCacheStatus, EdgeContext, EdgeSnapshotReader, Freshness, IdTokenChecks, IdTokenClaims, MenuSnapshot, MenuSnapshotInput, MenuSnapshotPayloadInput, PageCacheOptions, PkcePair, ResolveBranchOptions, ResolvedBranch, SealOptions, SealSecret, SecurityHeadersOptions, SessionData, SessionStore, SnapshotVersionRecord, StoreAndMenu, StoreSnapshot, StorefrontInstallation, StorefrontPageState, StorefrontQuery, StorefrontRoute, StorefrontUrlInput, StorefrontUrlOptions, TokenAlgorithm, TokenClaims, TokenErrorReason, TokenVerifier, TokenVerifierOptions, VerifyTokenChecks, VerifyWebhookOptions, WebhookEvent, WebhookEventType, ZappieServerConfig };
|
package/dist/server/index.js
CHANGED
|
@@ -26,6 +26,19 @@ import {
|
|
|
26
26
|
requestedBranch,
|
|
27
27
|
resolveBranch
|
|
28
28
|
} from "./chosen-branch.js";
|
|
29
|
+
import {
|
|
30
|
+
apiCacheBypass,
|
|
31
|
+
apiCacheKey,
|
|
32
|
+
cachedApiFetch,
|
|
33
|
+
cachePage,
|
|
34
|
+
EDGE_CACHE_HEADER,
|
|
35
|
+
openEdgeCache,
|
|
36
|
+
pageCacheBypass,
|
|
37
|
+
pageCacheKey,
|
|
38
|
+
pageStoreBypass,
|
|
39
|
+
rotatePageNonce,
|
|
40
|
+
sharedFreshness
|
|
41
|
+
} from "./edge-cache.js";
|
|
29
42
|
import {
|
|
30
43
|
applyAvailability,
|
|
31
44
|
canonicalJson,
|
|
@@ -54,13 +67,18 @@ function createZappieServer({
|
|
|
54
67
|
return buildClient({ ...config, key: secretKey }, true);
|
|
55
68
|
}
|
|
56
69
|
export {
|
|
70
|
+
EDGE_CACHE_HEADER,
|
|
57
71
|
STOREFRONT_QUERY_PARAMETERS,
|
|
58
72
|
STOREFRONT_V1_QUERY_PARAMETERS,
|
|
59
73
|
VERSION,
|
|
60
74
|
ZappieTokenError,
|
|
61
75
|
ZappieWebhookSignatureError,
|
|
76
|
+
apiCacheBypass,
|
|
77
|
+
apiCacheKey,
|
|
62
78
|
applyAvailability,
|
|
63
79
|
buildStorefrontUrl,
|
|
80
|
+
cachePage,
|
|
81
|
+
cachedApiFetch,
|
|
64
82
|
canonicalJson,
|
|
65
83
|
cookieSessionStore,
|
|
66
84
|
createAvailabilityPatch,
|
|
@@ -74,13 +92,19 @@ export {
|
|
|
74
92
|
isMenuSnapshot,
|
|
75
93
|
loadStoreAndMenu,
|
|
76
94
|
menuSnapshotFromPayload,
|
|
95
|
+
openEdgeCache,
|
|
77
96
|
openSealedValue,
|
|
97
|
+
pageCacheBypass,
|
|
98
|
+
pageCacheKey,
|
|
99
|
+
pageStoreBypass,
|
|
78
100
|
parseStorefrontUrl,
|
|
79
101
|
randomToken,
|
|
80
102
|
requestedBranch,
|
|
81
103
|
resolveBranch,
|
|
104
|
+
rotatePageNonce,
|
|
82
105
|
sealValue,
|
|
83
106
|
securityHeaders,
|
|
107
|
+
sharedFreshness,
|
|
84
108
|
signInRedirect,
|
|
85
109
|
snapshotHash,
|
|
86
110
|
snapshotKeys,
|
package/dist/server/index.js.map
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/server/index.ts"],
|
|
4
|
-
"mappings": ";AAAA,SAAS,mBAAmB;AAG5B,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OASK;AACP;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAQK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AAUA,SAAS,mBAAmB;AAAA,EACjC;AAAA,EACA,GAAG;AACL,GAAuB;AACrB,SAAO,YAAY,EAAE,GAAG,QAAQ,KAAK,UAAU,GAAG,IAAI;AACxD;",
|
|
4
|
+
"mappings": ";AAAA,SAAS,mBAAmB;AAG5B,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OASK;AACP;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAQK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AAUA,SAAS,mBAAmB;AAAA,EACjC;AAAA,EACA,GAAG;AACL,GAAuB;AACrB,SAAO,YAAY,EAAE,GAAG,QAAQ,KAAK,UAAU,GAAG,IAAI;AACxD;",
|
|
5
5
|
"names": []
|
|
6
6
|
}
|
|
@@ -54,17 +54,14 @@ function validateConfig(input) {
|
|
|
54
54
|
unique: true,
|
|
55
55
|
slug: true
|
|
56
56
|
});
|
|
57
|
-
|
|
58
|
-
(
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
);
|
|
57
|
+
if (input.prerender !== void 0) {
|
|
58
|
+
issue({
|
|
59
|
+
path: "prerender",
|
|
60
|
+
code: "unused_setting",
|
|
61
|
+
message: "Zappie hosting prerenders no page, so prerender does nothing. Remove it.",
|
|
62
|
+
severity: "warning"
|
|
63
|
+
});
|
|
64
|
+
}
|
|
68
65
|
nested(input.menu, "menu", ["hiddenCategories"], issue, (value) => {
|
|
69
66
|
stringList(value.hiddenCategories, "menu.hiddenCategories", error);
|
|
70
67
|
});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/site-config/validate.ts"],
|
|
4
|
-
"mappings": ";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAW,SAAS,cAAc;AAG3C,IAAM,WAAW;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AASO,SAAS,eAAe,OAAkC;AAC/D,QAAM,SAAwB,CAAC;AAC/B,QAAM,QAAQ,CAAC,UAAuB,OAAO,KAAK,KAAK;AACvD,QAAM,QAAQ,CAAC,MAAc,MAA2B,YACtD,MAAM,EAAE,MAAM,MAAM,SAAS,UAAU,QAAQ,CAAC;AAClD,MAAI,CAAC,OAAO,KAAK,GAAG;AAClB,WAAO;AAAA,MACL,OAAO;AAAA,MACP,QAAQ;AAAA,QACN;AAAA,UACE,MAAM;AAAA,UACN,MAAM;AAAA,UACN,SACE;AAAA,UACF,UAAU;A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oE,CAAC,GACrE;AACA,MAAI,UAAU,QAAW;AACvB,WAAO;AAAA,EACT;AACA,MACE,CAAC,MAAM,QAAQ,KAAK,KACpB,MAAM,KAAK,CAAC,UAAU,OAAO,UAAU,QAAQ,GAC/C;AACA;AAAA,MACE;AAAA,MACA;AAAA,MACA,qCAAqC,IAAI;AAAA,IAC3C;AACA,WAAO;AAAA,EACT;AACA,MAAI,QAAQ,YAAY,MAAM,WAAW,GAAG;AAC1C;AAAA,MACE;AAAA,MACA;AAAA,MACA,+CAA+C,IAAI;AAAA,IACrD;AAAA,EACF;AACA,QAAM,QAAQ,CAAC,OAAO,UAAU;AAC9B,QAAI,QAAQ,QAAQ,CAAC,SAAS,KAAK,GAAG;AACpC;AAAA,QACE,GAAG,IAAI,IAAI,KAAK;AAAA,QAChB;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACD,MAAI,QAAQ,UAAU,IAAI,IAAI,KAAK,EAAE,SAAS,MAAM,QAAQ;AAC1D;AAAA,MACE;AAAA,MACA;AAAA,MACA,kDAAkD,IAAI;AAAA,IACxD;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,SAAS,OAAgB,MAAc,OAAiB;AAC/D,aAAW,OAAO,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,UAAU;AACvD,QAAI,CAAC,SAAS,IAAI,GAAG;AACnB;AAAA,QACE,GAAG,IAAI,IAAI,KAAK;AAAA,QAChB;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;",
|
|
5
5
|
"names": []
|
|
6
6
|
}
|
package/dist/vite/index.d.ts
CHANGED
|
@@ -21,9 +21,11 @@ type MarkedSource = {
|
|
|
21
21
|
};
|
|
22
22
|
/**
|
|
23
23
|
* Mark each intrinsic JSX element under `app/` with the file and line that render it, and the component that holds it,
|
|
24
|
-
* so the Studio preview can tell Zee where a region the merchant selected lives. It
|
|
25
|
-
* `vite dev` with `previewHost`, the `ZAPPIE_PREVIEW_HOST` that Studio sets, given. `vite build` never runs it,
|
|
26
|
-
* source path reaches a published site.
|
|
24
|
+
* so the Studio preview can tell Zee where a region the merchant selected lives. It marks only on the Studio dev
|
|
25
|
+
* server: `vite dev` with `previewHost`, the `ZAPPIE_PREVIEW_HOST` that Studio sets, given. `vite build` never runs it,
|
|
26
|
+
* so no source path reaches a published site. On every dev server it also pre-bundles each browser entry of the
|
|
27
|
+
* installed `@zappie/sdk` and `@zappie/foundations` up front ({@link zappieDevEntries}), so opening a page that
|
|
28
|
+
* imports one the session hasn't seen never re-bundles and reloads the preview.
|
|
27
29
|
*
|
|
28
30
|
* @example
|
|
29
31
|
* ```ts
|
|
@@ -35,6 +37,14 @@ type MarkedSource = {
|
|
|
35
37
|
* ```
|
|
36
38
|
*/
|
|
37
39
|
declare function zappieSource({ previewHost }: ZappieSourceOptions): Plugin;
|
|
40
|
+
/**
|
|
41
|
+
* Every browser entry of the `@zappie/sdk` and `@zappie/foundations` installed under `root`, such as
|
|
42
|
+
* `@zappie/sdk/customer`, for Vite's `optimizeDeps.include`. A package that isn't installed, or that is linked from a
|
|
43
|
+
* workspace rather than installed, which Vite serves from source, adds none.
|
|
44
|
+
*
|
|
45
|
+
* @param root - The site's directory.
|
|
46
|
+
*/
|
|
47
|
+
declare function zappieDevEntries(root: string): string[];
|
|
38
48
|
/** Add source and component attributes to the intrinsic elements of one saved `.tsx` or `.jsx` file. */
|
|
39
49
|
declare function markSource(code: string, file: string): MarkedSource | null;
|
|
40
50
|
/**
|
|
@@ -83,6 +93,31 @@ declare function forwardUpload(origin: string, path: string, method?: string, ac
|
|
|
83
93
|
headers: Record<string, string>;
|
|
84
94
|
body: Buffer;
|
|
85
95
|
}>;
|
|
96
|
+
/**
|
|
97
|
+
* Build the site's Worker for a quick first page, and give each build its own id.
|
|
98
|
+
*
|
|
99
|
+
* - The Worker's code is minified, so each new isolate parses less before its first page.
|
|
100
|
+
* - `react-dom/server` and `react-dom/server.edge` become React's streaming renderer alone. Both also bundle React's
|
|
101
|
+
* older `renderToString` renderer, about 260 KB a Worker never runs: a storefront renders with
|
|
102
|
+
* `renderToReadableStream`, and a site that calls `renderToString` or `renderToStaticMarkup` fails its build.
|
|
103
|
+
* - `import.meta.env.ZAPPIE_DEPLOY_ID` is a new id for every build, so the Worker's page cache (`cachePage`'s
|
|
104
|
+
* `deployId`) starts afresh with each deploy, including one that changes only server code. On the dev server it is
|
|
105
|
+
* `dev`.
|
|
106
|
+
*
|
|
107
|
+
* The browser's code is unchanged, byte for byte.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* import { zappieWorker } from "@zappie/sdk/vite";
|
|
112
|
+
*
|
|
113
|
+
* export default defineConfig({
|
|
114
|
+
* plugins: [zappieWorker(), reactRouter()],
|
|
115
|
+
* });
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
declare function zappieWorker(): Plugin;
|
|
119
|
+
/** React's production streaming renderer for edge runtimes in the react-dom installed for `root`, if there is one. */
|
|
120
|
+
declare function streamingRenderer(root: string): string | undefined;
|
|
86
121
|
|
|
87
|
-
export { COMPONENT_ATTRIBUTE, SOURCE_ATTRIBUTE, forwardUpload, markSource, uploadsOrigin, zappieHoistImports, zappieSource, zappieUploads };
|
|
122
|
+
export { COMPONENT_ATTRIBUTE, SOURCE_ATTRIBUTE, forwardUpload, markSource, streamingRenderer, uploadsOrigin, zappieDevEntries, zappieHoistImports, zappieSource, zappieUploads, zappieWorker };
|
|
88
123
|
export type { MarkedSource, ZappieSourceOptions, ZappieUploadsOptions };
|
package/dist/vite/index.js
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
// src/vite/index.ts
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import path from "node:path";
|
|
2
6
|
import { parseSync } from "vite";
|
|
3
7
|
var SOURCE_ATTRIBUTE = "data-zappie-source";
|
|
4
8
|
var COMPONENT_ATTRIBUTE = "data-zappie-component";
|
|
@@ -7,13 +11,31 @@ function zappieSource({ previewHost }) {
|
|
|
7
11
|
return {
|
|
8
12
|
name: "zappie-source",
|
|
9
13
|
enforce: "pre",
|
|
10
|
-
apply: (_config, { command }) => command === "serve"
|
|
14
|
+
apply: (_config, { command }) => command === "serve",
|
|
15
|
+
config(config) {
|
|
16
|
+
root = path.resolve(config.root ?? process.cwd());
|
|
17
|
+
},
|
|
18
|
+
configEnvironment(name) {
|
|
19
|
+
if (name !== "client") {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
const include = zappieDevEntries(root);
|
|
23
|
+
return {
|
|
24
|
+
optimizeDeps: {
|
|
25
|
+
entries: ["app/**/*.{js,jsx,ts,tsx}"],
|
|
26
|
+
...include.length ? { include } : {}
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
},
|
|
11
30
|
configResolved(config) {
|
|
12
31
|
root = config.root;
|
|
13
32
|
},
|
|
14
33
|
transform: {
|
|
15
34
|
filter: { id: /\.[jt]sx$/ },
|
|
16
35
|
handler(code, id) {
|
|
36
|
+
if (!previewHost) {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
17
39
|
if (!id.startsWith(`${root}/`)) {
|
|
18
40
|
return null;
|
|
19
41
|
}
|
|
@@ -26,6 +48,37 @@ function zappieSource({ previewHost }) {
|
|
|
26
48
|
}
|
|
27
49
|
};
|
|
28
50
|
}
|
|
51
|
+
var SERVER_ONLY_ENTRIES = {
|
|
52
|
+
"@zappie/sdk": ["./vite", "./server", "./testing"],
|
|
53
|
+
"@zappie/foundations": ["./next"]
|
|
54
|
+
};
|
|
55
|
+
function zappieDevEntries(root) {
|
|
56
|
+
return Object.entries(SERVER_ONLY_ENTRIES).flatMap(([name, serverOnly]) => {
|
|
57
|
+
const manifest = installedManifest(root, name);
|
|
58
|
+
if (!manifest) {
|
|
59
|
+
return [];
|
|
60
|
+
}
|
|
61
|
+
const exports = manifest.exports;
|
|
62
|
+
const subpaths = exports && typeof exports === "object" && !Array.isArray(exports) ? Object.keys(exports).filter((key) => key.startsWith(".")) : ["."];
|
|
63
|
+
return subpaths.filter(
|
|
64
|
+
(subpath) => !serverOnly.includes(subpath) && !subpath.includes("*") && !/\.(?:css|json)$/.test(subpath)
|
|
65
|
+
).map(
|
|
66
|
+
(subpath) => subpath === "." ? name : `${name}${subpath.slice(1)}`
|
|
67
|
+
);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
function installedManifest(root, name) {
|
|
71
|
+
for (let directory = path.resolve(root); ; directory = path.dirname(directory)) {
|
|
72
|
+
const file = path.join(directory, "node_modules", name, "package.json");
|
|
73
|
+
if (existsSync(file)) {
|
|
74
|
+
const real = realpathSync(file);
|
|
75
|
+
return real.split(path.sep).includes("node_modules") ? JSON.parse(readFileSync(real, "utf8")) : void 0;
|
|
76
|
+
}
|
|
77
|
+
if (path.dirname(directory) === directory) {
|
|
78
|
+
return void 0;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
29
82
|
function markSource(code, file) {
|
|
30
83
|
if (!/^[\x21-\x7e]+$/.test(file)) {
|
|
31
84
|
return null;
|
|
@@ -204,12 +257,12 @@ function zappieUploads({ host }) {
|
|
|
204
257
|
apply: (_config, { command }) => command === "serve" && Boolean(origin),
|
|
205
258
|
configureServer(server) {
|
|
206
259
|
server.middlewares.use((request, response, next) => {
|
|
207
|
-
const
|
|
208
|
-
if (!origin || !
|
|
260
|
+
const path2 = request.url ?? "";
|
|
261
|
+
if (!origin || !path2.startsWith(UPLOADS_PREFIX)) {
|
|
209
262
|
next();
|
|
210
263
|
return;
|
|
211
264
|
}
|
|
212
|
-
void forwardUpload(origin,
|
|
265
|
+
void forwardUpload(origin, path2, request.method, request.headers.accept).then(({ status, headers, body }) => {
|
|
213
266
|
response.writeHead(status, headers);
|
|
214
267
|
response.end(body);
|
|
215
268
|
}).catch(() => {
|
|
@@ -231,7 +284,7 @@ function uploadsOrigin(host) {
|
|
|
231
284
|
return void 0;
|
|
232
285
|
}
|
|
233
286
|
}
|
|
234
|
-
async function forwardUpload(origin,
|
|
287
|
+
async function forwardUpload(origin, path2, method = "GET", accept) {
|
|
235
288
|
if (method !== "GET" && method !== "HEAD") {
|
|
236
289
|
return {
|
|
237
290
|
status: 405,
|
|
@@ -239,7 +292,7 @@ async function forwardUpload(origin, path, method = "GET", accept) {
|
|
|
239
292
|
body: Buffer.alloc(0)
|
|
240
293
|
};
|
|
241
294
|
}
|
|
242
|
-
const upstream = await fetch(`${origin}${
|
|
295
|
+
const upstream = await fetch(`${origin}${path2}`, {
|
|
243
296
|
method,
|
|
244
297
|
headers: accept ? { accept } : {}
|
|
245
298
|
});
|
|
@@ -256,13 +309,65 @@ async function forwardUpload(origin, path, method = "GET", accept) {
|
|
|
256
309
|
body: Buffer.from(await upstream.arrayBuffer())
|
|
257
310
|
};
|
|
258
311
|
}
|
|
312
|
+
function zappieWorker() {
|
|
313
|
+
let root = process.cwd();
|
|
314
|
+
let building = false;
|
|
315
|
+
let renderer;
|
|
316
|
+
return {
|
|
317
|
+
name: "zappie-worker",
|
|
318
|
+
enforce: "pre",
|
|
319
|
+
config(config, { command }) {
|
|
320
|
+
root = path.resolve(config.root ?? process.cwd());
|
|
321
|
+
building = command === "build";
|
|
322
|
+
return {
|
|
323
|
+
define: {
|
|
324
|
+
"import.meta.env.ZAPPIE_DEPLOY_ID": JSON.stringify(
|
|
325
|
+
building ? randomBytes(8).toString("hex") : "dev"
|
|
326
|
+
)
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
},
|
|
330
|
+
configEnvironment(name) {
|
|
331
|
+
return building && name !== "client" ? { build: { minify: true } } : void 0;
|
|
332
|
+
},
|
|
333
|
+
resolveId: {
|
|
334
|
+
filter: { id: STREAMING_ONLY },
|
|
335
|
+
handler(source) {
|
|
336
|
+
if (!building || this.environment.config.consumer === "client" || !STREAMING_ONLY.test(source)) {
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
renderer ?? (renderer = streamingRenderer(root) ?? null);
|
|
340
|
+
return renderer;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
var STREAMING_ONLY = /^react-dom\/server(?:\.edge)?$/;
|
|
346
|
+
function streamingRenderer(root) {
|
|
347
|
+
try {
|
|
348
|
+
const manifest = createRequire(path.join(root, "package.json")).resolve(
|
|
349
|
+
"react-dom/package.json"
|
|
350
|
+
);
|
|
351
|
+
const file = path.join(
|
|
352
|
+
path.dirname(manifest),
|
|
353
|
+
"cjs",
|
|
354
|
+
"react-dom-server.edge.production.js"
|
|
355
|
+
);
|
|
356
|
+
return existsSync(file) ? file : void 0;
|
|
357
|
+
} catch {
|
|
358
|
+
return void 0;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
259
361
|
export {
|
|
260
362
|
COMPONENT_ATTRIBUTE,
|
|
261
363
|
SOURCE_ATTRIBUTE,
|
|
262
364
|
forwardUpload,
|
|
263
365
|
markSource,
|
|
366
|
+
streamingRenderer,
|
|
264
367
|
uploadsOrigin,
|
|
368
|
+
zappieDevEntries,
|
|
265
369
|
zappieHoistImports,
|
|
266
370
|
zappieSource,
|
|
267
|
-
zappieUploads
|
|
371
|
+
zappieUploads,
|
|
372
|
+
zappieWorker
|
|
268
373
|
};
|