@gradial/aci 0.1.48 → 0.1.51-ssr.2

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.
Files changed (109) hide show
  1. package/README.md +13 -20
  2. package/dist/astro/assets.d.ts +6 -6
  3. package/dist/astro/assets.js +6 -6
  4. package/dist/astro/index.d.ts +0 -2
  5. package/dist/astro/index.js +0 -4
  6. package/dist/cli/emit-error-pages.mjs +0 -1
  7. package/dist/cli/verify-next-cdn-routes.mjs +3 -4
  8. package/dist/collect/aci.js +1 -1
  9. package/dist/collect/aci.js.sha256 +1 -1
  10. package/dist/collect/webvitals.d.ts +0 -3
  11. package/dist/collect/webvitals.js +11 -21
  12. package/dist/content/cache.d.ts +1 -9
  13. package/dist/content/cache.js +2 -37
  14. package/dist/content/error-pages.d.ts +1 -2
  15. package/dist/content/index.d.ts +0 -1
  16. package/dist/content/index.js +0 -1
  17. package/dist/index.d.ts +0 -1
  18. package/dist/internal/domain/edge/identity.d.ts +14 -0
  19. package/dist/internal/domain/edge/identity.js +214 -0
  20. package/dist/internal/domain/edge/index.d.ts +4 -0
  21. package/dist/internal/domain/edge/index.js +6 -0
  22. package/dist/internal/domain/edge/personalization-core.d.ts +24 -0
  23. package/dist/{edge → internal/domain/edge}/personalization-core.js +165 -64
  24. package/dist/internal/domain/edge/record/codec.d.ts +71 -0
  25. package/dist/internal/domain/edge/record/codec.js +401 -0
  26. package/dist/internal/domain/edge/resolve.d.ts +2 -0
  27. package/dist/internal/domain/edge/resolve.js +76 -0
  28. package/dist/{next/personalization-host.d.ts → internal/domain/edge/types.d.ts} +110 -61
  29. package/dist/internal/domain/edge/types.js +7 -0
  30. package/dist/internal/platform/collectionstore/errors.d.ts +5 -0
  31. package/dist/internal/platform/collectionstore/errors.js +7 -0
  32. package/dist/next/config.d.ts +0 -8
  33. package/dist/next/config.js +3 -78
  34. package/dist/next/error-pages.d.ts +2 -3
  35. package/dist/next/error-pages.js +5 -5
  36. package/dist/next/error-seat.d.ts +2 -3
  37. package/dist/next/index.d.ts +2 -2
  38. package/dist/next/index.js +1 -2
  39. package/dist/next/page.d.ts +3 -13
  40. package/dist/next/page.js +39 -51
  41. package/dist/next/server.d.ts +12 -32
  42. package/dist/next/server.js +66 -295
  43. package/dist/providers/object.d.ts +24 -0
  44. package/dist/providers/object.js +105 -0
  45. package/dist/providers/vercel-object-reader.d.ts +20 -0
  46. package/dist/providers/vercel-object-reader.js +45 -0
  47. package/dist/testing/conformance/checks.d.ts +1 -1
  48. package/dist/testing/conformance/checks.js +14 -144
  49. package/dist/testing/conformance/index.d.ts +1 -1
  50. package/dist/testing/conformance/index.js +1 -1
  51. package/dist/testing/conformance/preset.js +1 -1
  52. package/dist/testing/conformance/types.d.ts +1 -1
  53. package/dist/types/config.d.ts +0 -4
  54. package/dist/types/index.d.ts +0 -2
  55. package/dist/types/index.js +0 -2
  56. package/dist/types/page.d.ts +0 -10
  57. package/package.json +11 -35
  58. package/src/cli/emit-error-pages.mjs +0 -1
  59. package/src/cli/verify-next-cdn-routes.mjs +8 -11
  60. package/src/types/config.ts +0 -5
  61. package/src/types/index.ts +0 -2
  62. package/src/types/page.ts +0 -11
  63. package/templates/astro/template/.aci.yaml.tmpl +0 -11
  64. package/templates/common/.agents/skills/aci/SKILL.md +8 -9
  65. package/templates/common/.agents/skills/authoring/SKILL.md +3 -4
  66. package/templates/common/.agents/skills/authoring/references/block-registry.md +13 -36
  67. package/templates/common/.agents/skills/authoring/references/contracts.md +10 -17
  68. package/templates/common/.agents/skills/authoring/references/repo-structure.md +2 -2
  69. package/templates/common/.agents/skills/authoring/references/sdk-server-functions.md +45 -95
  70. package/templates/common/.agents/skills/migration/references/canon-migration.md +17 -37
  71. package/templates/nextjs/template/.aci.yaml.tmpl +0 -11
  72. package/templates/nextjs/template/README.md.tmpl +0 -1
  73. package/templates/nextjs/template/src/app/[[...slug]]/page.tsx +1 -1
  74. package/dist/content/assets.d.ts +0 -18
  75. package/dist/content/assets.js +0 -66
  76. package/dist/edge/personalization-core.d.ts +0 -11
  77. package/dist/internal/render-proof.d.ts +0 -1
  78. package/dist/internal/render-proof.js +0 -197
  79. package/dist/next/asset-route.d.ts +0 -10
  80. package/dist/next/asset-route.js +0 -45
  81. package/dist/next/collect-route.d.ts +0 -19
  82. package/dist/next/collect-route.js +0 -422
  83. package/dist/next/edge-config.d.ts +0 -1
  84. package/dist/next/edge-config.js +0 -92
  85. package/dist/next/envelope-digest.d.ts +0 -21
  86. package/dist/next/envelope-digest.js +0 -58
  87. package/dist/next/middleware.d.ts +0 -40
  88. package/dist/next/middleware.js +0 -462
  89. package/dist/next/personalization-host.js +0 -257
  90. package/dist/next/vercel-collect-sdk-route.d.ts +0 -27
  91. package/dist/next/vercel-collect-sdk-route.js +0 -181
  92. package/dist/next/vercel-edge-projection-v1.d.ts +0 -24
  93. package/dist/next/vercel-edge-projection-v1.js +0 -880
  94. package/dist/next/vercel-personalization.d.ts +0 -4
  95. package/dist/next/vercel-personalization.js +0 -4
  96. package/dist/next/vercel-s3-personalization.d.ts +0 -79
  97. package/dist/next/vercel-s3-personalization.js +0 -570
  98. package/dist/providers/s3.d.ts +0 -47
  99. package/dist/providers/s3.js +0 -434
  100. package/dist/types/render-mode.d.ts +0 -2
  101. package/dist/types/render-mode.js +0 -1
  102. package/dist/types/renderer.d.ts +0 -71
  103. package/dist/types/renderer.js +0 -1
  104. package/src/types/render-mode.ts +0 -10
  105. package/src/types/renderer.ts +0 -83
  106. package/templates/nextjs/starter-content/src/middleware.ts +0 -41
  107. package/templates/nextjs/template/src/app/gradial/assets/[...path]/route.ts +0 -1
  108. package/templates/nextjs/template/src/middleware.ts +0 -41
  109. package/templates/nextjs/template/src/middleware.ts.tmpl +0 -40
