@timber-js/app 0.2.0-alpha.128 → 0.2.0-alpha.129
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/dist/_chunks/{actions-DX2gkoOZ.js → actions-CdzSSeTh.js} +2 -2
- package/dist/_chunks/{actions-DX2gkoOZ.js.map → actions-CdzSSeTh.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-vdobDWwX.js → cli-schema-sync-CObqjGWF.js} +1 -1
- package/dist/_chunks/{cli-schema-sync-DFHBj6yZ.js → cli-schema-sync-q-Ce6-iG.js} +2 -2
- package/dist/_chunks/{cli-schema-sync-DFHBj6yZ.js.map → cli-schema-sync-q-Ce6-iG.js.map} +1 -1
- package/dist/_chunks/{logger-DDmK5skc.js → logger-CMd9P1xQ.js} +2 -2
- package/dist/_chunks/{logger-DDmK5skc.js.map → logger-CMd9P1xQ.js.map} +1 -1
- package/dist/_chunks/{tracing-DvKLzCFa.js → tracing-DP5djRq5.js} +43 -14
- package/dist/_chunks/tracing-DP5djRq5.js.map +1 -0
- package/dist/_chunks/{walkers-E5ss0qES.js → walkers-BbEu2_Pp.js} +2 -2
- package/dist/_chunks/{walkers-E5ss0qES.js.map → walkers-BbEu2_Pp.js.map} +1 -1
- package/dist/_chunks/{warnings-B30wpfaS.js → warnings-CAzunaGo.js} +2 -2
- package/dist/_chunks/{warnings-B30wpfaS.js.map → warnings-CAzunaGo.js.map} +1 -1
- package/dist/cache/index.js +2 -2
- package/dist/cli.js +1 -1
- package/dist/index.js +19 -6
- package/dist/index.js.map +1 -1
- package/dist/plugins/routing.d.ts.map +1 -1
- package/dist/routing/index.js +2 -2
- package/dist/server/als-registry.d.ts +17 -6
- package/dist/server/als-registry.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/internal.js +4 -4
- package/package.json +1 -1
- package/src/plugins/routing.ts +15 -2
- package/src/server/als-registry.ts +53 -13
- package/dist/_chunks/tracing-DvKLzCFa.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routing.d.ts","sourceRoot":"","sources":["../../src/plugins/routing.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAiB,MAAM,MAAM,CAAC;AAoBlD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"routing.d.ts","sourceRoot":"","sources":["../../src/plugins/routing.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAiB,MAAM,MAAM,CAAC;AAoBlD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAwG1D,wBAAgB,aAAa,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CAuNxD"}
|
package/dist/routing/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { i as INTERCEPTION_MARKERS, n as classifyUrlSegment, r as DEFAULT_PAGE_EXTENSIONS, t as classifySegment } from "../_chunks/segment-classify-BjfuctV2.js";
|
|
2
|
-
import { m as scanRoutes } from "../_chunks/cli-schema-sync-
|
|
3
|
-
import { a as generateRouteMap, i as collectInterceptionRewrites, n as collectDynamicSegmentsFromTree, r as validateSchemaAgainstRoutes, t as collectLeafRoutes } from "../_chunks/walkers-
|
|
2
|
+
import { m as scanRoutes } from "../_chunks/cli-schema-sync-q-Ce6-iG.js";
|
|
3
|
+
import { a as generateRouteMap, i as collectInterceptionRewrites, n as collectDynamicSegmentsFromTree, r as validateSchemaAgainstRoutes, t as collectLeafRoutes } from "../_chunks/walkers-BbEu2_Pp.js";
|
|
4
4
|
export { DEFAULT_PAGE_EXTENSIONS, INTERCEPTION_MARKERS, classifySegment, classifyUrlSegment, collectDynamicSegmentsFromTree, collectInterceptionRewrites, collectLeafRoutes, generateRouteMap, scanRoutes, validateSchemaAgainstRoutes };
|
|
@@ -6,18 +6,29 @@
|
|
|
6
6
|
* this registry and re-export public accessor functions.
|
|
7
7
|
*
|
|
8
8
|
* Why: ALS instances require singleton semantics — if two copies of the
|
|
9
|
-
* same ALS exist (one from a relative import, one from a barrel import
|
|
10
|
-
*
|
|
11
|
-
*
|
|
9
|
+
* same ALS exist (one from a relative import, one from a barrel import,
|
|
10
|
+
* or the same file re-evaluated by Vite after an HMR invalidation), one
|
|
11
|
+
* module writes to its copy and another reads from an empty copy.
|
|
12
|
+
* Centralizing ALS creation in a single module + anchoring each instance
|
|
13
|
+
* on `globalThis` under a `Symbol.for(...)` key eliminates this class of
|
|
14
|
+
* bug, including the Vite-dev case where module instance split would
|
|
15
|
+
* otherwise hand two copies of this file out of a single evaluation cycle.
|
|
12
16
|
*
|
|
13
|
-
* The `timber-shims` plugin
|
|
14
|
-
*
|
|
17
|
+
* The `timber-shims` plugin remaps `@timber-js/app/server` to src/ in
|
|
18
|
+
* RSC and SSR environments so import-specifier paths converge here, and
|
|
19
|
+
* the `globalThis[SYMBOL_FOR]` anchor below closes the remaining gap: any
|
|
20
|
+
* second evaluation of this module picks up the ALS the first evaluation
|
|
21
|
+
* already stored rather than instantiating a fresh one. Same pattern the
|
|
22
|
+
* Cloudflare bindings ALS uses in `adapters/cloudflare.ts`.
|
|
15
23
|
*
|
|
16
24
|
* DO NOT create ALS instances outside this file. If you need a new ALS,
|
|
17
25
|
* add it here and import from `./als-registry.js` in the consuming module.
|
|
26
|
+
* Inside this file, always route through `getOrCreateAls(symbol)` — a raw
|
|
27
|
+
* `new AsyncLocalStorage()` reintroduces the instance-split hazard.
|
|
18
28
|
*
|
|
19
29
|
* See design/18-build-system.md §"Module Singleton Strategy" and
|
|
20
|
-
* §"Singleton State Registry".
|
|
30
|
+
* §"Singleton State Registry". Regression test:
|
|
31
|
+
* `tests/als-registry-singleton.test.ts`.
|
|
21
32
|
*/
|
|
22
33
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
23
34
|
import type { DebugComponentEntry } from './rsc-entry/helpers.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"als-registry.d.ts","sourceRoot":"","sources":["../../src/server/als-registry.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"als-registry.d.ts","sourceRoot":"","sources":["../../src/server/als-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AA2BlE,2DAA2D;AAC3D,eAAO,MAAM,iBAAiB,wCAE7B,CAAC;AAEF,MAAM,WAAW,mBAAmB;IAClC,iDAAiD;IACjD,OAAO,EAAE,OAAO,CAAC;IACjB,0EAA0E;IAC1E,YAAY,EAAE,MAAM,CAAC;IACrB,8EAA8E;IAC9E,aAAa,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACpC,uEAAuE;IACvE,eAAe,EAAE,OAAO,CAAC;IACzB;;;;OAIG;IACH,YAAY,EAAE,eAAe,CAAC;IAC9B;;;OAGG;IACH,YAAY,EAAE,MAAM,CAAC;IACrB;;;;;;;OAOG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;IAClD;;;;;;OAMG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;;;;;;;OAUG;IACH,aAAa,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC,CAAC;IAC/D,wFAAwF;IACxF,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IACpC,4DAA4D;IAC5D,OAAO,EAAE,OAAO,CAAC;IACjB,0DAA0D;IAC1D,cAAc,EAAE,OAAO,CAAC;IACxB;;;;;OAKG;IACH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Als, t as addSpanEvent, v as isDebug, y as isDevMode } from "../_chunks/tracing-
|
|
1
|
+
import { a as getSpanId, d as withSpan, o as getTraceId, p as formFlashAls, t as addSpanEvent, v as isDebug, y as isDevMode } from "../_chunks/tracing-DP5djRq5.js";
|
|
2
2
|
import { t as formatSize } from "../_chunks/format-BjN9HLu9.js";
|
|
3
|
-
import { D as getCookieJar, a as revalidateTag, b as getSegmentParams, c as DenySignal, f as deny, h as waitUntil, i as revalidatePath, l as RedirectSignal, m as redirectExternal, o as coerce, p as redirect, s as parseFormData, u as RedirectType, v as getHeaders } from "../_chunks/actions-
|
|
3
|
+
import { D as getCookieJar, a as revalidateTag, b as getSegmentParams, c as DenySignal, f as deny, h as waitUntil, i as revalidatePath, l as RedirectSignal, m as redirectExternal, o as coerce, p as redirect, s as parseFormData, u as RedirectType, v as getHeaders } from "../_chunks/actions-CdzSSeTh.js";
|
|
4
4
|
//#region src/server/sensitive-fields.ts
|
|
5
5
|
/**
|
|
6
6
|
* Sensitive field stripping — removes password/token/CVV-style fields
|
package/dist/server/internal.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { c as replaceTraceId, d as withSpan, f as earlyHintsSenderAls, g as timingAls, i as getOtelTraceId, l as runWithTraceId, m as requestContextAls, o as getTraceId, r as generateTraceId, u as setSpanAttribute, v as isDebug } from "../_chunks/tracing-
|
|
2
|
-
import { a as warnRedirectInSuspense, c as warnSuspenseWrappingChildren, i as warnRedirectInAccess, n as setViteServer, o as warnSlowSlotWithoutSuspense, r as warnDenyInSuspense, s as warnStaticRequestApi, t as WarningId } from "../_chunks/warnings-
|
|
1
|
+
import { c as replaceTraceId, d as withSpan, f as earlyHintsSenderAls, g as timingAls, i as getOtelTraceId, l as runWithTraceId, m as requestContextAls, o as getTraceId, r as generateTraceId, u as setSpanAttribute, v as isDebug } from "../_chunks/tracing-DP5djRq5.js";
|
|
2
|
+
import { a as warnRedirectInSuspense, c as warnSuspenseWrappingChildren, i as warnRedirectInAccess, n as setViteServer, o as warnSlowSlotWithoutSuspense, r as warnDenyInSuspense, s as warnStaticRequestApi, t as WarningId } from "../_chunks/warnings-CAzunaGo.js";
|
|
3
3
|
import { i as getMetadataRouteServePath, n as classifyMetadataRoute, r as getMetadataRouteAutoLink, t as METADATA_ROUTE_CONVENTIONS } from "../_chunks/metadata-routes-DESG8uk5.js";
|
|
4
4
|
import { n as classifyUrlSegment } from "../_chunks/segment-classify-BjfuctV2.js";
|
|
5
|
-
import { a as logProxyError, c as logRequestReceived, d as logSwrRefetchFailed, f as logWaitUntilRejected, h as swallow, i as logMiddlewareShortCircuit, l as logRouteError, m as setLogger, n as logCacheMiss, o as logRenderError, p as logWaitUntilUnsupported, r as logMiddlewareError, s as logRequestCompleted, t as getLogger, u as logSlowRequest } from "../_chunks/logger-
|
|
6
|
-
import { C as setMatchedSegmentPath, E as getCookie, O as getSetCookieHeaders, S as runWithRequestContext, T as setSegmentParams, _ as getHeader, b as getSegmentParams, c as DenySignal, d as RenderError, g as applyRequestHeaderOverlay, l as RedirectSignal, n as executeAction, o as coerce, r as isRscActionRequest, t as buildNoJsResponse, w as setMutableCookieContext, x as markResponseFlushed, y as getSearchParams } from "../_chunks/actions-
|
|
5
|
+
import { a as logProxyError, c as logRequestReceived, d as logSwrRefetchFailed, f as logWaitUntilRejected, h as swallow, i as logMiddlewareShortCircuit, l as logRouteError, m as setLogger, n as logCacheMiss, o as logRenderError, p as logWaitUntilUnsupported, r as logMiddlewareError, s as logRequestCompleted, t as getLogger, u as logSlowRequest } from "../_chunks/logger-CMd9P1xQ.js";
|
|
6
|
+
import { C as setMatchedSegmentPath, E as getCookie, O as getSetCookieHeaders, S as runWithRequestContext, T as setSegmentParams, _ as getHeader, b as getSegmentParams, c as DenySignal, d as RenderError, g as applyRequestHeaderOverlay, l as RedirectSignal, n as executeAction, o as coerce, r as isRscActionRequest, t as buildNoJsResponse, w as setMutableCookieContext, x as markResponseFlushed, y as getSearchParams } from "../_chunks/actions-CdzSSeTh.js";
|
|
7
7
|
import "../client/error-boundary.js";
|
|
8
8
|
import { n as toBracketKey } from "../_chunks/resolve-schema-DU2nbVOi.js";
|
|
9
9
|
import "../_chunks/segment-context-Bg0pFbLT.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@timber-js/app",
|
|
3
|
-
"version": "0.2.0-alpha.
|
|
3
|
+
"version": "0.2.0-alpha.129",
|
|
4
4
|
"description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare-workers",
|
package/src/plugins/routing.ts
CHANGED
|
@@ -84,12 +84,25 @@ const CODEGEN_OUTPUT = '.timber/timber-routes.d.ts';
|
|
|
84
84
|
* Uses a triple-slash reference so TypeScript auto-discovers the generated
|
|
85
85
|
* route map without the user needing to edit tsconfig.json — same pattern
|
|
86
86
|
* as Next.js's next-env.d.ts.
|
|
87
|
+
*
|
|
88
|
+
* Also references `vite/client` so side-effect imports like
|
|
89
|
+
* `import './globals.css'` type-check without ts(2882), and so
|
|
90
|
+
* `import.meta.env`, `import.meta.hot`, `import.meta.glob`, asset
|
|
91
|
+
* imports (`*.png`, `*.svg`, …), CSS modules, and `?url`/`?raw`/
|
|
92
|
+
* `?inline` query variants all resolve without the user editing
|
|
93
|
+
* tsconfig.json themselves. Next.js's next-env.d.ts plays the same
|
|
94
|
+
* role via `next/types/global`.
|
|
95
|
+
*
|
|
96
|
+
* `vite` is a peer dep of `@timber-js/app`, so the reference always
|
|
97
|
+
* resolves in a correctly-installed project.
|
|
87
98
|
*/
|
|
88
99
|
const TIMBER_ENV_DTS = [
|
|
89
100
|
'// This file is auto-generated by timber.js. Do not edit.',
|
|
90
|
-
'// It ensures TypeScript picks up the generated route types
|
|
91
|
-
'//
|
|
101
|
+
'// It ensures TypeScript picks up the generated route types and',
|
|
102
|
+
'// Vite-provided ambient types (CSS, assets, import.meta.env, HMR).',
|
|
103
|
+
'/* eslint-disable @typescript-eslint/triple-slash-reference */',
|
|
92
104
|
'/// <reference path=".timber/timber-routes.d.ts" />',
|
|
105
|
+
'/// <reference types="vite/client" />',
|
|
93
106
|
'',
|
|
94
107
|
].join('\n');
|
|
95
108
|
|
|
@@ -6,29 +6,63 @@
|
|
|
6
6
|
* this registry and re-export public accessor functions.
|
|
7
7
|
*
|
|
8
8
|
* Why: ALS instances require singleton semantics — if two copies of the
|
|
9
|
-
* same ALS exist (one from a relative import, one from a barrel import
|
|
10
|
-
*
|
|
11
|
-
*
|
|
9
|
+
* same ALS exist (one from a relative import, one from a barrel import,
|
|
10
|
+
* or the same file re-evaluated by Vite after an HMR invalidation), one
|
|
11
|
+
* module writes to its copy and another reads from an empty copy.
|
|
12
|
+
* Centralizing ALS creation in a single module + anchoring each instance
|
|
13
|
+
* on `globalThis` under a `Symbol.for(...)` key eliminates this class of
|
|
14
|
+
* bug, including the Vite-dev case where module instance split would
|
|
15
|
+
* otherwise hand two copies of this file out of a single evaluation cycle.
|
|
12
16
|
*
|
|
13
|
-
* The `timber-shims` plugin
|
|
14
|
-
*
|
|
17
|
+
* The `timber-shims` plugin remaps `@timber-js/app/server` to src/ in
|
|
18
|
+
* RSC and SSR environments so import-specifier paths converge here, and
|
|
19
|
+
* the `globalThis[SYMBOL_FOR]` anchor below closes the remaining gap: any
|
|
20
|
+
* second evaluation of this module picks up the ALS the first evaluation
|
|
21
|
+
* already stored rather than instantiating a fresh one. Same pattern the
|
|
22
|
+
* Cloudflare bindings ALS uses in `adapters/cloudflare.ts`.
|
|
15
23
|
*
|
|
16
24
|
* DO NOT create ALS instances outside this file. If you need a new ALS,
|
|
17
25
|
* add it here and import from `./als-registry.js` in the consuming module.
|
|
26
|
+
* Inside this file, always route through `getOrCreateAls(symbol)` — a raw
|
|
27
|
+
* `new AsyncLocalStorage()` reintroduces the instance-split hazard.
|
|
18
28
|
*
|
|
19
29
|
* See design/18-build-system.md §"Module Singleton Strategy" and
|
|
20
|
-
* §"Singleton State Registry".
|
|
30
|
+
* §"Singleton State Registry". Regression test:
|
|
31
|
+
* `tests/als-registry-singleton.test.ts`.
|
|
21
32
|
*/
|
|
22
33
|
|
|
23
34
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
24
35
|
import type { DebugComponentEntry } from './rsc-entry/helpers.js';
|
|
25
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Return a process-wide singleton `AsyncLocalStorage` keyed by `symbol`.
|
|
39
|
+
*
|
|
40
|
+
* `Symbol.for(...)` keys live in the cross-realm symbol registry, and
|
|
41
|
+
* `globalThis` is shared across every module evaluation inside the same
|
|
42
|
+
* Node.js process. Together they give a stable anchor that survives
|
|
43
|
+
* re-evaluation of this file — the second evaluation observes the
|
|
44
|
+
* `globalThis[symbol]` slot already populated by the first and hands
|
|
45
|
+
* back the identical ALS instance.
|
|
46
|
+
*/
|
|
47
|
+
function getOrCreateAls<T>(symbol: symbol): AsyncLocalStorage<T> {
|
|
48
|
+
const g = globalThis as unknown as Record<symbol, unknown>;
|
|
49
|
+
const existing = g[symbol];
|
|
50
|
+
if (existing instanceof AsyncLocalStorage) {
|
|
51
|
+
return existing as AsyncLocalStorage<T>;
|
|
52
|
+
}
|
|
53
|
+
const created = new AsyncLocalStorage<T>();
|
|
54
|
+
g[symbol] = created;
|
|
55
|
+
return created;
|
|
56
|
+
}
|
|
57
|
+
|
|
26
58
|
// ─── Request Context ──────────────────────────────────────────────────────
|
|
27
59
|
// Used by: request-context.ts (getHeaders(), getCookies(), getSearchParams())
|
|
28
60
|
// Design doc: design/04-authorization.md
|
|
29
61
|
|
|
30
62
|
/** @internal — import via request-context.ts public API */
|
|
31
|
-
export const requestContextAls =
|
|
63
|
+
export const requestContextAls = getOrCreateAls<RequestContextStore>(
|
|
64
|
+
Symbol.for('timber:request-context-als')
|
|
65
|
+
);
|
|
32
66
|
|
|
33
67
|
export interface RequestContextStore {
|
|
34
68
|
/** Incoming request headers (read-only view). */
|
|
@@ -119,7 +153,7 @@ export interface TraceStore {
|
|
|
119
153
|
}
|
|
120
154
|
|
|
121
155
|
/** @internal — import via tracing.ts public API */
|
|
122
|
-
export const traceAls =
|
|
156
|
+
export const traceAls = getOrCreateAls<TraceStore>(Symbol.for('timber:trace-als'));
|
|
123
157
|
|
|
124
158
|
// ─── Server-Timing ────────────────────────────────────────────────────────
|
|
125
159
|
// Used by: server-timing.ts (recordTiming(), withTiming())
|
|
@@ -130,7 +164,7 @@ export interface TimingStore {
|
|
|
130
164
|
}
|
|
131
165
|
|
|
132
166
|
/** @internal — import via server-timing.ts public API */
|
|
133
|
-
export const timingAls =
|
|
167
|
+
export const timingAls = getOrCreateAls<TimingStore>(Symbol.for('timber:timing-als'));
|
|
134
168
|
|
|
135
169
|
// ─── Revalidation ─────────────────────────────────────────────────────────
|
|
136
170
|
// Used by: actions.ts (revalidatePath(), revalidateTag())
|
|
@@ -144,14 +178,18 @@ export interface RevalidationState {
|
|
|
144
178
|
}
|
|
145
179
|
|
|
146
180
|
/** @internal — import via actions.ts public API */
|
|
147
|
-
export const revalidationAls =
|
|
181
|
+
export const revalidationAls = getOrCreateAls<RevalidationState>(
|
|
182
|
+
Symbol.for('timber:revalidation-als')
|
|
183
|
+
);
|
|
148
184
|
|
|
149
185
|
// ─── Form Flash ───────────────────────────────────────────────────────────
|
|
150
186
|
// Used by: form-flash.ts (getFormFlash())
|
|
151
187
|
// Design doc: design/08-forms-and-actions.md §"No-JS Error Round-Trip"
|
|
152
188
|
|
|
153
189
|
/** @internal — import via form-flash.ts public API */
|
|
154
|
-
export const formFlashAls =
|
|
190
|
+
export const formFlashAls = getOrCreateAls<import('./form-flash.js').FormFlashData>(
|
|
191
|
+
Symbol.for('timber:form-flash-als')
|
|
192
|
+
);
|
|
155
193
|
|
|
156
194
|
// ─── Early Hints Sender ──────────────────────────────────────────────────
|
|
157
195
|
// Used by: early-hints-sender.ts (sendEarlyHints103())
|
|
@@ -161,7 +199,9 @@ export const formFlashAls = new AsyncLocalStorage<import('./form-flash.js').Form
|
|
|
161
199
|
export type EarlyHintsSenderFn = (links: string[]) => void;
|
|
162
200
|
|
|
163
201
|
/** @internal — import via early-hints-sender.ts public API */
|
|
164
|
-
export const earlyHintsSenderAls =
|
|
202
|
+
export const earlyHintsSenderAls = getOrCreateAls<EarlyHintsSenderFn>(
|
|
203
|
+
Symbol.for('timber:early-hints-sender-als')
|
|
204
|
+
);
|
|
165
205
|
|
|
166
206
|
// ─── waitUntil Bridge ────────────────────────────────────────────────────
|
|
167
207
|
// Used by: waituntil-bridge.ts (waitUntil())
|
|
@@ -171,4 +211,4 @@ export const earlyHintsSenderAls = new AsyncLocalStorage<EarlyHintsSenderFn>();
|
|
|
171
211
|
export type WaitUntilFn = (promise: Promise<unknown>) => void;
|
|
172
212
|
|
|
173
213
|
/** @internal — import via waituntil-bridge.ts public API */
|
|
174
|
-
export const waitUntilAls =
|
|
214
|
+
export const waitUntilAls = getOrCreateAls<WaitUntilFn>(Symbol.for('timber:wait-until-als'));
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tracing-DvKLzCFa.js","names":[],"sources":["../../src/server/debug.ts","../../src/server/als-registry.ts","../../src/server/tracing.ts"],"sourcesContent":["/**\n * Runtime debug flag for timber.js.\n *\n * Two distinct functions for two distinct security levels:\n *\n * ## `isDebug()` — server-side logging only\n *\n * Returns true when timber's debug/warning messages should be written to\n * stderr / the server console. This NEVER affects what is sent to the\n * client (no error details, no timing headers, no stack traces).\n *\n * Active when any of:\n * - `NODE_ENV !== 'production'` (standard dev mode)\n * - `TIMBER_DEBUG` env var is set to a truthy value at runtime\n * - `timber.config.ts` has `debug: true`\n *\n * ## `isDevMode()` — client-visible dev behavior\n *\n * Returns true ONLY when `NODE_ENV !== 'production'`. This gates anything\n * that changes what clients can observe:\n * - Dev error pages with stack traces (fallback-error.ts)\n * - Detailed Server-Timing headers (pipeline.ts)\n * - Error messages in action INTERNAL_ERROR payloads (action-client.ts)\n * - Pipeline error handler wiring (Vite overlay)\n *\n * `isDevMode()` is statically replaced in production builds → the guarded\n * code is tree-shaken to zero bytes. TIMBER_DEBUG cannot enable it.\n *\n * Usage:\n * In Cloudflare Workers wrangler.toml:\n * [vars]\n * TIMBER_DEBUG = \"1\"\n *\n * In Node.js:\n * TIMBER_DEBUG=1 node server.js\n *\n * In timber.config.ts:\n * export default { debug: true }\n *\n * See design/13-security.md for the security taxonomy.\n * See design/18-build-system.md for build pipeline details.\n */\n\n// ─── Dev Mode (client-visible) ──────────────────────────────────────────────\n\n/**\n * Check if the application is running in development mode.\n *\n * This is the ONLY function that should gate client-visible dev behavior:\n * - Dev error pages with stack traces\n * - Server-Timing mode default (`'detailed'` in dev, `'total'` in prod)\n * - Error messages in action `INTERNAL_ERROR` payloads\n * - Pipeline error handler wiring (Vite overlay)\n *\n * Returns `process.env.NODE_ENV !== 'production'`, which is statically\n * replaced by the bundler in production builds. Code guarded by this\n * function is tree-shaken to zero bytes in production.\n *\n * TIMBER_DEBUG does NOT enable this — that would leak server internals\n * to clients. Use `isDebug()` for server-side-only logging.\n */\nexport function isDevMode(): boolean {\n return process.env.NODE_ENV !== 'production';\n}\n\n// ─── Debug Flag (server-side logging only) ──────────────────────────────────\n\n/**\n * Config-level debug override. Set via `setDebugFromConfig()` during\n * initialization when timber.config.ts has `debug: true`.\n */\nlet _configDebug = false;\n\n/**\n * Set the debug flag from timber.config.ts.\n * Called during handler initialization.\n */\nexport function setDebugFromConfig(debug: boolean): void {\n _configDebug = debug;\n}\n\n/**\n * Check if timber debug logging is active (server-side only).\n *\n * Returns true if ANY of these conditions hold:\n * - NODE_ENV is not 'production' (standard dev mode)\n * - TIMBER_DEBUG environment variable is set to a truthy value at runtime\n * - timber.config.ts has `debug: true`\n *\n * This function controls ONLY server-side logging — messages written to\n * stderr or the server console. It NEVER affects client-visible behavior\n * (error pages, response headers, action payloads). For client-visible\n * behavior, use `isDevMode()`.\n *\n * The TIMBER_DEBUG check is deliberately written as a dynamic property\n * access so bundlers cannot statically replace it.\n */\nexport function isDebug(): boolean {\n // Fast path: dev mode (statically replaced to `true` in dev, `false` in prod)\n if (process.env.NODE_ENV !== 'production') return true;\n\n // Config override\n if (_configDebug) return true;\n\n // Runtime env var check — uses dynamic access to prevent static replacement.\n // In production builds, process.env.NODE_ENV is statically replaced, but\n // TIMBER_DEBUG must survive as a runtime check. The dynamic key access\n // pattern ensures the bundler treats this as opaque.\n return _readTimberDebugEnv();\n}\n\n/**\n * Read TIMBER_DEBUG from the environment at runtime.\n *\n * Extracted to a separate function to:\n * 1. Prevent bundler inlining (cross-module function calls are not inlined)\n * 2. Handle platforms where `process` may not exist (Cloudflare Workers)\n * 3. Support globalThis.__TIMBER_DEBUG for programmatic control\n */\nfunction _readTimberDebugEnv(): boolean {\n // globalThis override — useful for programmatic control and testing\n if ((globalThis as Record<string, unknown>).__TIMBER_DEBUG) return true;\n\n // process.env — works in Node.js and platforms that polyfill process\n try {\n const key = 'TIMBER_DEBUG';\n const val =\n typeof process !== 'undefined' && process.env\n ? (process.env as Record<string, string | undefined>)[key]\n : undefined;\n if (val && val !== '0' && val !== 'false') return true;\n } catch {\n // process may not exist or env may throw — safe to ignore\n }\n\n return false;\n}\n","/**\n * Centralized AsyncLocalStorage registry for server-side per-request state.\n *\n * ALL ALS instances used by the server framework live here. Individual\n * modules (request-context.ts, tracing.ts, actions.ts, etc.) import from\n * this registry and re-export public accessor functions.\n *\n * Why: ALS instances require singleton semantics — if two copies of the\n * same ALS exist (one from a relative import, one from a barrel import),\n * one module writes to its copy and another reads from an empty copy.\n * Centralizing ALS creation in a single module eliminates this class of bug.\n *\n * The `timber-shims` plugin ensures `@timber-js/app/server` resolves to\n * src/ in RSC and SSR environments, so all import paths converge here.\n *\n * DO NOT create ALS instances outside this file. If you need a new ALS,\n * add it here and import from `./als-registry.js` in the consuming module.\n *\n * See design/18-build-system.md §\"Module Singleton Strategy\" and\n * §\"Singleton State Registry\".\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DebugComponentEntry } from './rsc-entry/helpers.js';\n\n// ─── Request Context ──────────────────────────────────────────────────────\n// Used by: request-context.ts (getHeaders(), getCookies(), getSearchParams())\n// Design doc: design/04-authorization.md\n\n/** @internal — import via request-context.ts public API */\nexport const requestContextAls = new AsyncLocalStorage<RequestContextStore>();\n\nexport interface RequestContextStore {\n /** Incoming request headers (read-only view). */\n headers: Headers;\n /** Raw cookie header string, parsed lazily into a Map on first access. */\n cookieHeader: string;\n /** Lazily-parsed cookie map (mutable — reflects write-overlay from set()). */\n parsedCookies?: Map<string, string>;\n /** Original (pre-overlay) frozen headers, kept for overlay merging. */\n originalHeaders: Headers;\n /**\n * Raw URLSearchParams for the current request.\n * To get typed parsed params, import a search params definition and\n * call `.parse(searchParams())`.\n */\n searchParams: URLSearchParams;\n /**\n * Raw search string from the request URL (e.g. \"?foo=bar&baz=1\").\n * Available synchronously for use in `redirect()` with `preserveSearchParams`.\n */\n searchString: string;\n /**\n * Coerced segment params for the current request.\n * Set by the pipeline after route matching and param coercion, before\n * middleware and rendering. Pages and layouts read params via\n * `getSegmentParams()` instead of receiving them as a prop.\n *\n * See design/07-routing.md §\"params.ts — Convention File for Typed Params\"\n */\n segmentParams?: Record<string, string | string[]>;\n /**\n * The matched segment path (e.g. '/(browse)/[artistSlug]/[year]').\n * Includes route groups and parallel slots — uniquely identifies the\n * segment in the route tree. Set by the pipeline alongside segmentParams.\n * Used by getSegmentParams() for dev-mode validation.\n * See design/41-global-params.md §Runtime Validation\n */\n matchedSegmentPath?: string;\n /**\n * Per-slot coerced segment params, keyed by the slot's full tree path\n * (e.g. '/(browse)/@shows/[artistSlug]/[...year]').\n *\n * Each slot walks its own segment tree and may interpret URL parts\n * differently from the main route (e.g. catch-all vs dynamic). This\n * map stores slot-specific params so getSegmentParams(segmentPath)\n * returns the correct types for slot pages.\n *\n * See design/07-routing.md §\"Parallel Slot Params\"\n */\n slotParamsMap?: Map<string, Record<string, string | string[]>>;\n /** Outgoing Set-Cookie entries (name → serialized value + options). Last write wins. */\n cookieJar: Map<string, CookieEntry>;\n /** Whether the response has flushed (headers committed). */\n flushed: boolean;\n /** Whether the current context allows cookie mutation. */\n mutableContext: boolean;\n /**\n * Set by AccessGate or PageDenyBoundary when a DenySignal is caught\n * server-side (inside the React tree, before React Flight sees it).\n * The pipeline reads this after render to set the HTTP status code.\n * See TIM-666.\n */\n denyStatus?: number;\n /**\n * Dev-only: getter for the current request's RSC debug components.\n * Set by renderRoute() so onPipelineError can include component tree\n * context for render-phase errors without module-level shared state.\n */\n debugComponentsGetter?: () => DebugComponentEntry[];\n}\n\n/** A single outgoing cookie entry in the cookie jar. */\nexport interface CookieEntry {\n name: string;\n value: string;\n options: import('./cookie-context.js').CookieOptions;\n}\n\n// ─── Tracing ──────────────────────────────────────────────────────────────\n// Used by: tracing.ts (getTraceId(), getSpanId())\n// Design doc: design/17-logging.md\n\nexport interface TraceStore {\n /** 32-char lowercase hex trace ID (OTEL or UUID fallback). */\n traceId: string;\n /** OTEL span ID if available, undefined otherwise. */\n spanId?: string;\n}\n\n/** @internal — import via tracing.ts public API */\nexport const traceAls = new AsyncLocalStorage<TraceStore>();\n\n// ─── Server-Timing ────────────────────────────────────────────────────────\n// Used by: server-timing.ts (recordTiming(), withTiming())\n// Design doc: (dev-only performance instrumentation)\n\nexport interface TimingStore {\n entries: import('./server-timing.js').TimingEntry[];\n}\n\n/** @internal — import via server-timing.ts public API */\nexport const timingAls = new AsyncLocalStorage<TimingStore>();\n\n// ─── Revalidation ─────────────────────────────────────────────────────────\n// Used by: actions.ts (revalidatePath(), revalidateTag())\n// Design doc: design/08-forms-and-actions.md\n\nexport interface RevalidationState {\n /** Paths to re-render (populated by revalidatePath calls). */\n paths: string[];\n /** Tags to invalidate (populated by revalidateTag calls). */\n tags: string[];\n}\n\n/** @internal — import via actions.ts public API */\nexport const revalidationAls = new AsyncLocalStorage<RevalidationState>();\n\n// ─── Form Flash ───────────────────────────────────────────────────────────\n// Used by: form-flash.ts (getFormFlash())\n// Design doc: design/08-forms-and-actions.md §\"No-JS Error Round-Trip\"\n\n/** @internal — import via form-flash.ts public API */\nexport const formFlashAls = new AsyncLocalStorage<import('./form-flash.js').FormFlashData>();\n\n// ─── Early Hints Sender ──────────────────────────────────────────────────\n// Used by: early-hints-sender.ts (sendEarlyHints103())\n// Design doc: design/02-rendering-pipeline.md §\"Early Hints (103)\"\n\n/** Function that sends Link header values as a 103 Early Hints response. */\nexport type EarlyHintsSenderFn = (links: string[]) => void;\n\n/** @internal — import via early-hints-sender.ts public API */\nexport const earlyHintsSenderAls = new AsyncLocalStorage<EarlyHintsSenderFn>();\n\n// ─── waitUntil Bridge ────────────────────────────────────────────────────\n// Used by: waituntil-bridge.ts (waitUntil())\n// Design doc: design/11-platform.md §\"waitUntil()\"\n\n/** Function that extends the request lifecycle with a background promise. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** @internal — import via waituntil-bridge.ts public API */\nexport const waitUntilAls = new AsyncLocalStorage<WaitUntilFn>();\n","/**\n * Tracing — per-request trace ID via AsyncLocalStorage, OTEL span helpers.\n *\n * getTraceId() is always available in server code (middleware, access, components, actions).\n * Returns a 32-char lowercase hex string — the OTEL trace ID when an SDK is active,\n * or a crypto.randomUUID()-derived fallback otherwise.\n *\n * See design/17-logging.md §\"trace_id is Always Set\"\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { traceAls, type TraceStore } from './als-registry.js';\n\n// Re-export the TraceStore type for public API consumers.\nexport type { TraceStore } from './als-registry.js';\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Returns the current request's trace ID — always a 32-char lowercase hex string.\n *\n * With OTEL: the real OTEL trace ID (matches Jaeger/Honeycomb/Datadog).\n * Without OTEL: crypto.randomUUID() with hyphens stripped.\n *\n * Throws if called outside a request context (no ALS store).\n */\nexport function getTraceId(): string {\n const store = traceAls.getStore();\n if (!store) {\n throw new Error(\n '[timber] getTraceId() called outside of a request context. ' +\n 'It can only be used in middleware, access checks, server components, and server actions.'\n );\n }\n return store.traceId;\n}\n\n/**\n * Returns the current OTEL span ID if available, undefined otherwise.\n */\nexport function getSpanId(): string | undefined {\n return traceAls.getStore()?.spanId;\n}\n\n// ─── Framework-Internal Helpers ───────────────────────────────────────────\n\n/**\n * Generate a 32-char lowercase hex ID from crypto.randomUUID().\n * Same format as OTEL trace IDs — zero-friction upgrade path.\n */\nexport function generateTraceId(): string {\n return randomUUID().replace(/-/g, '');\n}\n\n/**\n * Run a callback within a trace context. Used by the pipeline to establish\n * per-request ALS scope.\n */\nexport function runWithTraceId<T>(id: string, fn: () => T): T {\n return traceAls.run({ traceId: id }, fn);\n}\n\n/**\n * Replace the trace ID in the current ALS store. Used when OTEL creates\n * a root span and we want to switch from the UUID fallback to the real\n * OTEL trace ID.\n */\nexport function replaceTraceId(newTraceId: string, newSpanId?: string): void {\n const store = traceAls.getStore();\n if (store) {\n store.traceId = newTraceId;\n store.spanId = newSpanId;\n }\n}\n\n/**\n * Update the span ID in the current ALS store. Used when entering a new\n * OTEL span to keep log–trace correlation accurate.\n */\nexport function updateSpanId(newSpanId: string | undefined): void {\n const store = traceAls.getStore();\n if (store) {\n store.spanId = newSpanId;\n }\n}\n\n/**\n * Get the current trace store, or undefined if outside a request context.\n * Framework-internal — use getTraceId()/getSpanId() in user code.\n */\nexport function getTraceStore(): TraceStore | undefined {\n return traceAls.getStore();\n}\n\n// ─── Dev-Mode OTEL Auto-Init ─────────────────────────────────────────────\n\n/**\n * Initialize a minimal OTEL SDK in dev mode so spans are recorded and\n * fed to the DevSpanProcessor for dev log output.\n *\n * If the user already configured an OTEL SDK in register(), we add\n * our DevSpanProcessor alongside theirs. If no SDK is configured,\n * we create a BasicTracerProvider with our processor.\n *\n * Only called in dev mode — zero overhead in production.\n */\nexport async function initDevTracing(\n config: import('../dev-tools/logger.js').DevLoggerConfig\n): Promise<void> {\n const api = await getOtelApi();\n if (!api) return;\n\n let DevSpanProcessor: typeof import('../dev-tools/instrumentation.js').DevSpanProcessor;\n let BasicTracerProvider: typeof import('@opentelemetry/sdk-trace-base').BasicTracerProvider;\n let AsyncLocalStorageContextManager: typeof import('@opentelemetry/context-async-hooks').AsyncLocalStorageContextManager;\n\n try {\n ({ DevSpanProcessor } = await import('../dev-tools/instrumentation.js'));\n ({ BasicTracerProvider } = await import('@opentelemetry/sdk-trace-base'));\n ({ AsyncLocalStorageContextManager } = await import('@opentelemetry/context-async-hooks'));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn(`[timber] Dev tracing disabled — failed to load OTEL packages:\\n ${msg}`);\n return;\n }\n\n const processor = new DevSpanProcessor(config);\n\n // Register a context manager so OTEL can propagate the active span\n // across async boundaries. Without this, startActiveSpan can't make\n // spans \"active\" — child spans get random trace IDs and getActiveSpan()\n // returns undefined.\n const contextManager = new AsyncLocalStorageContextManager();\n contextManager.enable();\n api.context.setGlobalContextManager(contextManager);\n\n // Create a minimal TracerProvider with our DevSpanProcessor.\n // If the user also configures an SDK in register(), their provider\n // will coexist — the global provider set last wins for new tracers,\n // but our processor captures all spans from the timber.js tracer.\n const provider = new BasicTracerProvider({\n spanProcessors: [processor],\n });\n api.trace.setGlobalTracerProvider(provider);\n\n // Reset cached tracer so next getTracer() picks up the new provider\n _tracer = undefined;\n}\n\n// ─── OTEL Span Helpers ───────────────────────────────────────────────────\n\n/**\n * Attempt to get the @opentelemetry/api tracer. Returns undefined if the\n * package is not installed or no SDK is registered.\n *\n * timber.js depends on @opentelemetry/api as the vendor-neutral interface.\n * The API is a no-op by default — spans are only emitted when the developer\n * initializes an SDK in register().\n */\nlet _otelApi: typeof import('@opentelemetry/api') | null | undefined;\n\nasync function getOtelApi(): Promise<typeof import('@opentelemetry/api') | null> {\n if (_otelApi === undefined) {\n try {\n _otelApi = await import('@opentelemetry/api');\n } catch {\n _otelApi = null;\n }\n }\n return _otelApi;\n}\n\n/** OTEL tracer instance, lazily created. */\nlet _tracer: import('@opentelemetry/api').Tracer | null | undefined;\n\n/**\n * Get the timber.js OTEL tracer. Returns null if @opentelemetry/api is not available.\n */\nexport async function getTracer(): Promise<import('@opentelemetry/api').Tracer | null> {\n if (_tracer === undefined) {\n const api = await getOtelApi();\n if (api) {\n _tracer = api.trace.getTracer('timber.js');\n } else {\n _tracer = null;\n }\n }\n return _tracer;\n}\n\n/**\n * Run a function within an OTEL span. If OTEL is not available, runs the function\n * directly without any span overhead.\n *\n * Automatically:\n * - Creates the span as a child of the current context\n * - Updates the ALS span ID for log–trace correlation\n * - Ends the span when the function completes\n * - Records exceptions on error\n */\nexport async function withSpan<T>(\n name: string,\n attributes: Record<string, string | number | boolean>,\n fn: () => T | Promise<T>\n): Promise<T> {\n const tracer = await getTracer();\n if (!tracer) {\n return fn();\n }\n\n const api = (await getOtelApi())!;\n return tracer.startActiveSpan(name, { attributes }, async (span) => {\n const prevSpanId = getSpanId();\n updateSpanId(span.spanContext().spanId);\n try {\n const result = await fn();\n span.setStatus({ code: api.SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({ code: api.SpanStatusCode.ERROR });\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n updateSpanId(prevSpanId);\n }\n });\n}\n\n/**\n * Set an attribute on the current active span (if any).\n * Used for setting span attributes after span creation (e.g. timber.result on access spans).\n */\nexport async function setSpanAttribute(\n key: string,\n value: string | number | boolean\n): Promise<void> {\n const api = await getOtelApi();\n if (!api) return;\n\n const activeSpan = api.trace.getActiveSpan();\n if (activeSpan) {\n activeSpan.setAttribute(key, value);\n }\n}\n\n/**\n * Add a span event to the current active span (if any).\n * Used for timber.cache HIT/MISS events — recorded as span events, not child spans.\n */\nexport async function addSpanEvent(\n name: string,\n attributes?: Record<string, string | number | boolean>\n): Promise<void> {\n const api = await getOtelApi();\n if (!api) return;\n\n const activeSpan = api.trace.getActiveSpan();\n if (activeSpan) {\n activeSpan.addEvent(name, attributes);\n }\n}\n\n/**\n * Fire-and-forget span event — no await, no microtask overhead.\n *\n * Used on the cache hot path where awaiting addSpanEvent creates an\n * unnecessary microtask per cache operation. If OTEL is not loaded yet,\n * the event is silently dropped (acceptable for diagnostics).\n *\n * See TIM-370 for perf motivation.\n */\nexport function addSpanEventSync(\n name: string,\n attributes?: Record<string, string | number | boolean>\n): void {\n // Fast path: if OTEL API hasn't been loaded yet, skip entirely.\n // _otelApi is undefined (not yet loaded), null (failed to load), or the module.\n if (!_otelApi) return;\n\n const activeSpan = _otelApi.trace.getActiveSpan();\n if (activeSpan) {\n activeSpan.addEvent(name, attributes);\n }\n}\n\n/**\n * Try to extract the OTEL trace ID from the current active span context.\n * Returns undefined if OTEL is not active or no span exists.\n */\nexport async function getOtelTraceId(): Promise<{ traceId: string; spanId: string } | undefined> {\n const api = await getOtelApi();\n if (!api) return undefined;\n\n const activeSpan = api.trace.getActiveSpan();\n if (!activeSpan) return undefined;\n\n const ctx = activeSpan.spanContext();\n // OTEL uses \"0000000000000000\" as invalid trace IDs\n if (!ctx.traceId || ctx.traceId === '00000000000000000000000000000000') {\n return undefined;\n }\n\n return { traceId: ctx.traceId, spanId: ctx.spanId };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,SAAgB,YAAqB;AACnC,QAAA,QAAA,IAAA,aAAgC;;;;;;AASlC,IAAI,eAAe;;;;;;;;;;;;;;;;;AA0BnB,SAAgB,UAAmB;AAEjC,KAAA,QAAA,IAAA,aAA6B,aAAc,QAAO;AAGlD,KAAI,aAAc,QAAO;AAMzB,QAAO,qBAAqB;;;;;;;;;;AAW9B,SAAS,sBAA+B;AAEtC,KAAK,WAAuC,eAAgB,QAAO;AAGnE,KAAI;EAEF,MAAM,MACJ,OAAO,YAAY,eAAe,QAAQ,MACrC,QAAQ,IAHH,kBAIN,KAAA;AACN,MAAI,OAAO,QAAQ,OAAO,QAAQ,QAAS,QAAO;SAC5C;AAIR,QAAO;;;;;;;;;;;;;;;;;;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