@zappie/sdk 0.21.0 → 0.23.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 +16 -0
- package/README.md +18 -1
- package/dist/debug.js +1 -1
- package/dist/error-pages/art.js +1 -1
- package/dist/error-pages/art.js.map +1 -1
- package/dist/error-pages/index.d.ts +37 -6
- package/dist/error-pages/index.js +7 -2
- package/dist/error-pages/index.js.map +1 -1
- package/dist/error-pages/react.d.ts +5 -4
- package/dist/error-pages/react.js +1 -1
- package/dist/error-pages/react.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/server/edge-cache.js +1 -1
- package/dist/server/edge-cache.js.map +1 -1
- package/dist/server/index.d.ts +40 -9
- package/dist/server/index.js +1 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/site-worker.js +1 -1
- package/dist/server/site-worker.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# @zappie/sdk
|
|
2
2
|
|
|
3
|
+
## 0.23.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 716dcd0: The edge caches key pages and store reads by the store's data version, which Zappie hosting sends in `x-zappie-data-version` and moves on each change the merchant makes to what the live site shows. A changed price, item, stock level, menu, branch or site setting now shows at the next visit at every Cloudflare location, where it used to wait up to eleven minutes for the cached copies to expire. `cachePage` and `siteWorker` remember the version for the request's `ctx`, and `cachedApiFetch({ ctx })` reads it from there, so a site that passes the same `ctx` to both changes nothing. `rememberDataVersion(request, ctx)` and `cachedApiFetch({ dataVersion })` cover a Worker that renders another way. Without the header both cache keys stay as they were.
|
|
8
|
+
|
|
9
|
+
## 0.22.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- 48bff20: `platformErrorDocument`, `platformErrorMarkup`, `platformErrorResponse`, `withPlatformErrorPage` and `PlatformErrorPage` take an optional `store` (`{ name, href?, logo? }`, the `PlatformErrorStore` type). Given one, the page leads with the store's logo or name over the heading, linking to the store's home, names the store in the title, and credits Zappie with "Powered by Zappie" in one line. Zee and the Zappie logo show only on Zappie's own page, which is unchanged when no store is given.
|
|
14
|
+
|
|
15
|
+
`siteWorker` takes the same `store`, or a function of the Worker's variables that returns it, for the page it answers with when the handler throws.
|
|
16
|
+
|
|
17
|
+
New `platformErrorTree` (with the `PlatformErrorNode` type) gives the page's `<main>` as a tree of elements. `platformErrorMarkup` writes it as HTML and `PlatformErrorPage` draws it in React, so the two always match.
|
|
18
|
+
|
|
3
19
|
## 0.21.0
|
|
4
20
|
|
|
5
21
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -137,7 +137,12 @@ export function ErrorBoundary() {
|
|
|
137
137
|
|
|
138
138
|
Zappie's own pages in `@zappie/sdk/error-pages` are for the site host, which
|
|
139
139
|
answers with them when a site can't answer at all. A Worker you host yourself
|
|
140
|
-
can return `platformErrorResponse("went-wrong")` when its handler throws.
|
|
140
|
+
can return `platformErrorResponse("went-wrong")` when its handler throws. Pass
|
|
141
|
+
`{ store: { name, href, logo } }` and the page leads with your store: its logo,
|
|
142
|
+
or its name, over the heading and linking home, with "Powered by Zappie" in one
|
|
143
|
+
line at the foot. Without a store it is Zappie's own page, with the Zappie logo
|
|
144
|
+
and Zee. `siteWorker({ store })` from `@zappie/sdk/server` uses the store on the
|
|
145
|
+
page it answers with when your handler throws.
|
|
141
146
|
|
|
142
147
|
When the merchant switches the storefront off, the site host asks your Worker
|
|
143
148
|
for each page with the closed state. Draw your own closed page in your header
|
|
@@ -456,6 +461,18 @@ cached HTML page gets a new CSP nonce in its policy and its markup for each
|
|
|
456
461
|
shopper. `x-zappie-edge-cache` says how each response was answered: `HIT`,
|
|
457
462
|
`STALE`, `MISS` or `BYPASS`.
|
|
458
463
|
|
|
464
|
+
Zappie hosting sends each live request with the store's data version in
|
|
465
|
+
`x-zappie-data-version` (`DATA_VERSION_HEADER`). It moves on each change the
|
|
466
|
+
merchant makes to what the site shows: an item, a price, stock, a menu, a
|
|
467
|
+
branch, the store's details or its site settings. Both caches key by it, so a
|
|
468
|
+
change shows at the next visit at every Cloudflare location instead of when
|
|
469
|
+
the cached copies expire. `cachePage` remembers the version for its `ctx`, and
|
|
470
|
+
`cachedApiFetch({ ctx })` reads it from there, so a site that passes the same
|
|
471
|
+
`ctx` to both needs nothing more. A Worker that renders without `cachePage`
|
|
472
|
+
calls `rememberDataVersion(request, ctx)` first, or passes
|
|
473
|
+
`cachedApiFetch({ dataVersion })`. Without the header both keys stay as they
|
|
474
|
+
were.
|
|
475
|
+
|
|
459
476
|
```ts
|
|
460
477
|
import { cachePage, cachedApiFetch } from "@zappie/sdk/server";
|
|
461
478
|
|
package/dist/debug.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var VERSION=true?"0.
|
|
1
|
+
var VERSION=true?"0.23.0":"0.0.0-development";function installDebug(client){if(typeof window==="undefined"||client.mode!=="test"){return}const events=[];let quote;const emit=(name,detail)=>{const event={name,detail,at:new Date().toISOString()};events.push(event);window.dispatchEvent(new CustomEvent("zappie:event",{detail:event}))};globalThis.__zappieEmit=emit;window.__zappie={version:VERSION,store:client.config.store,async catalogue(){await client.cart.hydrate();const branch=(await client.store.get()).branches.find(value=>value.id===client.cart.getSnapshot().branchId);return{branch,menu:await client.menu.get({branch:branch.id})}},cart:Object.assign(()=>client.cart.getSnapshot(),{async inject(input){await client.cart.hydrate();if(input.lines.length>100||input.lines.some(line=>!Number.isInteger(line.quantity??1)||(line.quantity??1)<1||(line.quantity??1)>99)){throw new Error("Use up to 100 cart lines with whole quantities from 1 to 99.")}const snapshot=client.cart.getSnapshot();const value={v:1,menuVersion:client._internal.cartCatalogue().version,updatedAt:Date.now(),fulfilment:snapshot.fulfilment,promoCode:snapshot.promoCode,lines:input.lines.map((line,index)=>({...line,id:`debug_${index}`,name:line.itemId,quantity:line.quantity??1,choices:(line.choices??[]).map(choice=>({...choice,quantity:choice.quantity??1})),inputs:line.inputs??{},addedAt:new Date().toISOString()}))};const scope=client.config.cart?.storageScope;(client.config.storage??window.localStorage).setItem(`zappie:cart:v1:${client.config.store}:${snapshot.branchId}${scope?`:${scope}`:""}`,JSON.stringify(value))}}),quote:()=>quote,events};client.on("add_to_cart",detail=>emit("add_to_cart",detail));client.cart.subscribe(()=>{const state=client.cart.state;const next="quote"in state?state.quote:void 0;if(next&&next!==quote){quote=next;emit("quote",next)}})}export{installDebug};
|
|
2
2
|
//# sourceMappingURL=debug.js.map
|
package/dist/error-pages/art.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var LOGO='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 153 31" width="118" height="24"><path d="M0 10.
|
|
1
|
+
var LOGO='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 153 31" width="118" height="24"><path d="M0 10.1L10.1 0H30.4V10.1L18 15.2L20.3 10.1H0Z" fill="#9FE870"/><path d="M30.4 20.3L20.3 30.4H0V20.3L12.4 15.2L10.1 20.3H30.4Z" fill="#9FE870"/><path d="M46.60 5.95H60.20V9.25L51.25 20.11H60.50V23.41H46.20V20.11L55.15 9.25H46.60Z" fill="{word}"/><path d="M63.21 18.4C63.21 15.7 65.1 13.6 69.8 13.6H76.2V12.4C76.2 9.8 74.7 8.6 71.6 8.6C68.9 8.6 67.4 9.6 67.4 11.6C67.4 11.7 67.4 12 67.4 12.3H63.8C63.8 12 63.7 11.6 63.7 11.3C63.7 7.7 66.7 5.7 71.7 5.7C77 5.7 80.1 8.2 80.1 12.8V23.4H76.2C76.3 22.6 76.4 21 76.4 19.6C75.8 22.1 73.7 23.7 69.8 23.7C65.9 23.7 63.2 21.8 63.2 18.4H63.21ZM76.2 16.4V16H70.1C67.8 16 66.9 16.8 66.9 18.2C66.9 19.8 68.3 20.7 70.7 20.7C74.1 20.7 76.2 19.1 76.2 16.4Z" fill="{word}"/><path d="M84.1 5.9H88L88 10C88.7 7.4 91 5.6 94.5 5.6C99.5 5.6 102.6 9.1 102.6 14.3C102.6 20 99.5 23.6 94.4 23.6C90.9 23.6 88.7 22.1 88 19.8C88 21 88.1 22.8 88.1 23.5V30.4H84.1V5.9L84.1 5.9ZM98.7 14.5C98.7 11.2 96.7 9 93.6 9C90.4 9 88.1 11.2 88 14.7V15.6C88 18.6 90.3 20.5 93.6 20.5C96.7 20.5 98.7 18.1 98.7 14.5Z" fill="{word}"/><path d="M106.18 5.9H110.1L110.1 10C110.8 7.4 113.1 5.6 116.6 5.6C121.6 5.6 124.7 9.1 124.7 14.3C124.7 20 121.6 23.6 116.5 23.6C113 23.6 110.8 22.1 110.1 19.8C110.1 21 110.2 22.8 110.2 23.5V30.4H106.2V5.9L106.18 5.9ZM120.8 14.5C120.8 11.2 118.8 9 115.7 9C112.5 9 110.2 11.2 110.1 14.7V15.6C110.1 18.6 112.4 20.5 115.74 20.5C118.8 20.5 120.8 18.1 120.8 14.5Z" fill="{word}"/><path d="M128.3 0H132.4V3.9H128.3V0ZM128.3 5.9H132.3V23.4H128.3V5.9Z" fill="{word}"/><path d="M153 15.5H139.9C140.1 18.8 142 20.6 144.96 20.6C147.5 20.6 149.25 19.5 149.4 17.5H153C152.9 21.4 149.7 23.7 144.9 23.7C139.4 23.7 135.9 20.3 135.9 14.8C135.9 9.3 139.4 5.7 144.9 5.7C149.8 5.7 153 8.6 153 14.1V15.5H153ZM149.4 12.8C149.4 10.2 147.8 8.8 144.9 8.8C142 8.8 140.4 10.2 140 13.1H149.4V12.9V12.8Z" fill="{word}"/></svg>';var ZEE={"not-found":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -8 120 128" width="112" height="120"><defs><linearGradient id="zpe-head" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#C2F3A3"/><stop offset=".55" stop-color="#9FE870"/><stop offset="1" stop-color="#86DB52"/></linearGradient><linearGradient id="zpe-hand" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#FAFAF8"/><stop offset="1" stop-color="#E4E6DC"/></linearGradient></defs><g><rect x="18" y="20" width="84" height="80" rx="28" fill="url(#zpe-head)"/><rect x="18" y="20" width="84" height="80" rx="28" fill="none" stroke="#FFFFFF" stroke-opacity=".35" stroke-width="2"/><path d="M60 24V12h10L50 2h20" fill="none" stroke="#86DB52" stroke-width="4.5" stroke-linecap="round" stroke-linejoin="round"/><ellipse cx="36" cy="79" rx="8" ry="4.5" fill="#FFFFFF"/><ellipse cx="84" cy="79" rx="8" ry="4.5" fill="#FFFFFF"/><g transform="translate(43.5 57) scale(1.08) translate(-43.5 -57)"><rect x="37" y="46" width="13" height="22" rx="6.5" fill="#121A0E"/><circle cx="41" cy="51" r="2.6" fill="#FFFFFF"/></g><g transform="translate(76.5 57) scale(1.08) translate(-76.5 -57)"><rect x="70" y="46" width="13" height="22" rx="6.5" fill="#121A0E"/><circle cx="74" cy="51" r="2.6" fill="#FFFFFF"/></g><ellipse cx="60" cy="81" rx="4.2" ry="5.5" fill="#121A0E"/><circle cx="15" cy="103" r="9.5" fill="url(#zpe-hand)"/><circle cx="105" cy="103" r="9.5" fill="url(#zpe-hand)"/></g></svg>',"went-wrong":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -8 120 128" width="112" height="120"><defs><linearGradient id="zpe-head" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#C2F3A3"/><stop offset=".55" stop-color="#9FE870"/><stop offset="1" stop-color="#86DB52"/></linearGradient><linearGradient id="zpe-hand" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#FAFAF8"/><stop offset="1" stop-color="#E4E6DC"/></linearGradient></defs><g><rect x="18" y="20" width="84" height="80" rx="28" fill="url(#zpe-head)"/><rect x="18" y="20" width="84" height="80" rx="28" fill="none" stroke="#FFFFFF" stroke-opacity=".35" stroke-width="2"/><path d="M60 24V12h10L50 2h20" fill="none" stroke="#86DB52" stroke-width="4.5" stroke-linecap="round" stroke-linejoin="round" transform="rotate(-20 60 24) translate(0 1)"/><ellipse cx="36" cy="79" rx="8" ry="4.5" fill="#FFFFFF"/><ellipse cx="84" cy="79" rx="8" ry="4.5" fill="#FFFFFF"/><g transform="translate(0 2)"><g><rect x="37" y="46" width="13" height="22" rx="6.5" fill="#121A0E"/><circle cx="41" cy="51" r="2.6" fill="#FFFFFF" transform="translate(0 2)"/></g><g><rect x="70" y="46" width="13" height="22" rx="6.5" fill="#121A0E"/><circle cx="74" cy="51" r="2.6" fill="#FFFFFF" transform="translate(0 2)"/></g></g><path d="M36 40l14 5" fill="none" stroke="#121A0E" stroke-width="3.4" stroke-linecap="round" transform="translate(0 -3) rotate(-38 43 42.5)"/><path d="M84 40l-14 5" fill="none" stroke="#121A0E" stroke-width="3.4" stroke-linecap="round" transform="translate(0 -3) rotate(38 77 42.5)"/><path d="M53 83q7-5.5 14 0" fill="none" stroke="#121A0E" stroke-width="3.6" stroke-linecap="round"/><circle cx="15" cy="103" r="9.5" fill="url(#zpe-hand)"/><circle cx="105" cy="103" r="9.5" fill="url(#zpe-hand)"/></g></svg>'};export{LOGO,ZEE};
|
|
2
2
|
//# sourceMappingURL=art.js.map
|
|
@@ -1,13 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The two pages Zappie's site host answers with when a site can't. `not-found` is a page or a table code that
|
|
3
|
-
* doesn't exist (404). `went-wrong` is a page the site could not render (500).
|
|
4
|
-
* `siteError` from
|
|
3
|
+
* doesn't exist (404). `went-wrong` is a page the site could not render (500). Given a `store`, a page leads with the
|
|
4
|
+
* store and credits Zappie in one line. Storefronts draw their own pages with `siteError` from
|
|
5
|
+
* `@zappie/sdk/site-error`.
|
|
5
6
|
*/
|
|
6
7
|
type PlatformErrorKind = "not-found" | "went-wrong";
|
|
7
|
-
/**
|
|
8
|
+
/** The store a page belongs to. */
|
|
9
|
+
type PlatformErrorStore = {
|
|
10
|
+
/** The store's name, shown over the heading and as the page's title. */
|
|
11
|
+
name: string;
|
|
12
|
+
/** Where the store's name leads. Default the page's `home`. */
|
|
13
|
+
href?: string;
|
|
14
|
+
/** The store's logo as an image URL, shown in place of its name. */
|
|
15
|
+
logo?: string;
|
|
16
|
+
};
|
|
17
|
+
/** Where the page's links lead, and whose page it is. */
|
|
8
18
|
type PlatformErrorOptions = {
|
|
9
19
|
/** The storefront's home page. Default `/`. */
|
|
10
20
|
home?: string;
|
|
21
|
+
/** The store the page belongs to. Leave it out for Zappie's own page, with the Zappie logo and Zee. */
|
|
22
|
+
store?: PlatformErrorStore;
|
|
11
23
|
};
|
|
12
24
|
/** One of the page's links. An empty `href` reloads the address the guest is on. */
|
|
13
25
|
type PlatformErrorAction = {
|
|
@@ -28,6 +40,10 @@ type PlatformErrorParts = {
|
|
|
28
40
|
/** Zee as an image source: surprised for a missing page, sad for a failed one. */
|
|
29
41
|
zee: string;
|
|
30
42
|
actions: PlatformErrorAction[];
|
|
43
|
+
/** The store the page belongs to, with its link resolved. Zappie's own page has none. */
|
|
44
|
+
store?: PlatformErrorStore & {
|
|
45
|
+
href: string;
|
|
46
|
+
};
|
|
31
47
|
};
|
|
32
48
|
/** The HTTP status each page answers with. */
|
|
33
49
|
declare function platformErrorStatus(kind: PlatformErrorKind): number;
|
|
@@ -36,11 +52,26 @@ declare function platformErrorStatus(kind: PlatformErrorKind): number;
|
|
|
36
52
|
*/
|
|
37
53
|
declare function platformErrorKind(error: unknown): PlatformErrorKind;
|
|
38
54
|
/** The words, artwork and links of the page for `kind`. */
|
|
39
|
-
declare function platformErrorParts(kind: PlatformErrorKind, { home }?: PlatformErrorOptions): PlatformErrorParts;
|
|
55
|
+
declare function platformErrorParts(kind: PlatformErrorKind, { home, store }?: PlatformErrorOptions): PlatformErrorParts;
|
|
40
56
|
/** The page's stylesheet. */
|
|
41
57
|
declare const PLATFORM_ERROR_STYLES: string;
|
|
42
58
|
/** The Geist stylesheet the page's type comes from. */
|
|
43
59
|
declare const PLATFORM_ERROR_FONTS = "https://fonts.googleapis.com/css2?family=Geist:wght@400;600&display=swap";
|
|
60
|
+
/** Where the store page's "Powered by Zappie" credit leads. */
|
|
61
|
+
declare const PLATFORM_ERROR_CREDIT = "https://zappie.ai";
|
|
62
|
+
/**
|
|
63
|
+
* One element of the page: its tag, its attributes as React names them, and its children. Text is plain, never HTML.
|
|
64
|
+
*/
|
|
65
|
+
type PlatformErrorNode = [
|
|
66
|
+
tag: string,
|
|
67
|
+
attributes: Record<string, string>,
|
|
68
|
+
...children: (PlatformErrorNode | string)[]
|
|
69
|
+
];
|
|
70
|
+
/**
|
|
71
|
+
* The page's `<main>` element as a tree, which `platformErrorMarkup` writes as HTML and `PlatformErrorPage` draws in
|
|
72
|
+
* React, so the two always match.
|
|
73
|
+
*/
|
|
74
|
+
declare function platformErrorTree(kind: PlatformErrorKind, options?: PlatformErrorOptions): PlatformErrorNode;
|
|
44
75
|
/** The page's `<main>` element as HTML. `PlatformErrorPage` from `@zappie/sdk/error-pages/react` draws the same. */
|
|
45
76
|
declare function platformErrorMarkup(kind: PlatformErrorKind, options?: PlatformErrorOptions): string;
|
|
46
77
|
/** A complete HTML document for the page, for a server or Worker answering without the site's own code. */
|
|
@@ -54,5 +85,5 @@ declare function withPlatformErrorPage(response: Response, options?: PlatformErr
|
|
|
54
85
|
/** The page as a Response with its status, for a site's Worker to return when its own rendering fails. */
|
|
55
86
|
declare function platformErrorResponse(kind: PlatformErrorKind, options?: PlatformErrorOptions): Response;
|
|
56
87
|
|
|
57
|
-
export { PLATFORM_ERROR_FONTS, PLATFORM_ERROR_STYLES, platformErrorDocument, platformErrorKind, platformErrorMarkup, platformErrorParts, platformErrorResponse, platformErrorStatus, withPlatformErrorPage };
|
|
58
|
-
export type { PlatformErrorAction, PlatformErrorKind, PlatformErrorOptions, PlatformErrorParts };
|
|
88
|
+
export { PLATFORM_ERROR_CREDIT, PLATFORM_ERROR_FONTS, PLATFORM_ERROR_STYLES, platformErrorDocument, platformErrorKind, platformErrorMarkup, platformErrorParts, platformErrorResponse, platformErrorStatus, platformErrorTree, withPlatformErrorPage };
|
|
89
|
+
export type { PlatformErrorAction, PlatformErrorKind, PlatformErrorNode, PlatformErrorOptions, PlatformErrorParts, PlatformErrorStore };
|
|
@@ -1,11 +1,16 @@
|
|
|
1
|
-
import{LOGO,ZEE}from"./art.js";var STATUS={"not-found":404,"went-wrong":500};var COPY={"not-found":{title:"We couldn't find that page",text:"The link or code you followed may be out of date, or the page may have moved."},"went-wrong":{title:"Something went wrong",text:"This page didn't load. Try again, or go to the home page."}};function platformErrorStatus(kind){return STATUS[kind]}function platformErrorKind(error){const status=typeof error==="object"&&error!==null&&"status"in error?error.status:void 0;return status===404||status===410?"not-found":"went-wrong"}var image=svg=>`data:image/svg+xml,${svg.replace(/["#%<> ]/g,character=>character==='"'?"'":encodeURIComponent(character))}`;function platformErrorParts(kind,{home="/"}={}){const homeAction=primary=>({label:"Go to the home page",href:home,primary});return{kind,...COPY[kind],logo:{light:image(LOGO.replaceAll("{word}","#121A0E")),dark:image(LOGO.replaceAll("{word}","#F1F1F1"))},zee:image(ZEE[kind]),actions:kind==="went-wrong"?[{label:"Try again",href:"",primary:true},homeAction(false)]:[homeAction(true)]}}var PLATFORM_ERROR_STYLES=`main.zpe{--zpe-bg:#fff;--zpe-fg:#121A0E;--zpe-fg2:#4A4A4A;--zpe-surface:#fff;--zpe-edge:#8A8A8A;--zpe-hover:#F5F5F5;position:fixed;inset:0;z-index:2147483000;overflow-y:auto;box-sizing:border-box;display:grid;grid-template-rows:auto 1fr;gap:24px;width:auto;max-width:none;margin:0;padding:24px 40px;background:var(--zpe-bg);color:var(--zpe-fg);font-family:Geist,system-ui,-apple-system,Roboto,sans-serif;font-size:15px;font-weight:400;line-height:22px;letter-spacing:-.003em;text-align:center}
|
|
1
|
+
import{LOGO,ZEE}from"./art.js";var STATUS={"not-found":404,"went-wrong":500};var COPY={"not-found":{title:"We couldn't find that page",text:"The link or code you followed may be out of date, or the page may have moved."},"went-wrong":{title:"Something went wrong",text:"This page didn't load. Try again, or go to the home page."}};function platformErrorStatus(kind){return STATUS[kind]}function platformErrorKind(error){const status=typeof error==="object"&&error!==null&&"status"in error?error.status:void 0;return status===404||status===410?"not-found":"went-wrong"}var image=svg=>`data:image/svg+xml,${svg.replace(/["#%<> ]/g,character=>character==='"'?"'":encodeURIComponent(character))}`;function platformErrorParts(kind,{home="/",store}={}){const homeAction=primary=>({label:"Go to the home page",href:home,primary});return{kind,...COPY[kind],logo:{light:image(LOGO.replaceAll("{word}","#121A0E")),dark:image(LOGO.replaceAll("{word}","#F1F1F1"))},zee:image(ZEE[kind]),actions:kind==="went-wrong"?[{label:"Try again",href:"",primary:true},homeAction(false)]:[homeAction(true)],...store?.name.trim()?{store:{...store,name:store.name.trim(),href:store.href??home}}:{}}}var PLATFORM_ERROR_STYLES=`main.zpe{--zpe-bg:#fff;--zpe-fg:#121A0E;--zpe-fg2:#4A4A4A;--zpe-surface:#fff;--zpe-edge:#8A8A8A;--zpe-hover:#F5F5F5;position:fixed;inset:0;z-index:2147483000;overflow-y:auto;box-sizing:border-box;display:grid;grid-template-rows:auto 1fr;gap:24px;width:auto;max-width:none;margin:0;padding:24px 40px;background:var(--zpe-bg);color:var(--zpe-fg);font-family:Geist,system-ui,-apple-system,Roboto,sans-serif;font-size:15px;font-weight:400;line-height:22px;letter-spacing:-.003em;text-align:center}
|
|
2
2
|
@media (prefers-color-scheme:dark){main.zpe{--zpe-bg:#1A1A1A;--zpe-fg:#F1F1F1;--zpe-fg2:#C4C4C4;--zpe-surface:#212121;--zpe-edge:#6B6B6B;--zpe-hover:#2A2A2A;color-scheme:dark}}
|
|
3
|
+
main.zpe[data-store]{grid-template-rows:1fr auto}
|
|
3
4
|
.zpe .zpe-brand{display:flex;justify-content:center}
|
|
4
5
|
.zpe .zpe-brand img{display:block;width:118px;height:24px}
|
|
5
6
|
.zpe .zpe-center{display:grid;place-items:center;min-width:0}
|
|
6
7
|
.zpe .zpe-body{display:grid;gap:12px;justify-items:center;width:100%;max-width:400px;animation:zpe-enter .2s cubic-bezier(.2,0,0,1) both}
|
|
7
8
|
.zpe .zpe-zee{display:block;width:112px;height:120px;max-width:none;margin:0 0 4px;animation:zpe-float 4.2s cubic-bezier(.4,0,.2,1) infinite}
|
|
8
9
|
.zpe[data-kind=went-wrong] .zpe-zee{animation-duration:6s}
|
|
10
|
+
.zpe .zpe-store{display:block;max-width:100%;margin:0 0 4px;color:var(--zpe-fg);font-size:17px;line-height:24px;font-weight:600;text-decoration:none;overflow-wrap:anywhere}
|
|
11
|
+
.zpe .zpe-store img{display:block;max-width:200px;max-height:56px}
|
|
12
|
+
.zpe .zpe-credit{margin:0;color:var(--zpe-fg2);font-size:13px;line-height:20px}
|
|
13
|
+
.zpe .zpe-credit a{color:inherit}
|
|
9
14
|
.zpe .zpe-title{margin:0;padding:0;color:var(--zpe-fg);font:inherit;font-size:26px;line-height:32px;font-weight:600;letter-spacing:-.022em;text-wrap:balance}
|
|
10
15
|
.zpe .zpe-text{margin:0;padding:0;max-width:52ch;color:var(--zpe-fg2);font:inherit;text-wrap:pretty}
|
|
11
16
|
.zpe .zpe-actions{display:flex;flex-wrap:wrap;justify-content:center;gap:8px;margin-top:4px}
|
|
@@ -17,5 +22,5 @@ import{LOGO,ZEE}from"./art.js";var STATUS={"not-found":404,"went-wrong":500};var
|
|
|
17
22
|
@media (max-width:767px){main.zpe{padding:24px 16px}.zpe .zpe-body{align-self:start;margin-top:12vh}.zpe .zpe-actions{flex-direction:column-reverse;align-self:stretch;width:100%}.zpe .zpe-button{width:100%}}
|
|
18
23
|
@media (prefers-reduced-motion:reduce){.zpe .zpe-body,.zpe .zpe-zee{animation:none}}
|
|
19
24
|
@keyframes zpe-enter{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
|
|
20
|
-
@keyframes zpe-float{0%,100%{transform:translateY(0)}50%{transform:translateY(-3px)}}`;var PLATFORM_ERROR_FONTS="https://fonts.googleapis.com/css2?family=Geist:wght@400;600&display=swap";var escape=text=>text.replace(/[&<>"
|
|
25
|
+
@keyframes zpe-float{0%,100%{transform:translateY(0)}50%{transform:translateY(-3px)}}`;var PLATFORM_ERROR_FONTS="https://fonts.googleapis.com/css2?family=Geist:wght@400;600&display=swap";var escape=text=>text.replace(/[&<>"]/g,character=>({"&":"&","<":"<",">":">",'"':"""})[character]??character);var PLATFORM_ERROR_CREDIT="https://zappie.ai";function platformErrorTree(kind,options={}){const parts=platformErrorParts(kind,options);const{store}=parts;const center=["div",{className:"zpe-center"},["div",{className:"zpe-body"},store?["a",{className:"zpe-store",href:store.href},store.logo?["img",{alt:store.name,src:store.logo}]:store.name]:["img",{className:"zpe-zee",alt:"",width:"112",height:"120",src:parts.zee}],["h1",{className:"zpe-title"},parts.title],["p",{className:"zpe-text"},parts.text],["div",{className:"zpe-actions"},...parts.actions.map(action=>["a",{className:action.primary?"zpe-button zpe-primary":"zpe-button",href:action.href},action.label])]]];return store?["main",{className:"zpe","data-kind":kind,"data-store":""},center,["p",{className:"zpe-credit"},"Powered by ",["a",{href:PLATFORM_ERROR_CREDIT,"data-zappie-attribution":""},"Zappie"]]]:["main",{className:"zpe","data-kind":kind},["div",{className:"zpe-brand"},["picture",{},["source",{srcSet:parts.logo.dark,media:"(prefers-color-scheme: dark)"}],["img",{alt:"Zappie",width:"118",height:"24",src:parts.logo.light}]]],center]}var html=node=>{if(typeof node==="string"){return escape(node)}const[tag,attributes,...children]=node;const open=`<${tag}${Object.entries(attributes).map(([name,value])=>` ${name==="className"?"class":name.toLowerCase()}="${escape(value)}"`).join("")}>`;return tag==="img"||tag==="source"?open:`${open}${children.map(html).join("")}</${tag}>`};function platformErrorMarkup(kind,options={}){return html(platformErrorTree(kind,options))}function platformErrorDocument(kind,options={}){const store=platformErrorParts(kind,options).store;return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${escape(COPY[kind].title)}${store?` | ${escape(store.name)}`:""}</title><link rel="stylesheet" href="${escape(PLATFORM_ERROR_FONTS)}"><style>${PLATFORM_ERROR_STYLES}</style></head><body style="margin:0">${platformErrorMarkup(kind,options)}</body></html>`}function withPlatformErrorPage(response,options={}){const status=response.status;const kind=status===404||status===410?"not-found":status>=500?"went-wrong":void 0;if(!kind||!/^text\/html/i.test(response.headers.get("content-type")??"")){return response}response.body?.cancel().catch(()=>void 0);const headers=new Headers(response.headers);for(const name of["content-length","content-encoding","etag"]){headers.delete(name)}headers.set("content-type","text/html; charset=utf-8");headers.set("cache-control","no-store");return new Response(platformErrorDocument(kind,options),{status,statusText:response.statusText,headers})}function platformErrorResponse(kind,options={}){return new Response(platformErrorDocument(kind,options),{status:STATUS[kind],headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}export{PLATFORM_ERROR_CREDIT,PLATFORM_ERROR_FONTS,PLATFORM_ERROR_STYLES,platformErrorDocument,platformErrorKind,platformErrorMarkup,platformErrorParts,platformErrorResponse,platformErrorStatus,platformErrorTree,withPlatformErrorPage};
|
|
21
26
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/error-pages/index.ts"],
|
|
4
|
-
"mappings": "AAAA,OAAS,KAAM,QAAW,
|
|
4
|
+
"mappings": "AAAA,OAAS,KAAM,QAAW,WAiD1B,IAAM,OAA4C,CAChD,YAAa,IACb,aAAc,GAChB,EAEA,IAAM,KAAmE,CACvE,YAAa,CACX,MAAO,6BACP,KAAM,+EACR,EACA,aAAc,CACZ,MAAO,uBACP,KAAM,2DACR,CACF,EAGO,SAAS,oBAAoB,KAAiC,CACnE,OAAO,OAAO,IAAI,CACpB,CAKO,SAAS,kBAAkB,MAAmC,CACnE,MAAM,OACJ,OAAO,QAAU,UAAY,QAAU,MAAQ,WAAY,MACvD,MAAM,OACN,OACN,OAAO,SAAW,KAAO,SAAW,IAAM,YAAc,YAC1D,CAGA,IAAM,MAAS,KACb,sBAAsB,IAAI,QAAQ,YAAc,WAAe,YAA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|
5
5
|
"names": []
|
|
6
6
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { PlatformErrorOptions, PlatformErrorKind } from '@zappie/sdk/error-pages';
|
|
3
|
-
export { PlatformErrorKind, PlatformErrorOptions, platformErrorKind } from '@zappie/sdk/error-pages';
|
|
3
|
+
export { PlatformErrorKind, PlatformErrorOptions, PlatformErrorStore, platformErrorKind } from '@zappie/sdk/error-pages';
|
|
4
4
|
|
|
5
5
|
/** Props for `PlatformErrorPage`. */
|
|
6
6
|
type PlatformErrorPageProps = PlatformErrorOptions & {
|
|
@@ -11,10 +11,11 @@ type PlatformErrorPageProps = PlatformErrorOptions & {
|
|
|
11
11
|
};
|
|
12
12
|
/**
|
|
13
13
|
* Zappie's page for a missing page (`not-found`) or a failed one (`went-wrong`). It is the site host's fallback for a
|
|
14
|
-
* site that can't answer.
|
|
15
|
-
* covers the whole window, over anything the site
|
|
14
|
+
* site that can't answer. Given a `store`, it leads with the store and credits Zappie in one line. A storefront draws
|
|
15
|
+
* its own pages with `siteError` from `@zappie/sdk/site-error`. It covers the whole window, over anything the site
|
|
16
|
+
* draws around it.
|
|
16
17
|
*/
|
|
17
|
-
declare function PlatformErrorPage({ kind, error, home, }: PlatformErrorPageProps): react.JSX.Element;
|
|
18
|
+
declare function PlatformErrorPage({ kind, error, home, store, }: PlatformErrorPageProps): react.JSX.Element;
|
|
18
19
|
|
|
19
20
|
export { PlatformErrorPage };
|
|
20
21
|
export type { PlatformErrorPageProps };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{PLATFORM_ERROR_FONTS,PLATFORM_ERROR_STYLES,platformErrorKind,
|
|
1
|
+
import{PLATFORM_ERROR_FONTS,PLATFORM_ERROR_STYLES,platformErrorKind,platformErrorTree}from"@zappie/sdk/error-pages";import{createElement,Fragment}from"react";import{platformErrorKind as platformErrorKind2}from"@zappie/sdk/error-pages";import{jsx,jsxs}from"react/jsx-runtime";var draw=node=>{if(typeof node==="string"){return node}const[tag,attributes,...children]=node;return createElement(tag,attributes,...children.map(draw))};function PlatformErrorPage({kind,error,home,store}){return jsxs(Fragment,{children:[jsx("link",{rel:"stylesheet",href:PLATFORM_ERROR_FONTS}),jsx("style",{children:PLATFORM_ERROR_STYLES}),draw(platformErrorTree(kind??platformErrorKind(error),{...home===void 0?{}:{home},...store===void 0?{}:{store}}))]})}export{PlatformErrorPage,platformErrorKind2 as platformErrorKind};
|
|
2
2
|
//# sourceMappingURL=react.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/error-pages/react.tsx"],
|
|
4
|
-
"mappings": "AAAA,OACE,qBACA,sBACA,kBACA,
|
|
4
|
+
"mappings": "AAAA,OACE,qBACA,sBACA,kBACA,sBAIK,0BACP,OAAS,cAAe,aAAgC,QAExD,OACE,qBAAAA,uBAIK,0BA+BH,OACE,IADF,6BArBJ,IAAM,KAAQ,MAAgD,CAC5D,GAAI,OAAO,OAAS,SAAU,CAC5B,OAAO,IACT,CACA,KAAM,CAAC,IAAK,WAAY,GAAG,QAAQ,EAAI,KACvC,OAAO,cAAc,IAAK,WAAY,GAAG,SAAS,IAAI,IAAI,CAAC,CAC7D,EAQO,SAAS,kBAAkB,CAChC,KACA,MACA,KACA,KACF,EAA2B,CACzB,OACE,KAAC,UACC,cAAC,QAAK,IAAI,aAAa,KAAM,qBAAsB,EACnD,IAAC,SAAO,+BAAsB,EAC7B,KACC,kBAAkB,MAAQ,kBAAkB,KAAK,EAAG,CAClD,GAAI,OAAS,OAAY,CAAC,EAAI,CAAE,IAAK,EACrC,GAAI,QAAU,OAAY,CAAC,EAAI,CAAE,KAAM,CACzC,CAAC,CACH,GACF,CAEJ",
|
|
5
5
|
"names": ["platformErrorKind"]
|
|
6
6
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ZappieCartError}from"./cart/errors.js";import{holdsForLater,isHeldQuote}from"./cart/held.js";import{previewItem}from"./cart/preview.js";import{estimateUnitPrice}from"./cart/price.js";import{resolveSourceMenu}from"./cart/source-menu.js";import{validateLine}from"./cart/validate.js";import{createZappie}from"./client.js";import{API_VERSION}from"./config.js";import{ZappieError,isZappieError}from"./errors.js";export*from"./models.js";import{format,money}from"./money.js";import{RestTransport}from"./transport/rest.js";var VERSION=true?"0.
|
|
1
|
+
import{ZappieCartError}from"./cart/errors.js";import{holdsForLater,isHeldQuote}from"./cart/held.js";import{previewItem}from"./cart/preview.js";import{estimateUnitPrice}from"./cart/price.js";import{resolveSourceMenu}from"./cart/source-menu.js";import{validateLine}from"./cart/validate.js";import{createZappie}from"./client.js";import{API_VERSION}from"./config.js";import{ZappieError,isZappieError}from"./errors.js";export*from"./models.js";import{format,money}from"./money.js";import{RestTransport}from"./transport/rest.js";var VERSION=true?"0.23.0":"0.0.0-development";export{API_VERSION,RestTransport,VERSION,ZappieCartError,ZappieError,createZappie,estimateUnitPrice,format,holdsForLater,isHeldQuote,isZappieError,money,previewItem,resolveSourceMenu,validateLine};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createSecurityNonce}from"./security.js";var EDGE_CACHE_HEADER="x-zappie-edge-cache";var STORED_AT="x-zappie-stored-at";var FRESH_FOR="x-zappie-fresh-for";var STALE_FOR="x-zappie-stale-for";var ORIGIN_CACHE_CONTROL="x-zappie-origin-cache-control";var CACHE_NAME="zappie";var opened;function openEdgeCache(){opened??(opened=(async()=>{try{return typeof caches==="undefined"?void 0:await caches.open(CACHE_NAME)}catch{return void 0}})());return opened}async function sha256(value){const digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(value));return[...new Uint8Array(digest)].map(byte=>byte.toString(16).padStart(2,"0")).join("")}function sharedFreshness(cacheControl){if(!cacheControl||/\b(?:private|no-store|no-cache)\b/i.test(cacheControl)){return void 0}const seconds=name=>{const match=new RegExp(`(?:^|[,\\s])${name}=(\\d+)`,"i").exec(cacheControl);return match?Number(match[1]):void 0};const fresh=seconds("s-maxage")??seconds("max-age")??0;if(fresh<=0){return void 0}return{fresh,stale:seconds("stale-while-revalidate")??0}}function storable(response,life,now){const headers=new Headers(response.headers);headers.delete("set-cookie");headers.delete(EDGE_CACHE_HEADER);const origin=response.headers.get("cache-control");if(origin){headers.set(ORIGIN_CACHE_CONTROL,origin)}headers.set(STORED_AT,String(now));headers.set(FRESH_FOR,String(life.fresh));headers.set(STALE_FOR,String(life.stale));headers.set("cache-control",`public, max-age=${life.fresh+life.stale}`);return new Response(response.body,{status:response.status,headers})}function served(cached,status,age){const headers=new Headers(cached.headers);const origin=headers.get(ORIGIN_CACHE_CONTROL);if(origin){headers.set("cache-control",origin)}else{headers.delete("cache-control")}for(const name of[STORED_AT,FRESH_FOR,STALE_FOR,ORIGIN_CACHE_CONTROL]){headers.delete(name)}headers.set("age",String(Math.max(0,Math.floor(age))));headers.set(EDGE_CACHE_HEADER,status);return new Response(cached.body,{status:cached.status,headers})}function discard(response){response.body?.cancel().catch(()=>{})}function marked(response,status){const out=new Response(response.body,response);out.headers.set(EDGE_CACHE_HEADER,status);return out}async function lookup(cache,key,now){const cached=await cache.match(key);if(!cached){return void 0}const storedAt=Number(cached.headers.get(STORED_AT));const life={fresh:Number(cached.headers.get(FRESH_FOR)),stale:Number(cached.headers.get(STALE_FOR))};if(!Number.isFinite(storedAt)||!Number.isFinite(life.fresh)||!Number.isFinite(life.stale)){discard(cached);return void 0}return{response:cached,age:(now-storedAt)/1e3,life}}var refreshing=new Map;function refreshOnce(ctx,key,refresh){if(refreshing.has(key.url)){return}const running=refresh().catch(()=>{}).finally(()=>refreshing.delete(key.url));refreshing.set(key.url,running);ctx.waitUntil(running)}var SHARED_READS=/\/(?:store|menus)$/;function apiCacheBypass(request){if(request.method!=="GET"){return"method"}if(!SHARED_READS.test(new URL(request.url).pathname)){return"path"}if(!/^Bearer pk_(?:test|live)_/.test(request.headers.get("authorization")??"")){return"credentials"}if(request.headers.has("cookie")){return"cookie"}if(request.headers.has("if-none-match")){return"conditional"}return void 0}async function apiCacheKey(request){const key=(request.headers.get("authorization")??"").replace(/^Bearer\s+/,"");const url=new URL(request.url);const identity=await sha256(JSON.stringify([key,request.headers.get("zappie-version")??""]));return new Request(`https://zappie-api-cache.internal/${identity.slice(0,40)}/${url.host}${url.pathname}${url.search}`)}function cachedApiFetch(options={}){const upstream=options.fetch??((input,init)=>globalThis.fetch(input,init));const now=options.now??Date.now;const source=()=>options.cache??openEdgeCache();return async(input,init)=>{const request=new Request(input,init);if(apiCacheBypass(request)){return upstream(request)}let cache;let key;let hit;try{cache=await source();if(cache){key=await apiCacheKey(request);hit=await lookup(cache,key,now())}}catch{cache=void 0}if(!cache){return upstream(request)}const store=async response=>{const life=sharedFreshness(response.headers.get("cache-control"));if(response.status!==200||!life||response.headers.has("set-cookie")){return response}const copy=response.clone();const put=cache.put(key,storable(copy,life,now())).catch(()=>{});if(options.ctx){options.ctx.waitUntil(put)}else{await put}return response};if(hit&&hit.age<hit.life.fresh){return served(hit.response,"HIT",hit.age)}if(hit&&options.ctx&&hit.age<hit.life.fresh+hit.life.stale){const etag=hit.response.headers.get("etag");const kept=hit.response.clone();refreshOnce(options.ctx,key,async()=>{const headers=new Headers(request.headers);if(etag){headers.set("if-none-match",etag)}const response=await upstream(new Request(request.url,{method:"GET",headers,redirect:"manual"}));if(response.status===304){discard(response);const life2=sharedFreshness(response.headers.get("cache-control"))??hit.life;const restamped=served(kept,"HIT",0);restamped.headers.delete("age");restamped.headers.delete(EDGE_CACHE_HEADER);await cache.put(key,storable(restamped,life2,now()));return}const life=sharedFreshness(response.headers.get("cache-control"));if(response.status===200&&life&&!response.headers.has("set-cookie")){await cache.put(key,storable(response,life,now()))}else{discard(response)}});return served(hit.response,"STALE",hit.age)}if(hit){discard(hit.response)}return store(await upstream(request))}}var SESSION_COOKIE=/^(?:__Host-zappie_|__Host-zp_)|(?:^|[_-])(?:session|sess|sid|auth|token|jwt)(?:$|[_-])/i;function cookieNames(request){return(request.headers.get("cookie")??"").split(";").map(part=>part.slice(0,part.indexOf("=")>>>0).trim()).filter(Boolean)}function cookieValue(request,name){for(const part of(request.headers.get("cookie")??"").split(";")){const index=part.indexOf("=");if(index>0&&part.slice(0,index).trim()===name){return part.slice(index+1).trim()}}return""}function pageCacheBypass(request,options={}){if(request.method!=="GET"){return"method"}if(["x-zappie-draft","x-zappie-review","x-zappie-preview"].some(name=>request.headers.has(name))||new URL(request.url).searchParams.has("preview")){return"preview"}if(request.headers.has("x-zappie-site-state")){return"closed"}if(request.headers.has("authorization")){return"authorization"}if(request.headers.has("x-forwarded-host")||request.headers.has("forwarded")){return"forwarded"}const own=new Set(options.privateCookies??[]);if(cookieNames(request).some(name=>own.has(name)||SESSION_COOKIE.test(name))){return"session"}return void 0}async function pageCacheKey(request,options){const identity=await sha256(JSON.stringify([request.url,options.branchCookie?cookieValue(request,options.branchCookie):"",options.deployId,request.headers.get("x-zappie-site")??"",request.headers.get("x-zappie-key")??""]));return new Request(`https://zappie-page-cache.internal/${identity}`)}function pageStoreBypass(response,fallback){if(response.status!==200){return"status"}if(response.headers.has("set-cookie")){return"set-cookie"}if(response.headers.has("x-zappie-closed-page")){return"closed"}if(/(?:^|,)\s*\*\s*(?:,|$)/.test(response.headers.get("vary")??"")){return"vary"}if(!sharedFreshness(response.headers.get("cache-control")??fallback??null)){return"cache-control"}return void 0}var NONCE=/'nonce-([A-Za-z0-9_+/=-]+)'/;var POLICY_HEADERS=["content-security-policy","content-security-policy-report-only"];async function rotatePageNonce(response,nonce=createSecurityNonce()){const old=POLICY_HEADERS.map(name=>NONCE.exec(response.headers.get(name)??"")?.[1]).find(Boolean);if(!old||!/^text\/html/i.test(response.headers.get("content-type")??"")){return response}const headers=new Headers(response.headers);for(const name of POLICY_HEADERS){const value=headers.get(name);if(value){headers.set(name,value.replaceAll(`'nonce-${old}'`,`'nonce-${nonce}'`))}}headers.delete("content-length");const body=(await response.text()).replaceAll(`nonce="${old}"`,`nonce="${nonce}"`).replaceAll(`nonce=${old}`,`nonce=${nonce}`);return new Response(body,{status:response.status,headers})}async function cachePage(request,render,options){if(pageCacheBypass(request,options)){return marked(await render(request),"BYPASS")}const now=options.now??Date.now;let cache;let key;let hit;try{cache=await(options.cache??openEdgeCache());if(cache){key=await pageCacheKey(request,options);hit=await lookup(cache,key,now())}}catch{cache=void 0}if(!cache||!key){return marked(await render(request),"BYPASS")}const fallback=()=>options.cacheControl?.(new URL(request.url));const keep=async response=>{const control=response.headers.get("cache-control")??fallback();if(pageStoreBypass(response,control)){return void 0}const life=sharedFreshness(control??null);const shared=new Response(response.body,response);if(control&&!shared.headers.has("cache-control")){shared.headers.set("cache-control",control)}return{shared,life}};if(hit&&hit.age<hit.life.fresh){return rotatePageNonce(served(hit.response,"HIT",hit.age))}if(hit&&options.ctx&&hit.age<hit.life.fresh+hit.life.stale){refreshOnce(options.ctx,key,async()=>{const kept2=await keep(await render(new Request(request.url,{method:"GET",headers:request.headers})));if(kept2){await cache.put(key,storable(kept2.shared,kept2.life,now()))}else{await cache.delete(key)}});return rotatePageNonce(served(hit.response,"STALE",hit.age))}if(hit){discard(hit.response)}const rendered=await render(request);const kept=await keep(rendered);if(!kept){return marked(rendered,"MISS")}const put=cache.put(key,storable(kept.shared.clone(),kept.life,now())).catch(()=>{});if(options.ctx){options.ctx.waitUntil(put)}else{await put}return marked(kept.shared,"MISS")}export{EDGE_CACHE_HEADER,apiCacheBypass,apiCacheKey,cachePage,cachedApiFetch,openEdgeCache,pageCacheBypass,pageCacheKey,pageStoreBypass,rotatePageNonce,sharedFreshness};
|
|
1
|
+
import{createSecurityNonce}from"./security.js";var EDGE_CACHE_HEADER="x-zappie-edge-cache";var DATA_VERSION_HEADER="x-zappie-data-version";var dataVersions=new WeakMap;function rememberDataVersion(request,ctx){const version=request.headers.get(DATA_VERSION_HEADER);if(ctx&&version){dataVersions.set(ctx,version)}}var STORED_AT="x-zappie-stored-at";var FRESH_FOR="x-zappie-fresh-for";var STALE_FOR="x-zappie-stale-for";var ORIGIN_CACHE_CONTROL="x-zappie-origin-cache-control";var CACHE_NAME="zappie";var opened;function openEdgeCache(){opened??(opened=(async()=>{try{return typeof caches==="undefined"?void 0:await caches.open(CACHE_NAME)}catch{return void 0}})());return opened}async function sha256(value){const digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(value));return[...new Uint8Array(digest)].map(byte=>byte.toString(16).padStart(2,"0")).join("")}function sharedFreshness(cacheControl){if(!cacheControl||/\b(?:private|no-store|no-cache)\b/i.test(cacheControl)){return void 0}const seconds=name=>{const match=new RegExp(`(?:^|[,\\s])${name}=(\\d+)`,"i").exec(cacheControl);return match?Number(match[1]):void 0};const fresh=seconds("s-maxage")??seconds("max-age")??0;if(fresh<=0){return void 0}return{fresh,stale:seconds("stale-while-revalidate")??0}}function storable(response,life,now){const headers=new Headers(response.headers);headers.delete("set-cookie");headers.delete(EDGE_CACHE_HEADER);const origin=response.headers.get("cache-control");if(origin){headers.set(ORIGIN_CACHE_CONTROL,origin)}headers.set(STORED_AT,String(now));headers.set(FRESH_FOR,String(life.fresh));headers.set(STALE_FOR,String(life.stale));headers.set("cache-control",`public, max-age=${life.fresh+life.stale}`);return new Response(response.body,{status:response.status,headers})}function served(cached,status,age){const headers=new Headers(cached.headers);const origin=headers.get(ORIGIN_CACHE_CONTROL);if(origin){headers.set("cache-control",origin)}else{headers.delete("cache-control")}for(const name of[STORED_AT,FRESH_FOR,STALE_FOR,ORIGIN_CACHE_CONTROL]){headers.delete(name)}headers.set("age",String(Math.max(0,Math.floor(age))));headers.set(EDGE_CACHE_HEADER,status);return new Response(cached.body,{status:cached.status,headers})}function discard(response){response.body?.cancel().catch(()=>{})}function marked(response,status){const out=new Response(response.body,response);out.headers.set(EDGE_CACHE_HEADER,status);return out}async function lookup(cache,key,now){const cached=await cache.match(key);if(!cached){return void 0}const storedAt=Number(cached.headers.get(STORED_AT));const life={fresh:Number(cached.headers.get(FRESH_FOR)),stale:Number(cached.headers.get(STALE_FOR))};if(!Number.isFinite(storedAt)||!Number.isFinite(life.fresh)||!Number.isFinite(life.stale)){discard(cached);return void 0}return{response:cached,age:(now-storedAt)/1e3,life}}var refreshing=new Map;function refreshOnce(ctx,key,refresh){if(refreshing.has(key.url)){return}const running=refresh().catch(()=>{}).finally(()=>refreshing.delete(key.url));refreshing.set(key.url,running);ctx.waitUntil(running)}var SHARED_READS=/\/(?:store|menus)$/;function apiCacheBypass(request){if(request.method!=="GET"){return"method"}if(!SHARED_READS.test(new URL(request.url).pathname)){return"path"}if(!/^Bearer pk_(?:test|live)_/.test(request.headers.get("authorization")??"")){return"credentials"}if(request.headers.has("cookie")){return"cookie"}if(request.headers.has("if-none-match")){return"conditional"}return void 0}async function apiCacheKey(request,dataVersion=""){const key=(request.headers.get("authorization")??"").replace(/^Bearer\s+/,"");const url=new URL(request.url);const parts=[key,request.headers.get("zappie-version")??""];const identity=await sha256(JSON.stringify(dataVersion?[...parts,dataVersion]:parts));return new Request(`https://zappie-api-cache.internal/${identity.slice(0,40)}/${url.host}${url.pathname}${url.search}`)}function cachedApiFetch(options={}){const upstream=options.fetch??((input,init)=>globalThis.fetch(input,init));const now=options.now??Date.now;const source=()=>options.cache??openEdgeCache();return async(input,init)=>{const request=new Request(input,init);if(apiCacheBypass(request)){return upstream(request)}let cache;let key;let hit;try{cache=await source();if(cache){key=await apiCacheKey(request,options.dataVersion??(options.ctx?dataVersions.get(options.ctx):void 0));hit=await lookup(cache,key,now())}}catch{cache=void 0}if(!cache){return upstream(request)}const store=async response=>{const life=sharedFreshness(response.headers.get("cache-control"));if(response.status!==200||!life||response.headers.has("set-cookie")){return response}const copy=response.clone();const put=cache.put(key,storable(copy,life,now())).catch(()=>{});if(options.ctx){options.ctx.waitUntil(put)}else{await put}return response};if(hit&&hit.age<hit.life.fresh){return served(hit.response,"HIT",hit.age)}if(hit&&options.ctx&&hit.age<hit.life.fresh+hit.life.stale){const etag=hit.response.headers.get("etag");const kept=hit.response.clone();refreshOnce(options.ctx,key,async()=>{const headers=new Headers(request.headers);if(etag){headers.set("if-none-match",etag)}const response=await upstream(new Request(request.url,{method:"GET",headers,redirect:"manual"}));if(response.status===304){discard(response);const life2=sharedFreshness(response.headers.get("cache-control"))??hit.life;const restamped=served(kept,"HIT",0);restamped.headers.delete("age");restamped.headers.delete(EDGE_CACHE_HEADER);await cache.put(key,storable(restamped,life2,now()));return}const life=sharedFreshness(response.headers.get("cache-control"));if(response.status===200&&life&&!response.headers.has("set-cookie")){await cache.put(key,storable(response,life,now()))}else{discard(response)}});return served(hit.response,"STALE",hit.age)}if(hit){discard(hit.response)}return store(await upstream(request))}}var SESSION_COOKIE=/^(?:__Host-zappie_|__Host-zp_)|(?:^|[_-])(?:session|sess|sid|auth|token|jwt)(?:$|[_-])/i;function cookieNames(request){return(request.headers.get("cookie")??"").split(";").map(part=>part.slice(0,part.indexOf("=")>>>0).trim()).filter(Boolean)}function cookieValue(request,name){for(const part of(request.headers.get("cookie")??"").split(";")){const index=part.indexOf("=");if(index>0&&part.slice(0,index).trim()===name){return part.slice(index+1).trim()}}return""}function pageCacheBypass(request,options={}){if(request.method!=="GET"){return"method"}if(["x-zappie-draft","x-zappie-review","x-zappie-preview"].some(name=>request.headers.has(name))||new URL(request.url).searchParams.has("preview")){return"preview"}if(request.headers.has("x-zappie-site-state")){return"closed"}if(request.headers.has("authorization")){return"authorization"}if(request.headers.has("x-forwarded-host")||request.headers.has("forwarded")){return"forwarded"}const own=new Set(options.privateCookies??[]);if(cookieNames(request).some(name=>own.has(name)||SESSION_COOKIE.test(name))){return"session"}return void 0}async function pageCacheKey(request,options){const parts=[request.url,options.branchCookie?cookieValue(request,options.branchCookie):"",options.deployId,request.headers.get("x-zappie-site")??"",request.headers.get("x-zappie-key")??""];const version=request.headers.get(DATA_VERSION_HEADER);const identity=await sha256(JSON.stringify(version?[...parts,version]:parts));return new Request(`https://zappie-page-cache.internal/${identity}`)}function pageStoreBypass(response,fallback){if(response.status!==200){return"status"}if(response.headers.has("set-cookie")){return"set-cookie"}if(response.headers.has("x-zappie-closed-page")){return"closed"}if(/(?:^|,)\s*\*\s*(?:,|$)/.test(response.headers.get("vary")??"")){return"vary"}if(!sharedFreshness(response.headers.get("cache-control")??fallback??null)){return"cache-control"}return void 0}var NONCE=/'nonce-([A-Za-z0-9_+/=-]+)'/;var POLICY_HEADERS=["content-security-policy","content-security-policy-report-only"];async function rotatePageNonce(response,nonce=createSecurityNonce()){const old=POLICY_HEADERS.map(name=>NONCE.exec(response.headers.get(name)??"")?.[1]).find(Boolean);if(!old||!/^text\/html/i.test(response.headers.get("content-type")??"")){return response}const headers=new Headers(response.headers);for(const name of POLICY_HEADERS){const value=headers.get(name);if(value){headers.set(name,value.replaceAll(`'nonce-${old}'`,`'nonce-${nonce}'`))}}headers.delete("content-length");const body=(await response.text()).replaceAll(`nonce="${old}"`,`nonce="${nonce}"`).replaceAll(`nonce=${old}`,`nonce=${nonce}`);return new Response(body,{status:response.status,headers})}async function cachePage(request,render,options){rememberDataVersion(request,options.ctx);if(pageCacheBypass(request,options)){return marked(await render(request),"BYPASS")}const now=options.now??Date.now;let cache;let key;let hit;try{cache=await(options.cache??openEdgeCache());if(cache){key=await pageCacheKey(request,options);hit=await lookup(cache,key,now())}}catch{cache=void 0}if(!cache||!key){return marked(await render(request),"BYPASS")}const fallback=()=>options.cacheControl?.(new URL(request.url));const keep=async response=>{const control=response.headers.get("cache-control")??fallback();if(pageStoreBypass(response,control)){return void 0}const life=sharedFreshness(control??null);const shared=new Response(response.body,response);if(control&&!shared.headers.has("cache-control")){shared.headers.set("cache-control",control)}return{shared,life}};if(hit&&hit.age<hit.life.fresh){return rotatePageNonce(served(hit.response,"HIT",hit.age))}if(hit&&options.ctx&&hit.age<hit.life.fresh+hit.life.stale){refreshOnce(options.ctx,key,async()=>{const kept2=await keep(await render(new Request(request.url,{method:"GET",headers:request.headers})));if(kept2){await cache.put(key,storable(kept2.shared,kept2.life,now()))}else{await cache.delete(key)}});return rotatePageNonce(served(hit.response,"STALE",hit.age))}if(hit){discard(hit.response)}const rendered=await render(request);const kept=await keep(rendered);if(!kept){return marked(rendered,"MISS")}const put=cache.put(key,storable(kept.shared.clone(),kept.life,now())).catch(()=>{});if(options.ctx){options.ctx.waitUntil(put)}else{await put}return marked(kept.shared,"MISS")}export{DATA_VERSION_HEADER,EDGE_CACHE_HEADER,apiCacheBypass,apiCacheKey,cachePage,cachedApiFetch,openEdgeCache,pageCacheBypass,pageCacheKey,pageStoreBypass,rememberDataVersion,rotatePageNonce,sharedFreshness};
|
|
2
2
|
//# sourceMappingURL=edge-cache.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/server/edge-cache.ts"],
|
|
4
|
-
"mappings": "AAAA,OAAS,wBAA2B,gBAS7B,IAAM,kBAAoB,
|
|
4
|
+
"mappings": "AAAA,OAAS,wBAA2B,gBAS7B,IAAM,kBAAoB,sBAO1B,IAAM,oBAAsB,wBAGnC,IAAM,aAAe,IAAI,QASlB,SAAS,oBAAoB,QAAkB,IAAmB,CACvE,MAAM,QAAU,QAAQ,QAAQ,IAAI,mBAAmB,EACvD,GAAI,KAAO,QAAS,CAClB,aAAa,IAAI,IAAK,OAAO,CAC/B,CACF,CAEA,IAAM,UAAY,qBAClB,IAAM,UAAY,qBAClB,IAAM,UAAY,qBAClB,IAAM,qBAAuB,gCAC7B,IAAM,WAAa,SASnB,IAAI,OAOG,SAAS,eAAgD,CAC9D,iBAAY,SAAY,CACtB,GAAI,CACF,OAAO,OAAO,SAAW,YACrB,OACA,MAAM,OAAO,KAAK,UAAU,CAClC,MAAQ,CACN,OAAO,MACT,CACF,GAAG,GACH,OAAO,MACT,CAGA,eAAe,OAAO,MAAgC,CACpD,MAAM,OAAS,MAAM,OAAO,OAAO,OACjC,UACA,IAAI,YAAY,EAAE,OAAO,KAAK,CAChC,EACA,MAAO,CAAC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L,MAAM,MAAO,OAAO,GAAI,CAC1B,CACF,CAAC,EACD,OAAO,gBAAgB,OAAO,IAAI,SAAU,QAAS,IAAI,GAAG,CAAC,CAC/D,CACA,GAAI,IAAK,CACP,QAAQ,IAAI,QAAQ,CACtB,CACA,MAAM,SAAW,MAAM,OAAO,OAAO,EACrC,MAAM,KAAO,MAAM,KAAK,QAAQ,EAChC,GAAI,CAAC,KAAM,CACT,OAAO,OAAO,SAAU,MAAM,CAChC,CACA,MAAM,IAAM,MACT,IAAI,IAAK,SAAS,KAAK,OAAO,MAAM,EAAG,KAAK,KAAM,IAAI,CAAC,CAAC,EACxD,MAAM,IAAM,CAAC,CAAC,EACjB,GAAI,QAAQ,IAAK,CACf,QAAQ,IAAI,UAAU,GAAG,CAC3B,KAAO,CACL,MAAM,GACR,CACA,OAAO,OAAO,KAAK,OAAQ,MAAM,CACnC",
|
|
5
5
|
"names": ["life", "kept"]
|
|
6
6
|
}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -444,6 +444,20 @@ type EdgeContext = {
|
|
|
444
444
|
type EdgeCacheStatus = "HIT" | "STALE" | "MISS" | "BYPASS";
|
|
445
445
|
/** The response header that says how the edge cache answered. */
|
|
446
446
|
declare const EDGE_CACHE_HEADER = "x-zappie-edge-cache";
|
|
447
|
+
/**
|
|
448
|
+
* The request header the site host sends with the store's data version, which moves on each change the merchant
|
|
449
|
+
* makes to what the live site shows. Pages and store reads are kept under it, so a change is never answered from an
|
|
450
|
+
* entry drawn before it, at any Cloudflare location.
|
|
451
|
+
*/
|
|
452
|
+
declare const DATA_VERSION_HEADER = "x-zappie-data-version";
|
|
453
|
+
/**
|
|
454
|
+
* Remember the data version the host sent with a request, so the store reads made while it renders are kept under
|
|
455
|
+
* it too. {@link cachePage} and `siteWorker` call it; a Worker that renders some other way calls it first.
|
|
456
|
+
*
|
|
457
|
+
* @param request - The request the Worker received.
|
|
458
|
+
* @param ctx - The Worker's execution context for that request.
|
|
459
|
+
*/
|
|
460
|
+
declare function rememberDataVersion(request: Request, ctx?: EdgeContext): void;
|
|
447
461
|
/** The part of the Cache API the edge cache uses: a Worker's `caches.open()` cache, or a stand-in in tests. */
|
|
448
462
|
type EdgeCache = {
|
|
449
463
|
match(request: Request): Promise<Response | undefined>;
|
|
@@ -478,6 +492,8 @@ type CachedApiFetchOptions = {
|
|
|
478
492
|
fetch?: typeof fetch;
|
|
479
493
|
/** The clock, in milliseconds. */
|
|
480
494
|
now?: () => number;
|
|
495
|
+
/** The store's data version. Defaults to the one {@link rememberDataVersion} kept for `ctx`. */
|
|
496
|
+
dataVersion?: string;
|
|
481
497
|
};
|
|
482
498
|
/**
|
|
483
499
|
* Why an API request can't come from the shared cache, or `undefined` when it can. Only a `GET` of the store or a
|
|
@@ -488,12 +504,13 @@ type CachedApiFetchOptions = {
|
|
|
488
504
|
*/
|
|
489
505
|
declare function apiCacheBypass(request: Request): string | undefined;
|
|
490
506
|
/**
|
|
491
|
-
* The cache key for a shared API read: the URL, the API version and a hash of the
|
|
492
|
-
* never share an entry and the key itself is never stored.
|
|
507
|
+
* The cache key for a shared API read: the URL, the API version, the store's data version and a hash of the
|
|
508
|
+
* publishable key, so two stores never share an entry and the key itself is never stored.
|
|
493
509
|
*
|
|
494
510
|
* @param request - A request {@link apiCacheBypass} accepts.
|
|
511
|
+
* @param dataVersion - The store's data version, from the site host. Empty keeps the key it had without one.
|
|
495
512
|
*/
|
|
496
|
-
declare function apiCacheKey(request: Request): Promise<Request>;
|
|
513
|
+
declare function apiCacheKey(request: Request, dataVersion?: string): Promise<Request>;
|
|
497
514
|
/**
|
|
498
515
|
* A fetch for `createZappie` on the server that keeps the storefront API's store and menu reads in the Worker's
|
|
499
516
|
* cache, for as long as the API's own `Cache-Control` allows (`s-maxage`, then `stale-while-revalidate`). A stale
|
|
@@ -540,9 +557,10 @@ type PageCacheOptions = {
|
|
|
540
557
|
*/
|
|
541
558
|
declare function pageCacheBypass(request: Request, options?: Pick<PageCacheOptions, "privateCookies">): string | undefined;
|
|
542
559
|
/**
|
|
543
|
-
* The cache key for a shared page: the full URL, query included, the branch cookie's value, the deploy,
|
|
560
|
+
* The cache key for a shared page: the full URL, query included, the branch cookie's value, the deploy, which
|
|
544
561
|
* site the host says this is (its id and a hash of its publishable key), so a Worker that serves several sites keeps
|
|
545
|
-
* each one's pages apart
|
|
562
|
+
* each one's pages apart, and the store's data version the host sends, so a page drawn before a change is never
|
|
563
|
+
* read again.
|
|
546
564
|
*
|
|
547
565
|
* @param request - A request {@link pageCacheBypass} accepts.
|
|
548
566
|
* @param options - The deploy id and the branch cookie.
|
|
@@ -1099,6 +1117,16 @@ declare function sitemapResponse({ preview, ...options }: SitemapOptions & {
|
|
|
1099
1117
|
preview: boolean;
|
|
1100
1118
|
}): Response;
|
|
1101
1119
|
|
|
1120
|
+
/** The store a page belongs to. */
|
|
1121
|
+
type PlatformErrorStore = {
|
|
1122
|
+
/** The store's name, shown over the heading and as the page's title. */
|
|
1123
|
+
name: string;
|
|
1124
|
+
/** Where the store's name leads. Default the page's `home`. */
|
|
1125
|
+
href?: string;
|
|
1126
|
+
/** The store's logo as an image URL, shown in place of its name. */
|
|
1127
|
+
logo?: string;
|
|
1128
|
+
};
|
|
1129
|
+
|
|
1102
1130
|
/** The Worker's own variables that {@link siteWorker} reads. */
|
|
1103
1131
|
type SiteWorkerEnv = {
|
|
1104
1132
|
/** `off` renders every page afresh, as an end-to-end test's own Worker does. */
|
|
@@ -1119,6 +1147,8 @@ type SiteWorkerOptions<Env extends SiteWorkerEnv> = {
|
|
|
1119
1147
|
branchCookie?: string;
|
|
1120
1148
|
/** Answers a request before anything renders, such as `legacyRedirects(…).classicHome`. */
|
|
1121
1149
|
redirect?: (request: Request) => Response | undefined;
|
|
1150
|
+
/** The store whose name leads the "Something went wrong" page, such as `{ name: "Kingfisher Africa" }`. */
|
|
1151
|
+
store?: PlatformErrorStore | ((env: Env) => PlatformErrorStore | undefined);
|
|
1122
1152
|
};
|
|
1123
1153
|
/**
|
|
1124
1154
|
* A site's Worker. It answers, in order:
|
|
@@ -1129,9 +1159,10 @@ type SiteWorkerOptions<Env extends SiteWorkerEnv> = {
|
|
|
1129
1159
|
* - a page through the edge page cache (`cachePage`), so shoppers who aren't signed in share the menu pages, their
|
|
1130
1160
|
* `.data`, robots and the sitemap at each location for as long as each one's `Cache-Control` says. It renders
|
|
1131
1161
|
* afresh with `ZAPPIE_EDGE_CACHE=off`, and for a request with `x-forwarded-host`: a page drawn behind a proxy names
|
|
1132
|
-
* the proxy's host in its links, so it is never shared. A new build starts with an empty cache
|
|
1162
|
+
* the proxy's host in its links, so it is never shared. A new build starts with an empty cache, and a page or
|
|
1163
|
+
* store read drawn before the store's data version the host sends moved on is never read again.
|
|
1133
1164
|
*
|
|
1134
|
-
* A handler that throws answers with Zappie's
|
|
1165
|
+
* A handler that throws answers with Zappie's "Something went wrong" page, led by `store` when you name it.
|
|
1135
1166
|
*
|
|
1136
1167
|
* @example
|
|
1137
1168
|
* ```ts
|
|
@@ -1146,7 +1177,7 @@ type SiteWorkerOptions<Env extends SiteWorkerEnv> = {
|
|
|
1146
1177
|
* });
|
|
1147
1178
|
* ```
|
|
1148
1179
|
*/
|
|
1149
|
-
declare function siteWorker<Env extends SiteWorkerEnv>({ render, deployId, cacheControl, branchCookie, redirect, }: SiteWorkerOptions<Env>): {
|
|
1180
|
+
declare function siteWorker<Env extends SiteWorkerEnv>({ render, deployId, cacheControl, branchCookie, redirect, store, }: SiteWorkerOptions<Env>): {
|
|
1150
1181
|
fetch(request: Request, env: Env, ctx: EdgeContext): Promise<Response>;
|
|
1151
1182
|
};
|
|
1152
1183
|
/**
|
|
@@ -1237,5 +1268,5 @@ declare function createZappieServer({ secretKey, ...config }: ZappieServerConfig
|
|
|
1237
1268
|
};
|
|
1238
1269
|
}>;
|
|
1239
1270
|
|
|
1240
|
-
export { CLASSIC_QUERY_KEYS, EDGE_CACHE_HEADER, PAGE_CACHE_CONTROL, PREVIEW_HEADERS, PRIVATE_PAGES, ROBOTS_DISALLOW, STOREFRONT_QUERY_PARAMETERS, STOREFRONT_V1_QUERY_PARAMETERS, ZappieTokenError, ZappieWebhookSignatureError, allMenus, apiCacheBypass, apiCacheKey, applyAvailability, buildStorefrontUrl, cachePage, cachedApiFetch, canonicalJson, cookieSessionStore, createAvailabilityPatch, createMenuSnapshot, createPkce, createSecurityNonce, createStoreSnapshot, createTokenVerifier, createZappieServer, deferredDataFailed, inlineScriptHashes, isMenuSnapshot, legacyRedirects, loadStoreAndMenu, menuSnapshotFromPayload, openEdgeCache, openSealedValue, originFetch, pageCacheBypass, pageCacheKey, pageCacheRules, pageStoreBypass, parseStorefrontUrl, randomToken, requestedBranch, resolveBranch, robotsResponse, robotsText, rotatePageNonce, sealValue, securityHeaders, sharedCacheControl, sharedFreshness, signInRedirect, siteWorker, sitemapResponse, sitemapUrls, sitemapXml, snapshotHash, snapshotKeys, storeRedirect, storefrontRedirect, verifyWebhook };
|
|
1271
|
+
export { CLASSIC_QUERY_KEYS, DATA_VERSION_HEADER, EDGE_CACHE_HEADER, PAGE_CACHE_CONTROL, PREVIEW_HEADERS, PRIVATE_PAGES, ROBOTS_DISALLOW, STOREFRONT_QUERY_PARAMETERS, STOREFRONT_V1_QUERY_PARAMETERS, ZappieTokenError, ZappieWebhookSignatureError, allMenus, apiCacheBypass, apiCacheKey, applyAvailability, buildStorefrontUrl, cachePage, cachedApiFetch, canonicalJson, cookieSessionStore, createAvailabilityPatch, createMenuSnapshot, createPkce, createSecurityNonce, createStoreSnapshot, createTokenVerifier, createZappieServer, deferredDataFailed, inlineScriptHashes, isMenuSnapshot, legacyRedirects, loadStoreAndMenu, menuSnapshotFromPayload, openEdgeCache, openSealedValue, originFetch, pageCacheBypass, pageCacheKey, pageCacheRules, pageStoreBypass, parseStorefrontUrl, randomToken, rememberDataVersion, requestedBranch, resolveBranch, robotsResponse, robotsText, rotatePageNonce, sealValue, securityHeaders, sharedCacheControl, sharedFreshness, signInRedirect, siteWorker, sitemapResponse, sitemapUrls, sitemapXml, snapshotHash, snapshotKeys, storeRedirect, storefrontRedirect, verifyWebhook };
|
|
1241
1272
|
export type { AllMenusOptions, AvailabilityPatch, AvailabilityPatchInput, CachedApiFetchOptions, CookieSessionStoreOptions, DocumentCacheInput, EdgeCache, EdgeCacheStatus, EdgeContext, EdgeSnapshotReader, Freshness, IdTokenChecks, IdTokenClaims, LegacyRedirects, LegacyRedirectsOptions, MenuSnapshot, MenuSnapshotInput, MenuSnapshotPayloadInput, PageCache, PageCacheOptions, PageCacheRules, PageCacheRulesOptions, PkcePair, ResolveBranchOptions, ResolvedBranch, RobotsResponseOptions, RobotsTextOptions, SealOptions, SealSecret, SecurityHeadersOptions, SessionData, SessionStore, SiteWorkerEnv, SiteWorkerOptions, SitemapOptions, 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
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{buildClient}from"../client.js";import{VERSION}from"../index.js";import{buildStorefrontUrl,parseStorefrontUrl,STOREFRONT_QUERY_PARAMETERS,STOREFRONT_V1_QUERY_PARAMETERS,storefrontRedirect}from"../url/index.js";import{createPkce,openSealedValue,randomToken,sealValue}from"./auth/crypto.js";import{createTokenVerifier,ZappieTokenError}from"./auth/jwt.js";import{cookieSessionStore}from"./auth/session-store.js";import{loadStoreAndMenu,requestedBranch,resolveBranch}from"./chosen-branch.js";import{apiCacheBypass,apiCacheKey,cachedApiFetch,cachePage,EDGE_CACHE_HEADER,openEdgeCache,pageCacheBypass,pageCacheKey,pageStoreBypass,rotatePageNonce,sharedFreshness}from"./edge-cache.js";import{applyAvailability,canonicalJson,createAvailabilityPatch,createMenuSnapshot,createStoreSnapshot,isMenuSnapshot,menuSnapshotFromPayload,snapshotHash,snapshotKeys}from"./edge-snapshot.js";import{CLASSIC_QUERY_KEYS,legacyRedirects}from"./legacy-order.js";import{deferredDataFailed,PAGE_CACHE_CONTROL,pageCacheRules,PREVIEW_HEADERS,PRIVATE_PAGES,sharedCacheControl}from"./page-cache.js";import{createSecurityNonce,inlineScriptHashes,securityHeaders}from"./security.js";import{signInRedirect}from"./sign-in.js";import{allMenus,ROBOTS_DISALLOW,robotsResponse,robotsText,sitemapResponse,sitemapUrls,sitemapXml,storeRedirect}from"./site-seo.js";import{originFetch,siteWorker}from"./site-worker.js";import{verifyWebhook,ZappieWebhookSignatureError}from"./webhook.js";function createZappieServer({secretKey,...config}){return buildClient({...config,key:secretKey},true)}export{CLASSIC_QUERY_KEYS,EDGE_CACHE_HEADER,PAGE_CACHE_CONTROL,PREVIEW_HEADERS,PRIVATE_PAGES,ROBOTS_DISALLOW,STOREFRONT_QUERY_PARAMETERS,STOREFRONT_V1_QUERY_PARAMETERS,VERSION,ZappieTokenError,ZappieWebhookSignatureError,allMenus,apiCacheBypass,apiCacheKey,applyAvailability,buildStorefrontUrl,cachePage,cachedApiFetch,canonicalJson,cookieSessionStore,createAvailabilityPatch,createMenuSnapshot,createPkce,createSecurityNonce,createStoreSnapshot,createTokenVerifier,createZappieServer,deferredDataFailed,inlineScriptHashes,isMenuSnapshot,legacyRedirects,loadStoreAndMenu,menuSnapshotFromPayload,openEdgeCache,openSealedValue,originFetch,pageCacheBypass,pageCacheKey,pageCacheRules,pageStoreBypass,parseStorefrontUrl,randomToken,requestedBranch,resolveBranch,robotsResponse,robotsText,rotatePageNonce,sealValue,securityHeaders,sharedCacheControl,sharedFreshness,signInRedirect,siteWorker,sitemapResponse,sitemapUrls,sitemapXml,snapshotHash,snapshotKeys,storeRedirect,storefrontRedirect,verifyWebhook};
|
|
1
|
+
import{buildClient}from"../client.js";import{VERSION}from"../index.js";import{buildStorefrontUrl,parseStorefrontUrl,STOREFRONT_QUERY_PARAMETERS,STOREFRONT_V1_QUERY_PARAMETERS,storefrontRedirect}from"../url/index.js";import{createPkce,openSealedValue,randomToken,sealValue}from"./auth/crypto.js";import{createTokenVerifier,ZappieTokenError}from"./auth/jwt.js";import{cookieSessionStore}from"./auth/session-store.js";import{loadStoreAndMenu,requestedBranch,resolveBranch}from"./chosen-branch.js";import{apiCacheBypass,apiCacheKey,cachedApiFetch,cachePage,DATA_VERSION_HEADER,EDGE_CACHE_HEADER,openEdgeCache,pageCacheBypass,pageCacheKey,pageStoreBypass,rememberDataVersion,rotatePageNonce,sharedFreshness}from"./edge-cache.js";import{applyAvailability,canonicalJson,createAvailabilityPatch,createMenuSnapshot,createStoreSnapshot,isMenuSnapshot,menuSnapshotFromPayload,snapshotHash,snapshotKeys}from"./edge-snapshot.js";import{CLASSIC_QUERY_KEYS,legacyRedirects}from"./legacy-order.js";import{deferredDataFailed,PAGE_CACHE_CONTROL,pageCacheRules,PREVIEW_HEADERS,PRIVATE_PAGES,sharedCacheControl}from"./page-cache.js";import{createSecurityNonce,inlineScriptHashes,securityHeaders}from"./security.js";import{signInRedirect}from"./sign-in.js";import{allMenus,ROBOTS_DISALLOW,robotsResponse,robotsText,sitemapResponse,sitemapUrls,sitemapXml,storeRedirect}from"./site-seo.js";import{originFetch,siteWorker}from"./site-worker.js";import{verifyWebhook,ZappieWebhookSignatureError}from"./webhook.js";function createZappieServer({secretKey,...config}){return buildClient({...config,key:secretKey},true)}export{CLASSIC_QUERY_KEYS,DATA_VERSION_HEADER,EDGE_CACHE_HEADER,PAGE_CACHE_CONTROL,PREVIEW_HEADERS,PRIVATE_PAGES,ROBOTS_DISALLOW,STOREFRONT_QUERY_PARAMETERS,STOREFRONT_V1_QUERY_PARAMETERS,VERSION,ZappieTokenError,ZappieWebhookSignatureError,allMenus,apiCacheBypass,apiCacheKey,applyAvailability,buildStorefrontUrl,cachePage,cachedApiFetch,canonicalJson,cookieSessionStore,createAvailabilityPatch,createMenuSnapshot,createPkce,createSecurityNonce,createStoreSnapshot,createTokenVerifier,createZappieServer,deferredDataFailed,inlineScriptHashes,isMenuSnapshot,legacyRedirects,loadStoreAndMenu,menuSnapshotFromPayload,openEdgeCache,openSealedValue,originFetch,pageCacheBypass,pageCacheKey,pageCacheRules,pageStoreBypass,parseStorefrontUrl,randomToken,rememberDataVersion,requestedBranch,resolveBranch,robotsResponse,robotsText,rotatePageNonce,sealValue,securityHeaders,sharedCacheControl,sharedFreshness,signInRedirect,siteWorker,sitemapResponse,sitemapUrls,sitemapXml,snapshotHash,snapshotKeys,storeRedirect,storefrontRedirect,verifyWebhook};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
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,OAAS,gBAAmB,eAG5B,OAAS,YAAe,cACxB,OACE,mBACA,mBACA,4BACA,+BACA,uBAOK,kBACP,OACE,WACA,gBACA,YACA,cAIK,mBACP,OACE,oBACA,qBASK,gBACP,OACE,uBAIK,0BACP,OACE,iBACA,gBACA,kBAIK,qBACP,OACE,eACA,YACA,eACA,UACA,kBACA,cACA,gBACA,aACA,gBACA,gBACA,oBAOK,kBACP,OACE,kBACA,cACA,wBACA,mBACA,oBACA,eACA,wBACA,aACA,iBAQK,qBACP,OACE,mBACA,oBAGK,oBACP,OACE,mBACA,mBACA,eACA,gBACA,cACA,uBAKK,kBACP,OACE,oBACA,mBACA,oBAEK,gBACP,OAAS,mBAAsB,eAC/B,OACE,SACA,gBACA,eACA,WACA,gBACA,YACA,WACA,kBAKK,gBACP,OACE,YACA,eAGK,mBACP,OACE,cACA,gCAIK,eAUA,SAAS,mBAAmB,CACjC,UACA,GAAG,MACL,EAAuB,CACrB,OAAO,YAAY,CAAE,GAAG,OAAQ,IAAK,SAAU,EAAG,IAAI,CACxD",
|
|
4
|
+
"mappings": "AAAA,OAAS,gBAAmB,eAG5B,OAAS,YAAe,cACxB,OACE,mBACA,mBACA,4BACA,+BACA,uBAOK,kBACP,OACE,WACA,gBACA,YACA,cAIK,mBACP,OACE,oBACA,qBASK,gBACP,OACE,uBAIK,0BACP,OACE,iBACA,gBACA,kBAIK,qBACP,OACE,eACA,YACA,eACA,UACA,oBACA,kBACA,cACA,gBACA,aACA,gBACA,oBACA,gBACA,oBAOK,kBACP,OACE,kBACA,cACA,wBACA,mBACA,oBACA,eACA,wBACA,aACA,iBAQK,qBACP,OACE,mBACA,oBAGK,oBACP,OACE,mBACA,mBACA,eACA,gBACA,cACA,uBAKK,kBACP,OACE,oBACA,mBACA,oBAEK,gBACP,OAAS,mBAAsB,eAC/B,OACE,SACA,gBACA,eACA,WACA,gBACA,YACA,WACA,kBAKK,gBACP,OACE,YACA,eAGK,mBACP,OACE,cACA,gCAIK,eAUA,SAAS,mBAAmB,CACjC,UACA,GAAG,MACL,EAAuB,CACrB,OAAO,YAAY,CAAE,GAAG,OAAQ,IAAK,SAAU,EAAG,IAAI,CACxD",
|
|
5
5
|
"names": []
|
|
6
6
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{platformErrorResponse}from"../error-pages/index.js";import{markClosedPage,siteClosed}from"../site-closed/index.js";import{cachePage}from"./edge-cache.js";function siteWorker({render,deployId,cacheControl,branchCookie,redirect}){return{async fetch(request,env,ctx){try{if(siteClosed(request)){const response=await render(new Request(new URL("/",request.url),request),env,ctx);return response.ok?markClosedPage(response):response}const early=redirect?.(request);if(early){return early}const fresh=next=>render(next,env,ctx);if(env.ZAPPIE_EDGE_CACHE==="off"||request.headers.has("x-forwarded-host")){return await fresh(request)}return await cachePage(request,fresh,{ctx,deployId:await deployId(),...cacheControl?{cacheControl}:{},...branchCookie?{branchCookie}:{}})}catch(error){console.error(error);return platformErrorResponse("went-wrong")}}}}function originFetch(origin,fetcher=(input,init)=>globalThis.fetch(input,init)){return(input,init)=>{const headers=new Headers(init?.headers??(input instanceof Request?input.headers:void 0));if(!headers.has("origin")){headers.set("origin",origin)}return fetcher(input,{...init,headers})}}export{originFetch,siteWorker};
|
|
1
|
+
import{platformErrorResponse}from"../error-pages/index.js";import{markClosedPage,siteClosed}from"../site-closed/index.js";import{cachePage,rememberDataVersion}from"./edge-cache.js";function siteWorker({render,deployId,cacheControl,branchCookie,redirect,store}){return{async fetch(request,env,ctx){try{if(siteClosed(request)){const response=await render(new Request(new URL("/",request.url),request),env,ctx);return response.ok?markClosedPage(response):response}const early=redirect?.(request);if(early){return early}const fresh=next=>render(next,env,ctx);rememberDataVersion(request,ctx);if(env.ZAPPIE_EDGE_CACHE==="off"||request.headers.has("x-forwarded-host")){return await fresh(request)}return await cachePage(request,fresh,{ctx,deployId:await deployId(),...cacheControl?{cacheControl}:{},...branchCookie?{branchCookie}:{}})}catch(error){console.error(error);let owner;try{owner=typeof store==="function"?store(env):store}catch{owner=void 0}return platformErrorResponse("went-wrong",owner?{store:owner}:{})}}}}function originFetch(origin,fetcher=(input,init)=>globalThis.fetch(input,init)){return(input,init)=>{const headers=new Headers(init?.headers??(input instanceof Request?input.headers:void 0));if(!headers.has("origin")){headers.set("origin",origin)}return fetcher(input,{...init,headers})}}export{originFetch,siteWorker};
|
|
2
2
|
//# sourceMappingURL=site-worker.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/server/site-worker.ts"],
|
|
4
|
-
"mappings": "AAAA,
|
|
4
|
+
"mappings": "AAAA,OACE,0BAEK,0BACP,OAAS,eAAgB,eAAkB,0BAC3C,OAAS,UAAW,wBAA6C,kBAsD1D,SAAS,WAAsC,CACpD,OACA,SACA,aACA,aACA,SACA,KACF,EAEE,CACA,MAAO,CACL,MAAM,MAAM,QAAS,IAAK,IAAK,CAC7B,GAAI,CACF,GAAI,WAAW,OAAO,EAAG,CACvB,MAAM,SAAW,MAAM,OACrB,IAAI,QAAQ,IAAI,IAA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