@tokenoftrust/storefront-runner 6.15.0 → 6.15.1
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/apps/storefront/src/components/catalog/storefront/islands/VariantSelector.tsx +28 -8
- package/apps/storefront/src/lib/inventory/mirrorStock.ts +26 -2
- package/apps/storefront/src/lib/inventory/publicAvailability.ts +226 -0
- package/apps/storefront/src/lib/inventory/publicAvailabilityOverlay.ts +59 -0
- package/apps/storefront/src/lib/inventory/publicAvailabilityRuntime.ts +49 -0
- package/apps/storefront/src/middleware/controlPlane.ts +27 -1
- package/apps/storefront/src/middleware/index.ts +37 -0
- package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +3 -1
- package/apps/storefront/src/pages/products/[handle].astro +5 -0
- package/package.json +1 -1
- package/packages/cli/src/publication-spaces.mjs +1 -1
- package/packages/public-runtime/schemas/publication-space/v1/manifest.schema.json +1 -1
- package/packages/public-runtime/schemas/publication-space/v1/normalized-mount.schema.json +1 -1
- package/packages/public-runtime/src/publication-space.ts +1 -0
- package/scripts/publish/lib/public-availability.mjs +193 -0
|
@@ -29,6 +29,7 @@ import { priceForPurchaseOption } from "@tot/public-runtime";
|
|
|
29
29
|
import { formatPrice } from "@/lib/content/shared/format";
|
|
30
30
|
import { stockStatus } from "@/lib/catalog/shared/stockStatus";
|
|
31
31
|
import { useCheckoutHandoffCorrelation } from "@/lib/checkout/browser/useCheckoutHandoffCorrelation";
|
|
32
|
+
import { loadPublicAvailability, overlayPublicAvailability } from "@/lib/inventory/publicAvailabilityOverlay";
|
|
32
33
|
|
|
33
34
|
export type PublicSelectorVariant = Pick<CatalogVariant,
|
|
34
35
|
"id" | "sku" | "price" | "compare_at_price" | "option_values" | "inventory" | "image_id">;
|
|
@@ -90,6 +91,12 @@ interface Props {
|
|
|
90
91
|
* passthrough field on the managed-cart form. Undefined → no correlation.
|
|
91
92
|
*/
|
|
92
93
|
handoffUrl?: string;
|
|
94
|
+
/**
|
|
95
|
+
* Base-path-aware URL of the stage's public availability document (ADR 0043). The island paints
|
|
96
|
+
* with the baked stock stamp, then replaces it with the document's bands after hydration.
|
|
97
|
+
* Undefined → the baked stamp stands.
|
|
98
|
+
*/
|
|
99
|
+
availabilityUrl?: string;
|
|
93
100
|
}
|
|
94
101
|
|
|
95
102
|
type Selection = Record<string, string>;
|
|
@@ -99,14 +106,14 @@ function variantMatches(v: PublicSelectorVariant, sel: Selection): boolean {
|
|
|
99
106
|
}
|
|
100
107
|
|
|
101
108
|
function findVariant(
|
|
102
|
-
variants: PublicSelectorVariant[],
|
|
109
|
+
variants: readonly PublicSelectorVariant[],
|
|
103
110
|
sel: Selection,
|
|
104
111
|
): PublicSelectorVariant | undefined {
|
|
105
112
|
return variants.find((v) => variantMatches(v, sel));
|
|
106
113
|
}
|
|
107
114
|
|
|
108
115
|
export default function VariantSelector({
|
|
109
|
-
variants,
|
|
116
|
+
variants: initialVariants,
|
|
110
117
|
options,
|
|
111
118
|
currency,
|
|
112
119
|
locale,
|
|
@@ -115,7 +122,20 @@ export default function VariantSelector({
|
|
|
115
122
|
checkoutCart,
|
|
116
123
|
pricing,
|
|
117
124
|
handoffUrl,
|
|
125
|
+
availabilityUrl,
|
|
118
126
|
}: Props) {
|
|
127
|
+
const [variants, setVariants] = useState<readonly PublicSelectorVariant[]>(initialVariants);
|
|
128
|
+
useEffect(() => {
|
|
129
|
+
setVariants(initialVariants);
|
|
130
|
+
if (!availabilityUrl || typeof fetch !== "function") return;
|
|
131
|
+
const controller = new AbortController();
|
|
132
|
+
void loadPublicAvailability(availabilityUrl, fetch, controller.signal).then((doc) => {
|
|
133
|
+
if (doc && !controller.signal.aborted) {
|
|
134
|
+
setVariants(overlayPublicAvailability(initialVariants, doc, Date.now()));
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
return () => controller.abort();
|
|
138
|
+
}, [availabilityUrl, initialVariants]);
|
|
119
139
|
// Checkout-correlation handoff mint (ext-commerce-10): resolved once the server
|
|
120
140
|
// attributes this shopper (analytics consent granted + signing secret present),
|
|
121
141
|
// else null → the buy form carries no correlation and the order is unattributed.
|
|
@@ -130,7 +150,7 @@ export default function VariantSelector({
|
|
|
130
150
|
// Default selection: first available variant (fallback: first variant).
|
|
131
151
|
const defaultSelection = useMemo<Selection>(() => {
|
|
132
152
|
const base =
|
|
133
|
-
|
|
153
|
+
initialVariants.find((v) => v.inventory.available) ?? initialVariants[0];
|
|
134
154
|
const sel: Selection = {};
|
|
135
155
|
if (base) {
|
|
136
156
|
for (const opt of sortedOptions) {
|
|
@@ -139,7 +159,7 @@ export default function VariantSelector({
|
|
|
139
159
|
}
|
|
140
160
|
}
|
|
141
161
|
return sel;
|
|
142
|
-
}, [
|
|
162
|
+
}, [initialVariants, sortedOptions]);
|
|
143
163
|
|
|
144
164
|
const [selection, setSelection] = useState<Selection>(defaultSelection);
|
|
145
165
|
const [quantity, setQuantity] = useState(1);
|
|
@@ -310,12 +330,12 @@ export default function VariantSelector({
|
|
|
310
330
|
</span>
|
|
311
331
|
)}
|
|
312
332
|
</div>
|
|
313
|
-
{stock && (
|
|
333
|
+
{(stock || availabilityUrl) && (
|
|
314
334
|
<p
|
|
315
|
-
data-product-availability={stock
|
|
316
|
-
class={`font-mono text-xs uppercase tracking-[0.08em] ${STOCK_CLASS[stock.state]}`}
|
|
335
|
+
data-product-availability={stock?.state ?? ""}
|
|
336
|
+
class={`min-h-[1rem] font-mono text-xs uppercase tracking-[0.08em] ${stock ? STOCK_CLASS[stock.state] : ""}`}
|
|
317
337
|
>
|
|
318
|
-
{stock
|
|
338
|
+
{stock?.label ?? ""}
|
|
319
339
|
</p>
|
|
320
340
|
)}
|
|
321
341
|
{selected.sku && (
|
|
@@ -296,16 +296,40 @@ export async function readAvailabilityBalances(
|
|
|
296
296
|
}
|
|
297
297
|
|
|
298
298
|
/**
|
|
299
|
-
*
|
|
300
|
-
*
|
|
299
|
+
* Publishes the public availability document (ADR 0043). It reads the balances itself, as often as
|
|
300
|
+
* it needs to converge with concurrent writers, from the store the KV projection reads.
|
|
301
|
+
*/
|
|
302
|
+
export type PublicAvailabilityPublisher = (input: {
|
|
303
|
+
tenantId: string;
|
|
304
|
+
stage: CommerceStage;
|
|
305
|
+
readBalances: () => Promise<ReadonlyMap<string, MirrorBalance>>;
|
|
306
|
+
}) => Promise<void>;
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Rewrites the whole TENANT_CACHE projection for the tenant and stage from stored availability,
|
|
310
|
+
* then the public availability document when a publisher is given.
|
|
311
|
+
* Unconditional: a retried or no-op write repairs a put that failed after an earlier commit. A
|
|
312
|
+
* publisher failure never fails the KV projection; the next write repeats it.
|
|
301
313
|
*/
|
|
302
314
|
export async function writeAvailabilityProjection(
|
|
303
315
|
db: Queryable,
|
|
304
316
|
kv: { put(key: string, value: string): Promise<unknown> },
|
|
305
317
|
input: { tenantId: string; stage: CommerceStage },
|
|
318
|
+
publishPublic?: PublicAvailabilityPublisher,
|
|
306
319
|
): Promise<void> {
|
|
307
320
|
const balances = await readAvailabilityBalances(db, input);
|
|
308
321
|
await kv.put(mirrorBalanceKey(input.tenantId, input.stage), serializeMirrorBalances(balances));
|
|
322
|
+
if (!publishPublic) return;
|
|
323
|
+
try {
|
|
324
|
+
await publishPublic({ tenantId: input.tenantId, stage: input.stage, readBalances: () => readAvailabilityBalances(db, input) });
|
|
325
|
+
} catch (error) {
|
|
326
|
+
console.warn(JSON.stringify({
|
|
327
|
+
event: "inventory.public_availability.write_failed",
|
|
328
|
+
tenantId: input.tenantId,
|
|
329
|
+
stage: input.stage,
|
|
330
|
+
error: error instanceof Error ? error.name : "unknown",
|
|
331
|
+
}));
|
|
332
|
+
}
|
|
309
333
|
}
|
|
310
334
|
|
|
311
335
|
async function digestId(prefix: string, parts: readonly string[]): Promise<string> {
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The public availability document's Worker half (ADR 0043): write it on every stock change, and
|
|
3
|
+
* serve the stored bytes. Opens neither D1 nor env; the runtime wiring is publicAvailabilityRuntime.
|
|
4
|
+
*
|
|
5
|
+
* Write path, per provider:
|
|
6
|
+
* - Cloudflare: the document is an object in STATIC_BUNDLES, served by key (`servePublicAvailability`).
|
|
7
|
+
* - CloudFront (`serving.provider: s3-overwrite`, publication stage): the same object is the source
|
|
8
|
+
* CI copies into the tenant's bucket. A changed document sends one `www-publish` dispatch with
|
|
9
|
+
* the `availability-v1` operation; CI reads the CURRENT object when it runs, so dispatches that
|
|
10
|
+
* coalesce still land the newest document. The object records whether that dispatch was sent,
|
|
11
|
+
* so a failed send is retried by the next write even when the bands did not change.
|
|
12
|
+
*
|
|
13
|
+
* Concurrent writers converge on current stock: each one re-reads the balances after its put and
|
|
14
|
+
* writes again until the stored document matches what it read, so a slow writer holding an older
|
|
15
|
+
* reading never leaves its bands in place.
|
|
16
|
+
*/
|
|
17
|
+
import type { TenantConfig } from "@tot/public-runtime";
|
|
18
|
+
import {
|
|
19
|
+
buildPublicAvailabilityDoc,
|
|
20
|
+
PREVIEW_AVAILABILITY_CACHE_CONTROL,
|
|
21
|
+
PUBLIC_AVAILABILITY_CONTENT_TYPE,
|
|
22
|
+
PUBLICATION_AVAILABILITY_CACHE_CONTROL,
|
|
23
|
+
publicAvailabilityObjectKey,
|
|
24
|
+
type PublicAvailabilityStage,
|
|
25
|
+
} from "../../../../../scripts/publish/lib/public-availability.mjs";
|
|
26
|
+
|
|
27
|
+
/** The operation discriminator CI's router (`publication-space-dispatch.mjs route`) dispatches on. */
|
|
28
|
+
export const WWW_AVAILABILITY_OPERATION = "availability-v1";
|
|
29
|
+
|
|
30
|
+
export interface AvailabilityObject {
|
|
31
|
+
text(): Promise<string>;
|
|
32
|
+
etag?: string;
|
|
33
|
+
customMetadata?: Record<string, string>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface AvailabilityBucket {
|
|
37
|
+
get(key: string): Promise<AvailabilityObject | null>;
|
|
38
|
+
put(
|
|
39
|
+
key: string,
|
|
40
|
+
value: string,
|
|
41
|
+
options: {
|
|
42
|
+
httpMetadata: { contentType: string; cacheControl: string };
|
|
43
|
+
customMetadata: Record<string, string>;
|
|
44
|
+
onlyIf?: { etagMatches: string };
|
|
45
|
+
},
|
|
46
|
+
): Promise<{ etag?: string } | null>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Hands a CloudFront tenant's publication document to CI's S3 projection. */
|
|
50
|
+
export interface CloudFrontAvailabilityDispatch {
|
|
51
|
+
publish(tenantId: string): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface PublicAvailabilityDeps {
|
|
55
|
+
bucket: AvailabilityBucket;
|
|
56
|
+
/** Present only for a CloudFront-served tenant. */
|
|
57
|
+
cloudFront?: CloudFrontAvailabilityDispatch | null;
|
|
58
|
+
now?: () => string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export type PublicAvailabilityOutcome = "unchanged" | "written" | "dispatched" | "dispatch-failed";
|
|
62
|
+
|
|
63
|
+
/** Puts one writer makes before it leaves convergence to the writers still racing it. */
|
|
64
|
+
export const PUBLIC_AVAILABILITY_MAX_PUTS = 4;
|
|
65
|
+
|
|
66
|
+
/** `s3` metadata on the stored object: the S3 copy's state for a CloudFront tenant's publication document. */
|
|
67
|
+
const S3_SENT = "sent";
|
|
68
|
+
const S3_PENDING = "pending";
|
|
69
|
+
const S3_NONE = "none";
|
|
70
|
+
|
|
71
|
+
export function availabilityCacheControl(stage: PublicAvailabilityStage): string {
|
|
72
|
+
return stage === "publication" ? PUBLICATION_AVAILABILITY_CACHE_CONTROL : PREVIEW_AVAILABILITY_CACHE_CONTROL;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Recompute the tenant's document for one stage from the balances `readBalances` returns, and store
|
|
77
|
+
* it when its bytes changed. The balances are read before the stored object and again after every
|
|
78
|
+
* put; the write is done only when a fresh reading builds the stored bytes. Throws on a storage
|
|
79
|
+
* failure, or when the document still moved after `PUBLIC_AVAILABILITY_MAX_PUTS` puts (the writers
|
|
80
|
+
* racing it then hold newer readings). A failed CloudFront dispatch is an outcome, retried by the
|
|
81
|
+
* next write.
|
|
82
|
+
*/
|
|
83
|
+
export async function writePublicAvailability(
|
|
84
|
+
deps: PublicAvailabilityDeps,
|
|
85
|
+
input: {
|
|
86
|
+
tenantId: string;
|
|
87
|
+
stage: PublicAvailabilityStage;
|
|
88
|
+
readBalances: () => Promise<Iterable<[string, { balance: number; asOf: string }]>>;
|
|
89
|
+
},
|
|
90
|
+
): Promise<PublicAvailabilityOutcome> {
|
|
91
|
+
const key = publicAvailabilityObjectKey(input.tenantId, input.stage);
|
|
92
|
+
const cloudFront = input.stage === "publication" ? deps.cloudFront ?? null : null;
|
|
93
|
+
const httpMetadata = { contentType: PUBLIC_AVAILABILITY_CONTENT_TYPE, cacheControl: availabilityCacheControl(input.stage) };
|
|
94
|
+
let puts = 0;
|
|
95
|
+
for (;;) {
|
|
96
|
+
const body = buildPublicAvailabilityDoc(await input.readBalances(), {
|
|
97
|
+
stage: input.stage,
|
|
98
|
+
now: deps.now?.() ?? new Date().toISOString(),
|
|
99
|
+
});
|
|
100
|
+
const existing = await deps.bucket.get(key);
|
|
101
|
+
const prior = existing ? await existing.text() : null;
|
|
102
|
+
if (prior === body) {
|
|
103
|
+
if (!cloudFront) return puts === 0 ? "unchanged" : "written";
|
|
104
|
+
if (existing?.customMetadata?.s3 === S3_SENT) return puts === 0 ? "unchanged" : "written";
|
|
105
|
+
try {
|
|
106
|
+
await cloudFront.publish(input.tenantId);
|
|
107
|
+
} catch {
|
|
108
|
+
return "dispatch-failed";
|
|
109
|
+
}
|
|
110
|
+
// Marked sent only if no newer write replaced this object meanwhile; that writer dispatches itself.
|
|
111
|
+
if (existing?.etag) {
|
|
112
|
+
await deps.bucket.put(key, body, { httpMetadata, customMetadata: { s3: S3_SENT }, onlyIf: { etagMatches: existing.etag } });
|
|
113
|
+
}
|
|
114
|
+
return "dispatched";
|
|
115
|
+
}
|
|
116
|
+
if (puts === PUBLIC_AVAILABILITY_MAX_PUTS) throw new Error("availability document did not settle");
|
|
117
|
+
await deps.bucket.put(key, body, { httpMetadata, customMetadata: { s3: cloudFront ? S3_PENDING : S3_NONE } });
|
|
118
|
+
puts += 1;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The stored document as a response, or 404 when this tenant has none for the stage. The body is
|
|
124
|
+
* served verbatim: the writer is the only producer, and the bytes are what the S3 copy holds.
|
|
125
|
+
*/
|
|
126
|
+
export async function servePublicAvailability(input: {
|
|
127
|
+
bucket: Pick<AvailabilityBucket, "get"> | undefined;
|
|
128
|
+
tenantId: string;
|
|
129
|
+
stage: PublicAvailabilityStage;
|
|
130
|
+
method: string;
|
|
131
|
+
}): Promise<Response> {
|
|
132
|
+
const cacheControl = availabilityCacheControl(input.stage);
|
|
133
|
+
const headers = { "content-type": PUBLIC_AVAILABILITY_CONTENT_TYPE, "cache-control": cacheControl, "x-content-type-options": "nosniff" };
|
|
134
|
+
if (input.method !== "GET" && input.method !== "HEAD") {
|
|
135
|
+
return new Response(null, { status: 405, headers: { allow: "GET, HEAD", "cache-control": "no-store" } });
|
|
136
|
+
}
|
|
137
|
+
let object: AvailabilityObject | null = null;
|
|
138
|
+
if (input.bucket) {
|
|
139
|
+
try {
|
|
140
|
+
object = await input.bucket.get(publicAvailabilityObjectKey(input.tenantId, input.stage));
|
|
141
|
+
} catch {
|
|
142
|
+
object = null;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (!object) return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
|
|
146
|
+
const body = await object.text();
|
|
147
|
+
return new Response(input.method === "HEAD" ? null : body, {
|
|
148
|
+
status: 200,
|
|
149
|
+
headers: { ...headers, ...(object.etag ? { etag: `"${object.etag}"` } : {}) },
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Who may read a stage's document. Publication bands are what every visitor's product page shows.
|
|
155
|
+
* Preview bands are test-mode stock: only a verified preview context, or a viewer the login gate
|
|
156
|
+
* admitted to a store that is not public, reads them. A preview host alone admits nothing, exactly
|
|
157
|
+
* as its pages refuse a request without a valid preview token.
|
|
158
|
+
*/
|
|
159
|
+
export function availabilityStageAdmitted(input: {
|
|
160
|
+
stage: PublicAvailabilityStage;
|
|
161
|
+
previewTokenValid: boolean;
|
|
162
|
+
admittedToPrivateStore: boolean;
|
|
163
|
+
}): boolean {
|
|
164
|
+
if (input.stage === "publication") return true;
|
|
165
|
+
return input.previewTokenValid || input.admittedToPrivateStore;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
type EnvReader = (key: string) => Promise<string | undefined>;
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* The CloudFront dispatch for a tenant whose publication is CDN → S3, or null for every other
|
|
172
|
+
* tenant and for an unconfigured dispatch. Coordinates come from env, never tenant config. The
|
|
173
|
+
* dispatch id is constant per tenant: the `www-publish` shim's concurrency group then keeps one
|
|
174
|
+
* running and one pending projection, and the pending one reads the newest document.
|
|
175
|
+
*/
|
|
176
|
+
export async function createCloudFrontAvailabilityDispatch(input: {
|
|
177
|
+
tenant: Pick<TenantConfig, "serving" | "staticPublish">;
|
|
178
|
+
readEnv: EnvReader;
|
|
179
|
+
fetchImpl?: typeof fetch;
|
|
180
|
+
}): Promise<CloudFrontAvailabilityDispatch | null> {
|
|
181
|
+
const staticPublish = input.tenant.staticPublish;
|
|
182
|
+
if (input.tenant.serving?.provider !== "s3-overwrite" || !staticPublish || staticPublish.enabled === false) return null;
|
|
183
|
+
const [tokenValue, repoValue, apiBaseValue] = await Promise.all([
|
|
184
|
+
input.readEnv("WWW_PUBLISH_DISPATCH_TOKEN"),
|
|
185
|
+
input.readEnv("WWW_PUBLISH_DISPATCH_REPO"),
|
|
186
|
+
input.readEnv("WWW_PUBLISH_DISPATCH_API_BASE"),
|
|
187
|
+
]);
|
|
188
|
+
const token = tokenValue?.trim();
|
|
189
|
+
const parts = (repoValue?.trim() || "tokenoftrust/storefront").split("/");
|
|
190
|
+
const plain = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
191
|
+
if (!token || parts.length !== 2 || !plain.test(parts[0] ?? "") || !plain.test(parts[1] ?? "")) return null;
|
|
192
|
+
const url = `${(apiBaseValue?.trim() || "https://api.github.com").replace(/\/+$/, "")}/repos/${parts[0]}/${parts[1]}/dispatches`;
|
|
193
|
+
const doFetch = input.fetchImpl ?? fetch;
|
|
194
|
+
return {
|
|
195
|
+
async publish(tenantId) {
|
|
196
|
+
// The `www-publish` repository_dispatch envelope the shim validates; no document rides in it.
|
|
197
|
+
const response = await doFetch(url, {
|
|
198
|
+
method: "POST",
|
|
199
|
+
headers: {
|
|
200
|
+
authorization: `Bearer ${token}`,
|
|
201
|
+
accept: "application/vnd.github+json",
|
|
202
|
+
"content-type": "application/json",
|
|
203
|
+
"user-agent": "tot-storefront-availability",
|
|
204
|
+
},
|
|
205
|
+
body: JSON.stringify({
|
|
206
|
+
event_type: "www-publish",
|
|
207
|
+
client_payload: {
|
|
208
|
+
tenantId,
|
|
209
|
+
versionId: "",
|
|
210
|
+
ref: "",
|
|
211
|
+
sourceSha: null,
|
|
212
|
+
phase: "live",
|
|
213
|
+
target: staticPublish.target ?? null,
|
|
214
|
+
params: { wwwPublishOperation: WWW_AVAILABILITY_OPERATION },
|
|
215
|
+
reason: "availability",
|
|
216
|
+
dispatchId: `availability:${tenantId}`,
|
|
217
|
+
dispatchedAt: new Date().toISOString(),
|
|
218
|
+
},
|
|
219
|
+
}),
|
|
220
|
+
signal: AbortSignal.timeout(10_000),
|
|
221
|
+
});
|
|
222
|
+
await response.body?.cancel().catch(() => {});
|
|
223
|
+
if (!response.ok) throw new Error(`availability dispatch answered HTTP ${response.status}`);
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Product-page hydration from the public availability document (ADR 0043). The page paints with
|
|
3
|
+
* its baked stamp; after hydration it fetches the document and replaces each variant's inventory
|
|
4
|
+
* with the band the document claims for its sku. Any failure (network, status, a malformed or
|
|
5
|
+
* stale document) keeps the baked stamp.
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
parsePublicAvailabilityDoc,
|
|
9
|
+
publicAvailabilityInventory,
|
|
10
|
+
type PublicAvailabilityDoc,
|
|
11
|
+
} from "../../../../../scripts/publish/lib/public-availability.mjs";
|
|
12
|
+
|
|
13
|
+
interface InventoryBearing {
|
|
14
|
+
sku?: string;
|
|
15
|
+
inventory: { available: boolean; quantity?: number };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The variants with each sku's band applied. Returns the same array when nothing changes, so a
|
|
20
|
+
* caller holding it in state does not re-render for an identical document.
|
|
21
|
+
*/
|
|
22
|
+
export function overlayPublicAvailability<T extends InventoryBearing>(
|
|
23
|
+
variants: readonly T[],
|
|
24
|
+
doc: PublicAvailabilityDoc,
|
|
25
|
+
nowMs: number,
|
|
26
|
+
): readonly T[] {
|
|
27
|
+
let changed = false;
|
|
28
|
+
const next = variants.map((variant) => {
|
|
29
|
+
const live = publicAvailabilityInventory(doc, variant.sku, nowMs);
|
|
30
|
+
if (!live) return variant;
|
|
31
|
+
if (variant.inventory.available === live.available && variant.inventory.quantity === live.quantity) return variant;
|
|
32
|
+
changed = true;
|
|
33
|
+
return { ...variant, inventory: live };
|
|
34
|
+
});
|
|
35
|
+
return changed ? next : variants;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The document at `url`, or null for anything but a well-formed 200. A network failure or an abort
|
|
40
|
+
* (the island unmounting) is null too; anything else is a bug and propagates.
|
|
41
|
+
*/
|
|
42
|
+
export async function loadPublicAvailability(
|
|
43
|
+
url: string,
|
|
44
|
+
fetchImpl: typeof fetch,
|
|
45
|
+
signal?: AbortSignal,
|
|
46
|
+
): Promise<PublicAvailabilityDoc | null> {
|
|
47
|
+
try {
|
|
48
|
+
const response = await fetchImpl(url, {
|
|
49
|
+
credentials: "same-origin",
|
|
50
|
+
headers: { accept: "application/json" },
|
|
51
|
+
...(signal ? { signal } : {}),
|
|
52
|
+
});
|
|
53
|
+
if (response.status !== 200) return null;
|
|
54
|
+
return parsePublicAvailabilityDoc(await response.text());
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error instanceof TypeError || (error instanceof Error && error.name === "AbortError")) return null;
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime wiring for the public availability document (ADR 0043): the STATIC_BUNDLES bucket, the
|
|
3
|
+
* tenant's declared serving provider, and the CloudFront dispatch coordinates. Every stock write
|
|
4
|
+
* that refreshes the KV mirror projection passes this publisher along with it.
|
|
5
|
+
*/
|
|
6
|
+
import { commerceTenantId, type TenantConfig } from "@tot/public-runtime";
|
|
7
|
+
import { readEnv, readR2, runAfterResponse, type CfExecutionContextLike } from "@/lib/publication/shared/runtimeEnv";
|
|
8
|
+
import type { PublicAvailabilityPublisher } from "./mirrorStock";
|
|
9
|
+
import {
|
|
10
|
+
createCloudFrontAvailabilityDispatch,
|
|
11
|
+
writePublicAvailability,
|
|
12
|
+
type AvailabilityBucket,
|
|
13
|
+
} from "./publicAvailability";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The publisher for this request, from its locals: the tenant the middleware resolved and the
|
|
17
|
+
* ExecutionContext the Cloudflare adapter exposes as `locals.cfContext`. With that context the
|
|
18
|
+
* document is written past the response, so a stock write (a checkout authorization included)
|
|
19
|
+
* never waits on storage or a dispatch. Without a bundle store (plain `astro dev`) nothing is
|
|
20
|
+
* published.
|
|
21
|
+
*/
|
|
22
|
+
export async function publicAvailabilityPublisher(locals: unknown): Promise<PublicAvailabilityPublisher | undefined> {
|
|
23
|
+
const bucket = (await readR2("STATIC_BUNDLES")) as unknown as AvailabilityBucket | undefined;
|
|
24
|
+
if (!bucket) return undefined;
|
|
25
|
+
const scope = (locals ?? {}) as { tenant?: TenantConfig; cfContext?: CfExecutionContextLike };
|
|
26
|
+
const cfContext = scope.cfContext ?? null;
|
|
27
|
+
const publish: PublicAvailabilityPublisher = async ({ tenantId, stage, readBalances }) => {
|
|
28
|
+
const tenant = scope.tenant;
|
|
29
|
+
const owned = tenant && commerceTenantId(tenant) === tenantId ? tenant : null;
|
|
30
|
+
const cloudFront = owned && stage === "publication"
|
|
31
|
+
? await createCloudFrontAvailabilityDispatch({ tenant: owned, readEnv })
|
|
32
|
+
: null;
|
|
33
|
+
const outcome = await writePublicAvailability({ bucket, cloudFront }, { tenantId, stage, readBalances });
|
|
34
|
+
if (outcome === "dispatch-failed") {
|
|
35
|
+
console.warn(JSON.stringify({ event: "inventory.public_availability.dispatch_failed", tenantId, stage }));
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
if (!cfContext) return publish;
|
|
39
|
+
return async (input) => {
|
|
40
|
+
runAfterResponse(publish(input).catch((error: unknown) => {
|
|
41
|
+
console.warn(JSON.stringify({
|
|
42
|
+
event: "inventory.public_availability.write_failed",
|
|
43
|
+
tenantId: input.tenantId,
|
|
44
|
+
stage: input.stage,
|
|
45
|
+
error: error instanceof Error ? error.name : "unknown",
|
|
46
|
+
}));
|
|
47
|
+
}), cfContext);
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -8,7 +8,14 @@
|
|
|
8
8
|
* to the shared render chain with those values supplied.
|
|
9
9
|
*/
|
|
10
10
|
import type { APIContext, MiddlewareNext } from "astro";
|
|
11
|
-
import { readEnv, readD1, readKv } from "@/lib/publication/shared/env";
|
|
11
|
+
import { readEnv, readD1, readKv, readR2 } from "@/lib/publication/shared/env";
|
|
12
|
+
import { applySecurityHeaders } from "@/lib/access/shared/securityHeaders";
|
|
13
|
+
import { publicAvailabilityStageOf } from "../../../../scripts/publish/lib/public-availability.mjs";
|
|
14
|
+
import {
|
|
15
|
+
availabilityStageAdmitted,
|
|
16
|
+
servePublicAvailability,
|
|
17
|
+
type AvailabilityBucket,
|
|
18
|
+
} from "@/lib/inventory/publicAvailability";
|
|
12
19
|
import { fromD1, type D1Like } from "@/lib/catalog/d1/catalog";
|
|
13
20
|
import { readCurrentTenantConsentConfig } from "@/lib/measurement/consent/consentConfigRead";
|
|
14
21
|
import { loadActiveManagedInstallDeclarations } from "@/lib/integrations/integration/managedInstallDeclarations";
|
|
@@ -273,6 +280,25 @@ export async function serveControlPlane(input: ControlPlaneInput): Promise<Respo
|
|
|
273
280
|
}
|
|
274
281
|
}
|
|
275
282
|
|
|
283
|
+
// The availability document (ADR 0043) on a login-gated host, reached only past the gate above.
|
|
284
|
+
const availabilityStage = publicAvailabilityStageOf(renderPath);
|
|
285
|
+
if (availabilityStage) {
|
|
286
|
+
const response = availabilityStageAdmitted({
|
|
287
|
+
stage: availabilityStage,
|
|
288
|
+
previewTokenValid: preview.context.status === "valid",
|
|
289
|
+
admittedToPrivateStore: input.hostLoginGated && !tenantIsDeclaredPublic(tenant.tenant_id),
|
|
290
|
+
})
|
|
291
|
+
? await servePublicAvailability({
|
|
292
|
+
bucket: (await readR2("STATIC_BUNDLES")) as unknown as AvailabilityBucket | undefined,
|
|
293
|
+
tenantId: commerceTenantId(tenant),
|
|
294
|
+
stage: availabilityStage,
|
|
295
|
+
method: request.method,
|
|
296
|
+
})
|
|
297
|
+
: new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
|
|
298
|
+
applySecurityHeaders(response.headers);
|
|
299
|
+
return response;
|
|
300
|
+
}
|
|
301
|
+
|
|
276
302
|
// /dev is the old name of /cockpit. 302-redirect any /dev link — host-routed (/dev)
|
|
277
303
|
// or path-routed (/<vendor>/dev) — to the cockpit, keeping the tenant prefix. The
|
|
278
304
|
// target is a sanitized pathname: the request query never reaches the Location.
|
|
@@ -50,6 +50,12 @@ import {
|
|
|
50
50
|
resolveMiddlewareBranchV1,
|
|
51
51
|
} from "./routeBranch.js";
|
|
52
52
|
import { servePublicRender } from "./publicRender.js";
|
|
53
|
+
import { publicAvailabilityStageOf } from "../../../../scripts/publish/lib/public-availability.mjs";
|
|
54
|
+
import {
|
|
55
|
+
availabilityStageAdmitted,
|
|
56
|
+
servePublicAvailability,
|
|
57
|
+
type AvailabilityBucket,
|
|
58
|
+
} from "@/lib/inventory/publicAvailability";
|
|
53
59
|
import { mirrorBalanceKey, parseMirrorBalances, publicMirrorStage } from "@/lib/inventory/mirrorBalanceProjection";
|
|
54
60
|
import { serveControlPlane } from "./controlPlane.js";
|
|
55
61
|
import { KvSessionStore, SESSION_COOKIE } from "@/lib/access/auth/session";
|
|
@@ -224,6 +230,37 @@ async function serveRequest(
|
|
|
224
230
|
locals.routeTier = route;
|
|
225
231
|
locals.publicationRoute = publication;
|
|
226
232
|
|
|
233
|
+
// The availability document (ADR 0043): stored bytes by key, one R2 read, no D1 and no render.
|
|
234
|
+
// On a login-gated host it is served by the control plane, after the gate.
|
|
235
|
+
const availabilityStage = publicAvailabilityStageOf(renderPath);
|
|
236
|
+
if (availabilityStage && !hostLoginGated) {
|
|
237
|
+
const previewTokenValid = availabilityStage === "preview"
|
|
238
|
+
? (await resolveRequestPreviewContext({
|
|
239
|
+
url,
|
|
240
|
+
request,
|
|
241
|
+
cookies: context.cookies,
|
|
242
|
+
renderPath,
|
|
243
|
+
tenantId: tenant.tenant_id,
|
|
244
|
+
secret: await readEnv("CUSTOMIZATION_PREVIEW_SECRET"),
|
|
245
|
+
nowSeconds: Math.floor(Date.now() / 1000),
|
|
246
|
+
})).context.status === "valid"
|
|
247
|
+
: false;
|
|
248
|
+
const response = availabilityStageAdmitted({
|
|
249
|
+
stage: availabilityStage,
|
|
250
|
+
previewTokenValid,
|
|
251
|
+
admittedToPrivateStore: false,
|
|
252
|
+
})
|
|
253
|
+
? await servePublicAvailability({
|
|
254
|
+
bucket: (await readR2("STATIC_BUNDLES")) as unknown as AvailabilityBucket | undefined,
|
|
255
|
+
tenantId: commerceTenantId(tenant),
|
|
256
|
+
stage: availabilityStage,
|
|
257
|
+
method: request.method,
|
|
258
|
+
})
|
|
259
|
+
: new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
|
|
260
|
+
applySecurityHeaders(response.headers);
|
|
261
|
+
return response;
|
|
262
|
+
}
|
|
263
|
+
|
|
227
264
|
// Public aliases are an edge decision from the same normalized publication
|
|
228
265
|
// plan. Preserve the path-routing tenant prefix and request query while the
|
|
229
266
|
// canonical target itself remains tenant-relative. Authorization-gated alias
|
|
@@ -12,6 +12,7 @@ import { readD1, readEnv, readKv } from "@/lib/publication/shared/env";
|
|
|
12
12
|
import { evaluateFinalCart, type RefusedLine, type SeamView } from "@/lib/checkout/commerce/finalCartAuthorization.js";
|
|
13
13
|
import { d1CommerceRunner, reserveAllocation } from "@/lib/inventory/allocations.js";
|
|
14
14
|
import { readMirrorBalance, readMirrorStock, writeAvailabilityProjection } from "@/lib/inventory/mirrorStock.js";
|
|
15
|
+
import { publicAvailabilityPublisher } from "@/lib/inventory/publicAvailabilityRuntime";
|
|
15
16
|
import { admissionMatches, readCommerceAdmission, admissionSnapshotStatement } from "@/lib/checkout/commerce/commerceAdmission.js";
|
|
16
17
|
import { evaluatePreflight } from "../compliance/preflight.js";
|
|
17
18
|
import {
|
|
@@ -415,7 +416,8 @@ async function authorize(context: APIContext): Promise<Response> {
|
|
|
415
416
|
if (!reserved.ok) return deny(reserved.finding);
|
|
416
417
|
if (kv && !reserved.repeated) {
|
|
417
418
|
try {
|
|
418
|
-
await writeAvailabilityProjection(queryable, kv, { tenantId: decision.tenantId, stage: decision.stage }
|
|
419
|
+
await writeAvailabilityProjection(queryable, kv, { tenantId: decision.tenantId, stage: decision.stage },
|
|
420
|
+
await publicAvailabilityPublisher(context.locals));
|
|
419
421
|
} catch {
|
|
420
422
|
// The reservation is the record. Pages keep the prior projection until the next write.
|
|
421
423
|
}
|
|
@@ -50,6 +50,7 @@ import { truncate } from "@/lib/content/shared/format";
|
|
|
50
50
|
import { productLd, breadcrumbLd, reviewLd } from "@/lib/content/shared/jsonld";
|
|
51
51
|
import { isUsableImageUrl } from "@/lib/content/shared/placeholder";
|
|
52
52
|
import { withBase } from "@/lib/publication/shared/basePath";
|
|
53
|
+
import { publicAvailabilityPath } from "../../../../../scripts/publish/lib/public-availability.mjs";
|
|
53
54
|
import { productPageType, structuredDataProfile } from "@/lib/content/seo/structuredData";
|
|
54
55
|
import { pageUrlForm } from "@/lib/content/seo/urlForm";
|
|
55
56
|
import { sourceSeoTitle } from "@/lib/content/seo/documentTitle";
|
|
@@ -432,6 +433,10 @@ const structuredData = {
|
|
|
432
433
|
? cartApiPath
|
|
433
434
|
: undefined
|
|
434
435
|
}
|
|
436
|
+
availabilityUrl={withBase(
|
|
437
|
+
basePath,
|
|
438
|
+
publicAvailabilityPath(Astro.locals.customizationEnv === "live" ? "publication" : "preview"),
|
|
439
|
+
)}
|
|
435
440
|
/>
|
|
436
441
|
{/* Regulated-tenant checkout ENFORCEMENT gate. Intercepts the
|
|
437
442
|
managed-cart handoff to clear age + ship-to compliance server-side
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tokenoftrust/storefront-runner",
|
|
3
|
-
"version": "6.15.
|
|
3
|
+
"version": "6.15.1",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE",
|
|
5
5
|
"description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
|
|
6
6
|
"packageManager": "pnpm@11.9.0",
|
|
@@ -32,7 +32,7 @@ export const TOPOLOGY_VERSION = 1;
|
|
|
32
32
|
* packages/public-runtime/src/sitemap-index.mjs, pinned by test/sitemap-index-copy.test.mjs).
|
|
33
33
|
*/
|
|
34
34
|
export const PLATFORM_PATHS = Object.freeze([
|
|
35
|
-
"/.well-known", "/__evidence", "/__preview", "/_a", "/_astro", "/_style-guide", "/admin", "/api",
|
|
35
|
+
"/.well-known", "/__evidence", "/__preview", "/_a", "/_astro", "/_availability", "/_style-guide", "/admin", "/api",
|
|
36
36
|
"/apps", "/assets", "/auth", "/brand", "/capabilities", "/cockpit", "/dashboard", "/dev",
|
|
37
37
|
"/favicon.svg", "/health", "/js", "/feed.json", "/llms.txt", "/publication-discovery",
|
|
38
38
|
"/search-index.json", "/sitemap.xml", "/platform", "/preview", "/products", "/collections",
|
|
@@ -207,7 +207,7 @@
|
|
|
207
207
|
"mountPath": {
|
|
208
208
|
"allOf": [
|
|
209
209
|
{ "$ref": "#/$defs/path" },
|
|
210
|
-
{ "type": "string", "pattern": "^/(?!(?:\\.[wW][eE][lL][lL]-[kK][nN][oO][wW][nN]|__[eE][vV][iI][dD][eE][nN][cC][eE]|__[pP][rR][eE][vV][iI][eE][wW]|_[aA]|_[aA][sS][tT][rR][oO]|_[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[aA][dD][mM][iI][nN]|[aA][pP][iI]|[aA][pP][pP][sS]|[aA][sS][sS][eE][tT][sS]|[aA][uU][tT][hH]|[bB][rR][aA][nN][dD]|[cC][aA][pP][aA][bB][iI][lL][iI][tT][iI][eE][sS]|[cC][aA][tT][aA][lL][oO][gG]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[cC][oO][cC][kK][pP][iI][tT]|[cC][oO][lL][lL][eE][cC][tT][iI][oO][nN][sS]|[dD][aA][sS][hH][bB][oO][aA][rR][dD]|[dD][eE][vV]|[fF][aA][vV][iI][cC][oO][nN]\\.[sS][vV][gG]|[fF][eE][eE][dD]\\.[jJ][sS][oO][nN]|[hH][eE][aA][lL][tT][hH]|[jJ][sS]|[lL][lL][mM][sS]\\.[tT][xX][tT]|[pP][lL][aA][tT][fF][oO][rR][mM]|[pP][rR][eE][vV][iI][eE][wW]|[pP][rR][oO][dD][uU][cC][tT][sS]|[pP][uU][bB][lL][iI][cC][aA][tT][iI][oO][nN]-[dD][iI][sS][cC][oO][vV][eE][rR][yY]|[rR][oO][bB][oO][tT][sS]\\.[tT][xX][tT]|[sS][aA][vV][eE][dD]|[sS][eE][aA][rR][cC][hH]|[sS][eE][aA][rR][cC][hH]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[sS][hH][aA][rR][eE][dD]|[sS][iI][tT][eE][mM][aA][pP]\\.[xX][mM][lL]|[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[tT][eE][nN][aA][nN][tT][sS])(?:/|$))" }
|
|
210
|
+
{ "type": "string", "pattern": "^/(?!(?:\\.[wW][eE][lL][lL]-[kK][nN][oO][wW][nN]|__[eE][vV][iI][dD][eE][nN][cC][eE]|__[pP][rR][eE][vV][iI][eE][wW]|_[aA]|_[aA][vV][aA][iI][lL][aA][bB][iI][lL][iI][tT][yY]|_[aA][sS][tT][rR][oO]|_[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[aA][dD][mM][iI][nN]|[aA][pP][iI]|[aA][pP][pP][sS]|[aA][sS][sS][eE][tT][sS]|[aA][uU][tT][hH]|[bB][rR][aA][nN][dD]|[cC][aA][pP][aA][bB][iI][lL][iI][tT][iI][eE][sS]|[cC][aA][tT][aA][lL][oO][gG]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[cC][oO][cC][kK][pP][iI][tT]|[cC][oO][lL][lL][eE][cC][tT][iI][oO][nN][sS]|[dD][aA][sS][hH][bB][oO][aA][rR][dD]|[dD][eE][vV]|[fF][aA][vV][iI][cC][oO][nN]\\.[sS][vV][gG]|[fF][eE][eE][dD]\\.[jJ][sS][oO][nN]|[hH][eE][aA][lL][tT][hH]|[jJ][sS]|[lL][lL][mM][sS]\\.[tT][xX][tT]|[pP][lL][aA][tT][fF][oO][rR][mM]|[pP][rR][eE][vV][iI][eE][wW]|[pP][rR][oO][dD][uU][cC][tT][sS]|[pP][uU][bB][lL][iI][cC][aA][tT][iI][oO][nN]-[dD][iI][sS][cC][oO][vV][eE][rR][yY]|[rR][oO][bB][oO][tT][sS]\\.[tT][xX][tT]|[sS][aA][vV][eE][dD]|[sS][eE][aA][rR][cC][hH]|[sS][eE][aA][rR][cC][hH]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[sS][hH][aA][rR][eE][dD]|[sS][iI][tT][eE][mM][aA][pP]\\.[xX][mM][lL]|[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[tT][eE][nN][aA][nN][tT][sS])(?:/|$))" }
|
|
211
211
|
]
|
|
212
212
|
},
|
|
213
213
|
"aliasPath": {
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
"mountPath": {
|
|
68
68
|
"allOf": [
|
|
69
69
|
{ "$ref": "#/$defs/normalizedPath" },
|
|
70
|
-
{ "type": "string", "pattern": "^/(?!(?:\\.[wW][eE][lL][lL]-[kK][nN][oO][wW][nN]|__[eE][vV][iI][dD][eE][nN][cC][eE]|__[pP][rR][eE][vV][iI][eE][wW]|_[aA]|_[aA][sS][tT][rR][oO]|_[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[aA][dD][mM][iI][nN]|[aA][pP][iI]|[aA][pP][pP][sS]|[aA][sS][sS][eE][tT][sS]|[aA][uU][tT][hH]|[bB][rR][aA][nN][dD]|[cC][aA][pP][aA][bB][iI][lL][iI][tT][iI][eE][sS]|[cC][aA][tT][aA][lL][oO][gG]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[cC][oO][cC][kK][pP][iI][tT]|[cC][oO][lL][lL][eE][cC][tT][iI][oO][nN][sS]|[dD][aA][sS][hH][bB][oO][aA][rR][dD]|[dD][eE][vV]|[fF][aA][vV][iI][cC][oO][nN]\\.[sS][vV][gG]|[fF][eE][eE][dD]\\.[jJ][sS][oO][nN]|[hH][eE][aA][lL][tT][hH]|[jJ][sS]|[lL][lL][mM][sS]\\.[tT][xX][tT]|[pP][lL][aA][tT][fF][oO][rR][mM]|[pP][rR][eE][vV][iI][eE][wW]|[pP][rR][oO][dD][uU][cC][tT][sS]|[pP][uU][bB][lL][iI][cC][aA][tT][iI][oO][nN]-[dD][iI][sS][cC][oO][vV][eE][rR][yY]|[rR][oO][bB][oO][tT][sS]\\.[tT][xX][tT]|[sS][aA][vV][eE][dD]|[sS][eE][aA][rR][cC][hH]|[sS][eE][aA][rR][cC][hH]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[sS][hH][aA][rR][eE][dD]|[sS][iI][tT][eE][mM][aA][pP]\\.[xX][mM][lL]|[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[tT][eE][nN][aA][nN][tT][sS])(?:/|$))" }
|
|
70
|
+
{ "type": "string", "pattern": "^/(?!(?:\\.[wW][eE][lL][lL]-[kK][nN][oO][wW][nN]|__[eE][vV][iI][dD][eE][nN][cC][eE]|__[pP][rR][eE][vV][iI][eE][wW]|_[aA]|_[aA][vV][aA][iI][lL][aA][bB][iI][lL][iI][tT][yY]|_[aA][sS][tT][rR][oO]|_[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[aA][dD][mM][iI][nN]|[aA][pP][iI]|[aA][pP][pP][sS]|[aA][sS][sS][eE][tT][sS]|[aA][uU][tT][hH]|[bB][rR][aA][nN][dD]|[cC][aA][pP][aA][bB][iI][lL][iI][tT][iI][eE][sS]|[cC][aA][tT][aA][lL][oO][gG]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[cC][oO][cC][kK][pP][iI][tT]|[cC][oO][lL][lL][eE][cC][tT][iI][oO][nN][sS]|[dD][aA][sS][hH][bB][oO][aA][rR][dD]|[dD][eE][vV]|[fF][aA][vV][iI][cC][oO][nN]\\.[sS][vV][gG]|[fF][eE][eE][dD]\\.[jJ][sS][oO][nN]|[hH][eE][aA][lL][tT][hH]|[jJ][sS]|[lL][lL][mM][sS]\\.[tT][xX][tT]|[pP][lL][aA][tT][fF][oO][rR][mM]|[pP][rR][eE][vV][iI][eE][wW]|[pP][rR][oO][dD][uU][cC][tT][sS]|[pP][uU][bB][lL][iI][cC][aA][tT][iI][oO][nN]-[dD][iI][sS][cC][oO][vV][eE][rR][yY]|[rR][oO][bB][oO][tT][sS]\\.[tT][xX][tT]|[sS][aA][vV][eE][dD]|[sS][eE][aA][rR][cC][hH]|[sS][eE][aA][rR][cC][hH]-[iI][nN][dD][eE][xX]\\.[jJ][sS][oO][nN]|[sS][hH][aA][rR][eE][dD]|[sS][iI][tT][eE][mM][aA][pP]\\.[xX][mM][lL]|[sS][tT][yY][lL][eE]-[gG][uU][iI][dD][eE]|[tT][eE][nN][aA][nN][tT][sS])(?:/|$))" }
|
|
71
71
|
]
|
|
72
72
|
},
|
|
73
73
|
"aliasPath": {
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* The public availability document (ADR 0043): per-sku stock bands a product page hydrates from
|
|
4
|
+
* after paint, recomputed on every stock change and served CDN → storage on both providers.
|
|
5
|
+
*
|
|
6
|
+
* URL `/_availability/v1/<stage>.json` (tenant-relative; `<stage>` is `publication` or `preview`)
|
|
7
|
+
* R2 `availability/v1/<tenantId>/<stage>.json` in STATIC_BUNDLES (Cloudflare serving + CI source)
|
|
8
|
+
* S3 `availability/v1/publication.json` in the tenant's bucket (CloudFront serving)
|
|
9
|
+
*
|
|
10
|
+
* The body carries no more than the product page already renders: a band per sku, where 0 is
|
|
11
|
+
* "Sold out", 1..LOW_STOCK_THRESHOLD is "Only N left", and PUBLIC_AVAILABILITY_CAP stands for every
|
|
12
|
+
* larger count ("In stock"). A positive band is only claimed while its mirror reading is fresh, so
|
|
13
|
+
* the document carries one `freshUntil` instant after which a reader drops every positive band and
|
|
14
|
+
* keeps the page's baked stamp. A sku with no tracked reading is absent.
|
|
15
|
+
*
|
|
16
|
+
* Pure and dependency-free: the Worker (writer, server), the product-page island and the CI
|
|
17
|
+
* projection (`scripts/publish/www-availability.mjs`) all import this one module.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export const PUBLIC_AVAILABILITY_VERSION = 1;
|
|
21
|
+
/** One above the product page's low-stock threshold: every larger count renders the same "In stock". */
|
|
22
|
+
export const PUBLIC_AVAILABILITY_CAP = 6;
|
|
23
|
+
/** A positive mirror reading is claimed for this long after its as-of instant (the mirror's own freshness). */
|
|
24
|
+
export const PUBLIC_AVAILABILITY_FRESH_MS = 15 * 60_000;
|
|
25
|
+
/** `freshUntil` is floored to this quantum, so a steady mirror refresh rewrites the document at most this often. */
|
|
26
|
+
export const PUBLIC_AVAILABILITY_FRESH_QUANTUM_MS = 5 * 60_000;
|
|
27
|
+
export const PUBLIC_AVAILABILITY_MAX_BYTES = 2 * 1024 * 1024;
|
|
28
|
+
export const PUBLIC_AVAILABILITY_MAX_SKUS = 50_000;
|
|
29
|
+
const MAX_SKU_LENGTH = 256;
|
|
30
|
+
|
|
31
|
+
/** @typedef {"preview" | "publication"} PublicAvailabilityStage */
|
|
32
|
+
/** @type {readonly PublicAvailabilityStage[]} */
|
|
33
|
+
export const PUBLIC_AVAILABILITY_STAGES = Object.freeze(["preview", "publication"]);
|
|
34
|
+
|
|
35
|
+
/** Shared caches may hold the publication document briefly and serve it stale while refetching. */
|
|
36
|
+
export const PUBLICATION_AVAILABILITY_CACHE_CONTROL = "public, max-age=15, s-maxage=30, stale-while-revalidate=45";
|
|
37
|
+
/** The preview document is test-mode stock behind a preview context: never stored by any cache. */
|
|
38
|
+
export const PREVIEW_AVAILABILITY_CACHE_CONTROL = "private, no-store";
|
|
39
|
+
export const PUBLIC_AVAILABILITY_CONTENT_TYPE = "application/json; charset=utf-8";
|
|
40
|
+
/** The CloudFront tenant's bucket key; the live-pointer function maps the public URL to it. */
|
|
41
|
+
export const PUBLIC_AVAILABILITY_S3_KEY = "availability/v1/publication.json";
|
|
42
|
+
|
|
43
|
+
const TENANT_ID = /^[a-z0-9](?:[a-z0-9._-]{0,190}[a-z0-9])?$/;
|
|
44
|
+
const OBJECT_KEY = /^availability\/v1\/([a-z0-9](?:[a-z0-9._-]{0,190}[a-z0-9])?)\/(preview|publication)\.json$/;
|
|
45
|
+
const PUBLIC_PATH = /^\/_availability\/v1\/(preview|publication)\.json$/;
|
|
46
|
+
const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
47
|
+
|
|
48
|
+
/** @param {unknown} value @returns {value is PublicAvailabilityStage} */
|
|
49
|
+
export function isPublicAvailabilityStage(value) {
|
|
50
|
+
return value === "preview" || value === "publication";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** @param {PublicAvailabilityStage} stage */
|
|
54
|
+
export function publicAvailabilityPath(stage) {
|
|
55
|
+
if (!isPublicAvailabilityStage(stage)) throw new Error("unknown availability stage");
|
|
56
|
+
return `/_availability/v1/${stage}.json`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The stage a tenant-relative path names, or null when it is not the availability document.
|
|
61
|
+
* @param {string} renderPath
|
|
62
|
+
* @returns {PublicAvailabilityStage | null}
|
|
63
|
+
*/
|
|
64
|
+
export function publicAvailabilityStageOf(renderPath) {
|
|
65
|
+
const match = PUBLIC_PATH.exec(renderPath);
|
|
66
|
+
return match ? /** @type {PublicAvailabilityStage} */ (match[1]) : null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** @param {string} tenantId @param {PublicAvailabilityStage} stage */
|
|
70
|
+
export function publicAvailabilityObjectKey(tenantId, stage) {
|
|
71
|
+
if (typeof tenantId !== "string" || !TENANT_ID.test(tenantId)) throw new Error("availability tenant id is malformed");
|
|
72
|
+
if (!isPublicAvailabilityStage(stage)) throw new Error("unknown availability stage");
|
|
73
|
+
return `availability/v1/${tenantId}/${stage}.json`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The tenant and stage an R2 object key names, or null for any other key.
|
|
78
|
+
* @param {string} key
|
|
79
|
+
* @returns {{ tenantId: string, stage: PublicAvailabilityStage } | null}
|
|
80
|
+
*/
|
|
81
|
+
export function publicAvailabilityKeyParts(key) {
|
|
82
|
+
const match = typeof key === "string" ? OBJECT_KEY.exec(key) : null;
|
|
83
|
+
return match ? { tenantId: /** @type {string} */ (match[1]), stage: /** @type {PublicAvailabilityStage} */ (match[2]) } : null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** @param {unknown} sku @returns {sku is string} */
|
|
87
|
+
function validSku(sku) {
|
|
88
|
+
// eslint-disable-next-line no-control-regex
|
|
89
|
+
return typeof sku === "string" && sku.length > 0 && sku.length <= MAX_SKU_LENGTH && !/[\u0000-\u001f\u007f]/.test(sku);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Serialize the document for one stage from mirror balances (sku → {balance, asOf}). Deterministic:
|
|
94
|
+
* the same visible bands and the same freshness quantum give the same bytes.
|
|
95
|
+
* @param {Iterable<[string, { balance: number, asOf: string }]>} balances
|
|
96
|
+
* @param {{ stage: PublicAvailabilityStage, now: string | number }} input
|
|
97
|
+
* @returns {string}
|
|
98
|
+
*/
|
|
99
|
+
export function buildPublicAvailabilityDoc(balances, input) {
|
|
100
|
+
if (!isPublicAvailabilityStage(input.stage)) throw new Error("unknown availability stage");
|
|
101
|
+
const nowMs = typeof input.now === "number" ? input.now : Date.parse(input.now);
|
|
102
|
+
if (!Number.isFinite(nowMs)) throw new Error("availability clock is malformed");
|
|
103
|
+
/** @type {Array<[string, number]>} */
|
|
104
|
+
const bands = [];
|
|
105
|
+
let oldestFresh = Infinity;
|
|
106
|
+
for (const [sku, reading] of balances) {
|
|
107
|
+
if (!validSku(sku) || !reading || !Number.isSafeInteger(reading.balance)) continue;
|
|
108
|
+
if (reading.balance <= 0) {
|
|
109
|
+
bands.push([sku, 0]);
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
const asOf = Date.parse(reading.asOf);
|
|
113
|
+
const age = nowMs - asOf;
|
|
114
|
+
if (!Number.isFinite(age) || age < 0 || age > PUBLIC_AVAILABILITY_FRESH_MS) continue;
|
|
115
|
+
bands.push([sku, Math.min(reading.balance, PUBLIC_AVAILABILITY_CAP)]);
|
|
116
|
+
oldestFresh = Math.min(oldestFresh, asOf);
|
|
117
|
+
}
|
|
118
|
+
bands.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
|
|
119
|
+
if (bands.length > PUBLIC_AVAILABILITY_MAX_SKUS) throw new Error("availability document exceeds its sku bound");
|
|
120
|
+
/** @type {Record<string, number>} */
|
|
121
|
+
const skus = Object.create(null);
|
|
122
|
+
for (const [sku, band] of bands) skus[sku] = band;
|
|
123
|
+
const freshUntil = Number.isFinite(oldestFresh)
|
|
124
|
+
? new Date(Math.floor((oldestFresh + PUBLIC_AVAILABILITY_FRESH_MS) / PUBLIC_AVAILABILITY_FRESH_QUANTUM_MS) *
|
|
125
|
+
PUBLIC_AVAILABILITY_FRESH_QUANTUM_MS).toISOString()
|
|
126
|
+
: null;
|
|
127
|
+
return JSON.stringify({ v: PUBLIC_AVAILABILITY_VERSION, stage: input.stage, freshUntil, skus });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* @typedef {{ stage: PublicAvailabilityStage, freshUntil: number | null, skus: Map<string, number> }} PublicAvailabilityDoc
|
|
132
|
+
*/
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Strictly parse a document. Anything malformed, oversized, of another version, or of a stage other
|
|
136
|
+
* than `expectedStage` is null — a reader then keeps the page's baked stamp.
|
|
137
|
+
* @param {string | null | undefined} raw
|
|
138
|
+
* @param {PublicAvailabilityStage} [expectedStage]
|
|
139
|
+
* @returns {PublicAvailabilityDoc | null}
|
|
140
|
+
*/
|
|
141
|
+
export function parsePublicAvailabilityDoc(raw, expectedStage) {
|
|
142
|
+
if (typeof raw !== "string" || raw === "" || raw.length > PUBLIC_AVAILABILITY_MAX_BYTES) return null;
|
|
143
|
+
/** @type {unknown} */
|
|
144
|
+
let parsed;
|
|
145
|
+
try {
|
|
146
|
+
parsed = JSON.parse(raw);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (error instanceof SyntaxError) return null;
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
152
|
+
const body = /** @type {Record<string, unknown>} */ (parsed);
|
|
153
|
+
if (Object.keys(body).sort().join(",") !== "freshUntil,skus,stage,v") return null;
|
|
154
|
+
if (body.v !== PUBLIC_AVAILABILITY_VERSION || !isPublicAvailabilityStage(body.stage)) return null;
|
|
155
|
+
if (expectedStage !== undefined && body.stage !== expectedStage) return null;
|
|
156
|
+
/** @type {number | null} */
|
|
157
|
+
let freshUntil = null;
|
|
158
|
+
if (body.freshUntil !== null) {
|
|
159
|
+
if (typeof body.freshUntil !== "string" || !ISO_INSTANT.test(body.freshUntil)) return null;
|
|
160
|
+
freshUntil = Date.parse(body.freshUntil);
|
|
161
|
+
if (!Number.isFinite(freshUntil) || new Date(freshUntil).toISOString() !== body.freshUntil) return null;
|
|
162
|
+
}
|
|
163
|
+
const rawSkus = body.skus;
|
|
164
|
+
if (!rawSkus || typeof rawSkus !== "object" || Array.isArray(rawSkus)) return null;
|
|
165
|
+
const entries = Object.entries(rawSkus);
|
|
166
|
+
if (entries.length > PUBLIC_AVAILABILITY_MAX_SKUS) return null;
|
|
167
|
+
/** @type {Map<string, number>} */
|
|
168
|
+
const skus = new Map();
|
|
169
|
+
for (const [sku, band] of entries) {
|
|
170
|
+
if (!validSku(sku) || typeof band !== "number" || !Number.isSafeInteger(band) ||
|
|
171
|
+
band < 0 || band > PUBLIC_AVAILABILITY_CAP) return null;
|
|
172
|
+
if (band > 0 && freshUntil === null) return null;
|
|
173
|
+
skus.set(sku, band);
|
|
174
|
+
}
|
|
175
|
+
return { stage: body.stage, freshUntil, skus };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* What the document says about one sku at `nowMs`: sold out, a positive band while the document is
|
|
180
|
+
* fresh, or null (absent, untracked, or a positive band past `freshUntil`) — keep the baked stamp.
|
|
181
|
+
* @param {PublicAvailabilityDoc} doc
|
|
182
|
+
* @param {string | null | undefined} sku
|
|
183
|
+
* @param {number} nowMs
|
|
184
|
+
* @returns {{ available: boolean, quantity: number } | null}
|
|
185
|
+
*/
|
|
186
|
+
export function publicAvailabilityInventory(doc, sku, nowMs) {
|
|
187
|
+
if (!sku) return null;
|
|
188
|
+
const band = doc.skus.get(sku);
|
|
189
|
+
if (band === undefined) return null;
|
|
190
|
+
if (band === 0) return { available: false, quantity: 0 };
|
|
191
|
+
if (doc.freshUntil === null || !(nowMs < doc.freshUntil)) return null;
|
|
192
|
+
return { available: true, quantity: band };
|
|
193
|
+
}
|