@@ -1,422 +0,0 @@
1
- import { MAX_BATCH_EVENTS } from '../collect/batcher.js';
2
- import { computeEnvelopeDigest } from './envelope-digest.js';
3
- import { consentSignals, IdentityErasureFencedError, identityHashHex, parseCookieHeader, verifyClaims, verifyIdentityCookie, } from './personalization-host.js';
4
- const MAX_COLLECT_BODY_BYTES = 64 * 1024;
5
- const DEFAULT_RETENTION_SECONDS = 13 * 30 * 24 * 60 * 60;
6
- const ULID = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i;
7
- const UTM_KEYS = ['source', 'medium', 'campaign', 'term', 'content', 'id'];
8
- const ENVELOPE_FIELDS = new Set(['envelopeId', 'events']);
9
- const EVENT_FIELDS = new Set([
10
- 'eventId',
11
- 'eventName',
12
- 'occurredAt',
13
- 'properties',
14
- 'url',
15
- 'referrer',
16
- 'title',
17
- 'path',
18
- 'utm',
19
- 'viewport',
20
- 'experiment',
21
- ]);
22
- function identityHashShard(identityHash) {
23
- const hash = identityHash.trim().toLowerCase();
24
- if (hash.length < 2)
25
- throw new Error('identity hash is too short');
26
- return hash.slice(0, 2);
27
- }
28
- export function createPersonalizationCollectRoute(config) {
29
- return async function collect(request) {
30
- if (request.method === 'OPTIONS')
31
- return new Response(null, { status: 204 });
32
- if (request.method !== 'POST')
33
- return new Response(null, { status: 405, headers: { allow: 'POST, OPTIONS' } });
34
- const bytes = new Uint8Array(await request.arrayBuffer());
35
- if (bytes.byteLength > MAX_COLLECT_BODY_BYTES)
36
- return new Response(null, { status: 413 });
37
- let envelopeId;
38
- let events;
39
- try {
40
- const envelope = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
41
- if (!envelope || typeof envelope !== 'object' || Array.isArray(envelope)) {
42
- throw new CollectValidationError('collect envelope must be an object');
43
- }
44
- for (const key of Object.keys(envelope)) {
45
- if (!ENVELOPE_FIELDS.has(key)) {
46
- throw new CollectValidationError(`field ${key} is not allowed on the collect envelope`);
47
- }
48
- }
49
- if (typeof envelope.envelopeId !== 'string' || !ULID.test(envelope.envelopeId.trim())) {
50
- throw new CollectValidationError('envelopeId must be a valid ULID');
51
- }
52
- envelopeId = envelope.envelopeId.trim().toUpperCase();
53
- if (!Array.isArray(envelope.events))
54
- throw new CollectValidationError('events must be an array');
55
- // The TS runtime has no cross-instance quota checker (Go's REQ-14/
56
- // REQ-20 guard); the 64KiB body cap plus this per-batch event cap and
57
- // the platform WAF are the abuse bounds. The cap is the client
58
- // batcher's MAX_BATCH_EVENTS — one constant, both sides of the wire.
59
- if (envelope.events.length > MAX_BATCH_EVENTS)
60
- throw new CollectValidationError('too many events in one batch');
61
- events = envelope.events;
62
- const eventIds = new Set();
63
- for (const event of events) {
64
- validateEvent(event);
65
- const eventId = event.eventId.trim().toUpperCase();
66
- if (eventId === envelopeId) {
67
- throw new CollectValidationError('envelopeId must be distinct from every eventId');
68
- }
69
- if (eventIds.has(eventId)) {
70
- throw new CollectValidationError('eventId must be unique within an envelope');
71
- }
72
- eventIds.add(eventId);
73
- }
74
- }
75
- catch (error) {
76
- return validationResponse(error);
77
- }
78
- const cookies = parseCookieHeader(request.headers.get('cookie'));
79
- const signals = consentSignals(request, cookies);
80
- const rawIdentity = await verifyIdentityCookie(cookies.get('aci_id') || '', config.identityKeys);
81
- const now = (config.now ?? (() => new Date()))();
82
- const secure = config.secureCookies ?? new URL(request.url).protocol === 'https:';
83
- const responseHeaders = new Headers({ 'cache-control': 'no-store', 'content-type': 'application/json' });
84
- try {
85
- // Withdrawal EVIDENCE (anonymous-experiments REQ-6): a signature-
86
- // verified aci_claims cookie proves prior identity-tier state exists
87
- // to suppress. Never-consented visitors present no verifiable claims
88
- // and stay measurement-only.
89
- const evidence = rawIdentity
90
- ? await verifyClaims(cookies.get('aci_claims') || '', config.claimsKeys || {}, now) !== null
91
- : false;
92
- const putSuppression = async (trigger) => {
93
- const hash = await identityHashHex('aci_id', rawIdentity);
94
- await config.store.putSuppression(`audience/suppression/${identityHashShard(hash)}/${config.siteId}/aci_id/${hash}/${trigger}.json`, { schemaVersion: 1, trigger, observedAt: now.toISOString() });
95
- };
96
- if (signals.privacyDenied) {
97
- if (rawIdentity && evidence) {
98
- await putSuppression('gpc');
99
- }
100
- if (cookies.has('aci_claims'))
101
- appendCookie(responseHeaders, expiredClaimsCookie(secure));
102
- return accepted(responseHeaders);
103
- }
104
- if (!rawIdentity)
105
- return accepted(responseHeaders);
106
- // Measurement tier (anonymous-experiments REQ-5): a verified aci_id
107
- // stores events even without a personalization grant — the snapshot
108
- // records what was (not) granted. An explicit denial with verified
109
- // evidence is an observed withdrawal; measurement storage continues.
110
- const personalization = signals.allowsIdentityTier;
111
- if (!personalization && signals.hasConsent && evidence) {
112
- await putSuppression('withdrawal');
113
- }
114
- const identityHash = await identityHashHex('aci_id', rawIdentity);
115
- const collectedAt = now.toISOString();
116
- const expiresAt = new Date(now.getTime() +
117
- (config.retentionSeconds ?? DEFAULT_RETENTION_SECONDS) * 1000).toISOString();
118
- const consent = signals.snapshot
119
- ? {
120
- v: signals.snapshot.version,
121
- p: signals.snapshot.purposes,
122
- ...(signals.snapshot.grantedAt ? { t: signals.snapshot.grantedAt } : {}),
123
- ...(signals.snapshot.source ? { src: signals.snapshot.source } : {}),
124
- }
125
- : { v: 0, p: [] };
126
- const records = events.map((event) => {
127
- const normalized = normalizeEvent(event, now);
128
- return {
129
- schemaVersion: 2,
130
- eventId: normalized.eventId,
131
- eventName: normalized.eventName,
132
- eventCategory: normalized.eventCategory,
133
- siteId: config.siteId,
134
- identity: { namespace: 'aci_id', hash: identityHash },
135
- // Go decodes `t` as time.Time and CANNOT parse an empty string —
136
- // an empty-t record permanently poisons that identity's
137
- // classification and DSAR reads. Omit t unless a real timestamp
138
- // was observed (legacy bare tokens have none).
139
- consent,
140
- ...(normalized.properties ? { properties: normalized.properties } : {}),
141
- page: normalized.page,
142
- ...(normalized.utm ? { utm: normalized.utm } : {}),
143
- ...(normalized.viewport ? { viewport: normalized.viewport } : {}),
144
- ...(normalized.experiment ? { experiment: normalized.experiment } : {}),
145
- occurredAt: normalized.occurredAt,
146
- collectedAt,
147
- expiresAt,
148
- };
149
- });
150
- if (records.length > 0) {
151
- const key = `audience/first-party/${identityHashShard(identityHash)}/${config.siteId}/aci_id/${identityHash}/${envelopeId}.json`;
152
- const digest = await computeEnvelopeDigest({
153
- siteId: config.siteId,
154
- acceptedBody: bytes,
155
- identity: { namespace: 'aci_id', hash: identityHash },
156
- consent: {
157
- version: signals.snapshot?.version ?? 0,
158
- purposes: signals.snapshot?.purposes ?? [],
159
- grantedAt: signals.snapshot?.grantedAt,
160
- source: signals.snapshot?.source,
161
- },
162
- });
163
- try {
164
- await config.store.appendEnvelope({
165
- key,
166
- envelopeId,
167
- siteId: config.siteId,
168
- identityNamespace: 'aci_id',
169
- identityHash,
170
- records,
171
- digest,
172
- });
173
- }
174
- catch (error) {
175
- if (error instanceof IdentityErasureFencedError) {
176
- if (cookies.has('aci_claims'))
177
- appendCookie(responseHeaders, expiredClaimsCookie(secure));
178
- return accepted(responseHeaders);
179
- }
180
- throw error;
181
- }
182
- }
183
- if (personalization) {
184
- const claims = await config.store.readClaims(config.siteId, 'aci_id', identityHash);
185
- if (claims)
186
- appendCookie(responseHeaders, claimsCookie(claims, secure));
187
- else if (cookies.has('aci_claims'))
188
- appendCookie(responseHeaders, expiredClaimsCookie(secure));
189
- }
190
- else if (cookies.has('aci_claims')) {
191
- // Claims are personalization; a non-granting touch expires them.
192
- appendCookie(responseHeaders, expiredClaimsCookie(secure));
193
- }
194
- return accepted(responseHeaders);
195
- }
196
- catch {
197
- return Response.json({ error: 'internal error', status: 500 }, { status: 500, headers: { 'cache-control': 'no-store' } });
198
- }
199
- };
200
- }
201
- function validateEvent(value) {
202
- if (!value || typeof value !== 'object' || Array.isArray(value))
203
- throw new CollectValidationError('event must be an object');
204
- for (const key of Object.keys(value)) {
205
- if (!EVENT_FIELDS.has(key))
206
- throw new CollectValidationError(`field ${key} is not allowed on the public collect route`);
207
- }
208
- if (typeof value.eventId !== 'string' || !ULID.test(value.eventId.trim()))
209
- throw new CollectValidationError('eventId must be a valid ULID');
210
- if (typeof value.eventName !== 'string')
211
- throw new CollectValidationError('event name is required');
212
- normalizeEventName(value.eventName);
213
- for (const field of ['url', 'referrer', 'title', 'path']) {
214
- if (value[field] !== undefined && typeof value[field] !== 'string')
215
- throw new CollectValidationError(`${field} must be a string`);
216
- }
217
- if (value.properties !== undefined && (!value.properties || typeof value.properties !== 'object' || Array.isArray(value.properties))) {
218
- throw new CollectValidationError('properties must be an object');
219
- }
220
- if (value.properties !== undefined)
221
- sanitizeProperties(value.properties, 'properties', 0);
222
- if (value.occurredAt !== undefined && (typeof value.occurredAt !== 'string' || Number.isNaN(Date.parse(value.occurredAt)))) {
223
- throw new CollectValidationError('occurredAt must be an RFC3339 timestamp');
224
- }
225
- if (value.utm !== undefined && (!value.utm || typeof value.utm !== 'object' || Array.isArray(value.utm))) {
226
- throw new CollectValidationError('utm must be an object');
227
- }
228
- normalizeViewport(value.viewport);
229
- normalizeExperiment(value.experiment);
230
- }
231
- function normalizeEvent(event, now) {
232
- const [eventName, eventCategory] = normalizeEventName(String(event.eventName));
233
- const rawURL = typeof event.url === 'string' ? event.url.trim() : '';
234
- const pageURL = sanitizeURL(rawURL, 'url');
235
- const referrer = sanitizeURL(typeof event.referrer === 'string' ? event.referrer.trim() : '', 'referrer');
236
- const parsedURL = rawURL ? new URL(rawURL, 'https://aci.invalid') : null;
237
- let path = typeof event.path === 'string' ? event.path.trim() : parsedURL?.pathname || '';
238
- if (path && !path.startsWith('/'))
239
- path = `/${path}`;
240
- const utm = normalizeUTM(event.utm, parsedURL);
241
- const occurredAt = typeof event.occurredAt === 'string' && !Number.isNaN(Date.parse(event.occurredAt))
242
- ? new Date(event.occurredAt).toISOString()
243
- : now.toISOString();
244
- return {
245
- eventId: String(event.eventId).trim().toUpperCase(),
246
- eventName,
247
- eventCategory,
248
- occurredAt,
249
- properties: event.properties === undefined ? undefined : sanitizeProperties(event.properties, 'properties', 0),
250
- page: {
251
- ...(pageURL ? { url: pageURL } : {}),
252
- ...(referrer ? { referrer } : {}),
253
- ...(typeof event.title === 'string' && event.title.trim() ? { title: event.title.trim() } : {}),
254
- ...(path ? { path } : {}),
255
- },
256
- utm,
257
- viewport: normalizeViewport(event.viewport),
258
- experiment: normalizeExperiment(event.experiment),
259
- };
260
- }
261
- function normalizeEventName(value) {
262
- const name = value.trim().toLowerCase();
263
- if (!name || name.length > 128 || /[\s/\\]/.test(name))
264
- throw new CollectValidationError('event name must be dot-delimited');
265
- const rum = new Set(['rum.page_view', 'rum.link_click', 'rum.variation_view', 'rum.web_vital']);
266
- const experiment = new Set(['experiment.exposure', 'experiment.conversion', 'experiment.engagement']);
267
- if (rum.has(name))
268
- return [name, 'rum'];
269
- if (experiment.has(name))
270
- return [name, 'experiment'];
271
- if (name.startsWith('custom.') && name.length > 'custom.'.length)
272
- return [name, 'custom'];
273
- throw new CollectValidationError('event name must be one of the supported rum.* or experiment.* events, or use the custom.* namespace');
274
- }
275
- function sanitizeURL(value, field) {
276
- if (!value)
277
- return '';
278
- if (value.length > 2048)
279
- throw new CollectValidationError(`${field} is too long`);
280
- let parsed;
281
- try {
282
- parsed = new URL(value, 'https://aci.invalid');
283
- }
284
- catch {
285
- throw new CollectValidationError(`${field} is invalid`);
286
- }
287
- if (!['http:', 'https:'].includes(parsed.protocol))
288
- throw new CollectValidationError(`${field} scheme is not allowed`);
289
- parsed.search = '';
290
- parsed.hash = '';
291
- if (parsed.origin === 'https://aci.invalid')
292
- return parsed.pathname;
293
- return parsed.toString().replace(/\/$/, parsed.pathname === '/' ? '/' : '');
294
- }
295
- function normalizeUTM(value, url) {
296
- const source = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
297
- const out = {};
298
- for (const key of UTM_KEYS) {
299
- const raw = source[key] ?? source[`utm_${key}`] ?? url?.searchParams.get(`utm_${key}`);
300
- if (typeof raw === 'string' && raw.trim())
301
- out[key] = raw.trim();
302
- }
303
- return Object.keys(out).length > 0 ? out : undefined;
304
- }
305
- function sanitizeProperties(value, field, depth) {
306
- if (depth > 4)
307
- throw new CollectValidationError(`${field} is nested too deeply`);
308
- if (value === null || typeof value === 'boolean' || typeof value === 'number')
309
- return value;
310
- if (typeof value === 'string')
311
- return sanitizeString(value, field, 2048);
312
- if (Array.isArray(value)) {
313
- if (value.length > 32)
314
- throw new CollectValidationError(`${field} has too many values`);
315
- return value.map((item, index) => sanitizeProperties(item, `${field}[${index}]`, depth + 1));
316
- }
317
- if (typeof value !== 'object')
318
- throw new CollectValidationError(`${field} has unsupported value type`);
319
- const entries = Object.entries(value);
320
- if (entries.length > 64)
321
- throw new CollectValidationError(`${field} has too many keys`);
322
- const sanitized = {};
323
- for (const [rawKey, item] of entries) {
324
- const key = sanitizeString(rawKey, `${field} key`, 256);
325
- if (!key)
326
- throw new CollectValidationError(`${field} contains an empty key`);
327
- if (secretLikeKey(key))
328
- throw new CollectValidationError(`${field} contains a sensitive key`);
329
- sanitized[key] = sanitizeProperties(item, `${field}.${key}`, depth + 1);
330
- }
331
- return sanitized;
332
- }
333
- function secretLikeKey(key) {
334
- const normalized = key.toLowerCase().replace(/[-. ]/g, '_');
335
- const compact = normalized.replace(/_/g, '');
336
- const normalizedMarkers = [
337
- 'authorization', 'access_token', 'refresh_token', 'id_token', 'api_key',
338
- 'private_key', 'secret', 'password', 'passwd', 'credential', 'cookie', 'set_cookie',
339
- ];
340
- const compactMarkers = [
341
- 'authorization', 'accesstoken', 'refreshtoken', 'idtoken', 'apikey',
342
- 'privatekey', 'secret', 'password', 'passwd', 'credential', 'cookie', 'setcookie',
343
- ];
344
- return normalizedMarkers.some((marker) => normalized.includes(marker))
345
- || compactMarkers.some((marker) => compact.includes(marker));
346
- }
347
- function sanitizeString(value, field, limit) {
348
- const clean = value.trim();
349
- if (clean.length > limit)
350
- throw new CollectValidationError(`${field} is too long`);
351
- if (/[\u0000-\u001F\u007F-\u009F]/u.test(clean))
352
- throw new CollectValidationError(`${field} contains control characters`);
353
- return clean;
354
- }
355
- function normalizeViewport(value) {
356
- if (value === undefined || value === null)
357
- return undefined;
358
- if (typeof value !== 'object' || Array.isArray(value))
359
- throw new CollectValidationError('viewport is invalid');
360
- const viewport = value;
361
- const width = viewport.width ?? 0;
362
- const height = viewport.height ?? 0;
363
- if (!Number.isInteger(width) || !Number.isInteger(height) || Number(width) < 0 || Number(height) < 0 || Number(width) > 20_000 || Number(height) > 20_000) {
364
- throw new CollectValidationError('viewport is invalid');
365
- }
366
- if (width === 0 && height === 0)
367
- return undefined;
368
- return { width: Number(width), height: Number(height) };
369
- }
370
- function normalizeExperiment(value) {
371
- if (value === undefined || value === null)
372
- return undefined;
373
- if (typeof value !== 'object' || Array.isArray(value))
374
- throw new CollectValidationError('experiment is invalid');
375
- const source = value;
376
- const experimentId = shortOptionalString(source.experimentId, 'experiment.experimentId');
377
- const armId = shortOptionalString(source.armId, 'experiment.armId');
378
- const allocationVersion = shortOptionalString(source.allocationVersion, 'experiment.allocationVersion');
379
- const goalId = shortOptionalString(source.goalId, 'experiment.goalId');
380
- const bucket = source.assignmentBucket;
381
- if (!experimentId && !armId && !allocationVersion && !goalId && bucket === undefined)
382
- return undefined;
383
- if (!experimentId)
384
- throw new CollectValidationError('experiment.experimentId is required when experiment context is present');
385
- if (!armId)
386
- throw new CollectValidationError('experiment.armId is required when experiment context is present');
387
- if (bucket !== undefined && (!Number.isInteger(bucket) || Number(bucket) < 0 || Number(bucket) > 9999)) {
388
- throw new CollectValidationError('experiment.assignmentBucket must be between 0 and 9999');
389
- }
390
- return {
391
- experimentId,
392
- armId,
393
- ...(allocationVersion ? { allocationVersion } : {}),
394
- ...(goalId ? { goalId } : {}),
395
- ...(bucket !== undefined ? { assignmentBucket: bucket } : {}),
396
- };
397
- }
398
- function shortOptionalString(value, field) {
399
- if (value === undefined || value === null)
400
- return '';
401
- if (typeof value !== 'string')
402
- throw new CollectValidationError(`${field} must be a string`);
403
- return sanitizeString(value, field, 128);
404
- }
405
- function accepted(headers) {
406
- return new Response('{"accepted":true}', { status: 202, headers });
407
- }
408
- function validationResponse(error) {
409
- const message = error instanceof CollectValidationError ? error.message : 'invalid JSON body';
410
- return Response.json({ error: message, status: 400 }, { status: 400, headers: { 'cache-control': 'no-store' } });
411
- }
412
- function claimsCookie(value, secure) {
413
- return `aci_claims=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${secure ? '; Secure' : ''}`;
414
- }
415
- function expiredClaimsCookie(secure) {
416
- return `aci_claims=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT${secure ? '; Secure' : ''}`;
417
- }
418
- function appendCookie(headers, cookie) {
419
- headers.append('set-cookie', cookie);
420
- }
421
- class CollectValidationError extends Error {
422
- }
@@ -1 +0,0 @@
1
- export declare function getUncachedEdgeConfigValue(edgeConfig: string, key: string): Promise<unknown>;
@@ -1,92 +0,0 @@
1
- export async function getUncachedEdgeConfigValue(edgeConfig, key) {
2
- const connection = parseEdgeConfigConnection(edgeConfig);
3
- if (!connection) {
4
- throw new Error('Invalid Edge Config connection string');
5
- }
6
- const headers = new Headers({
7
- authorization: `Bearer ${connection.token}`,
8
- 'x-edge-config-min-updated-at': `${Number.MAX_SAFE_INTEGER}`,
9
- });
10
- if (process.env.VERCEL_ENV) {
11
- headers.set('x-edge-config-vercel-env', process.env.VERCEL_ENV);
12
- }
13
- const url = `${connection.baseUrl}/item/${encodeURIComponent(key)}?version=${encodeURIComponent(connection.version)}`;
14
- const response = await fetch(url, {
15
- headers,
16
- cache: 'no-store',
17
- });
18
- if (response.ok) {
19
- return response.json();
20
- }
21
- if (response.status === 404 && response.headers.has('x-edge-config-digest')) {
22
- return undefined;
23
- }
24
- const body = await response.text().catch(() => '');
25
- throw new Error(`Edge Config read ${key} returned ${response.status}: ${body.slice(0, 500)}`);
26
- }
27
- function parseEdgeConfigConnection(value) {
28
- const text = value.trim();
29
- if (!text)
30
- return null;
31
- return parseEdgeConfigQueryConnection(text)
32
- || parseVercelEdgeConfigURL(text)
33
- || parseExternalEdgeConfigURL(text);
34
- }
35
- function parseEdgeConfigQueryConnection(value) {
36
- if (!value.startsWith('edge-config:'))
37
- return null;
38
- const params = new URLSearchParams(value.slice('edge-config:'.length));
39
- const id = params.get('id') || '';
40
- const token = params.get('token') || '';
41
- if (!id || !token)
42
- return null;
43
- return {
44
- baseUrl: `https://edge-config.vercel.com/${id}`,
45
- token,
46
- version: params.get('version') || '1',
47
- };
48
- }
49
- function parseVercelEdgeConfigURL(value) {
50
- let url;
51
- try {
52
- url = new URL(value);
53
- }
54
- catch {
55
- return null;
56
- }
57
- if (url.protocol !== 'https:' || url.host !== 'edge-config.vercel.com')
58
- return null;
59
- const id = url.pathname.split('/').filter(Boolean)[0] || '';
60
- const token = url.searchParams.get('token') || '';
61
- if (!id || !id.startsWith('ecfg') || !token)
62
- return null;
63
- return {
64
- baseUrl: `https://edge-config.vercel.com/${id}`,
65
- token,
66
- version: url.searchParams.get('version') || '1',
67
- };
68
- }
69
- function parseExternalEdgeConfigURL(value) {
70
- let url;
71
- try {
72
- url = new URL(value);
73
- }
74
- catch {
75
- return null;
76
- }
77
- let id = url.searchParams.get('id') || '';
78
- const token = url.searchParams.get('token') || '';
79
- const version = url.searchParams.get('version') || '1';
80
- if (!id || url.pathname.startsWith('/ecfg_')) {
81
- id = url.pathname.split('/').filter(Boolean)[0] || '';
82
- }
83
- if (!id || !token)
84
- return null;
85
- url.search = '';
86
- const base = url.toString().replace(/\/+$/, '');
87
- return {
88
- baseUrl: base,
89
- token,
90
- version,
91
- };
92
- }
@@ -1,21 +0,0 @@
1
- export interface EnvelopeDigestInput {
2
- siteId: string;
3
- acceptedBody: Uint8Array;
4
- identity: {
5
- namespace: string;
6
- hash: string;
7
- };
8
- consent: {
9
- version: number;
10
- purposes: readonly string[];
11
- grantedAt?: string;
12
- source?: string;
13
- };
14
- }
15
- /**
16
- * Computes the cross-runtime digest used to distinguish an identical
17
- * envelope retry from reuse of the same envelope ID with different accepted
18
- * inputs. Every field is framed with an unsigned 8-byte big-endian length so
19
- * concatenation cannot create ambiguous inputs.
20
- */
21
- export declare function computeEnvelopeDigest(input: EnvelopeDigestInput): Promise<string>;
@@ -1,58 +0,0 @@
1
- const ENVELOPE_DIGEST_ALGORITHM = 'aci-envelope-digest-v1';
2
- const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/;
3
- const encoder = new TextEncoder();
4
- const CONSENT_EDGE_WHITESPACE = /^[\t\n\v\f\r ]+|[\t\n\v\f\r ]+$/g;
5
- /**
6
- * Computes the cross-runtime digest used to distinguish an identical
7
- * envelope retry from reuse of the same envelope ID with different accepted
8
- * inputs. Every field is framed with an unsigned 8-byte big-endian length so
9
- * concatenation cannot create ambiguous inputs.
10
- */
11
- export async function computeEnvelopeDigest(input) {
12
- if (!Number.isInteger(input.consent.version)) {
13
- throw new Error('consent version must be an integer');
14
- }
15
- const purposes = input.consent.purposes
16
- .map((purpose) => trimConsentWhitespace(purpose).toLowerCase())
17
- .sort();
18
- const fields = [
19
- encoder.encode(ENVELOPE_DIGEST_ALGORITHM),
20
- encoder.encode(input.siteId.trim()),
21
- input.acceptedBody,
22
- encoder.encode(input.identity.namespace.trim()),
23
- encoder.encode(input.identity.hash.trim()),
24
- encoder.encode(String(input.consent.version)),
25
- encoder.encode(String(purposes.length)),
26
- ...purposes.map((purpose) => encoder.encode(purpose)),
27
- encoder.encode(canonicalGrantedAt(input.consent.grantedAt || '')),
28
- encoder.encode(trimConsentWhitespace(input.consent.source || '')),
29
- ];
30
- const byteLength = fields.reduce((total, field) => total + 8 + field.byteLength, 0);
31
- const framed = new Uint8Array(byteLength);
32
- const view = new DataView(framed.buffer);
33
- let offset = 0;
34
- for (const field of fields) {
35
- view.setBigUint64(offset, BigInt(field.byteLength), false);
36
- offset += 8;
37
- framed.set(field, offset);
38
- offset += field.byteLength;
39
- }
40
- const digest = await globalThis.crypto.subtle.digest('SHA-256', framed);
41
- return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
42
- }
43
- function canonicalGrantedAt(value) {
44
- const clean = trimConsentWhitespace(value);
45
- if (!clean)
46
- return '';
47
- const match = RFC3339.exec(clean);
48
- const epochMillis = Date.parse(clean);
49
- if (!match || Number.isNaN(epochMillis)) {
50
- throw new Error('consent grantedAt must be an RFC3339 timestamp');
51
- }
52
- const fraction = (match[7] || '').replace(/0+$/, '');
53
- const seconds = new Date(epochMillis).toISOString().slice(0, 19);
54
- return `${seconds}${fraction ? `.${fraction}` : ''}Z`;
55
- }
56
- function trimConsentWhitespace(value) {
57
- return value.replace(CONSENT_EDGE_WHITESPACE, '');
58
- }
@@ -1,40 +0,0 @@
1
- import { NextResponse, type NextRequest } from 'next/server.js';
2
- import { type PersonalizationHostConfig } from './personalization-host.js';
3
- export interface GradialMiddlewareConfig {
4
- siteId?: string;
5
- edgeConfig?: string;
6
- previewSignKey?: string;
7
- deploymentId?: string;
8
- deploymentProtectionBypass?: string;
9
- /** Site-scoped token shared only with the outer ACI framework proxy. */
10
- frameworkOriginAuthToken?: string;
11
- personalization?: Omit<PersonalizationHostConfig, 'siteId'> & {
12
- siteId?: string;
13
- };
14
- }
15
- export declare function createGradialMiddleware(config?: GradialMiddlewareConfig): (request: NextRequest) => Promise<Response>;
16
- /**
17
- * Any response that writes a cookie is per-visitor and must never enter a
18
- * shared cache (anonymous-experiments REQ-3(a)): a CDN-cached Set-Cookie
19
- * replays one visitor's identity/claims to everyone under that cache key.
20
- * Per-variant CACHING itself stays legitimate — the variant travels in the
21
- * cache-keyed query parameter, not in cookies.
22
- */
23
- export declare function enforceCookieCacheRule(response: NextResponse): void;
24
- export declare const aciMiddlewareMatcher: (string | {
25
- source: string;
26
- has: {
27
- type: string;
28
- key: string;
29
- }[];
30
- })[];
31
- export declare const config: {
32
- runtime: string;
33
- matcher: (string | {
34
- source: string;
35
- has: {
36
- type: string;
37
- key: string;
38
- }[];
39
- })[];
40
- };