@shubh90/app-runtime 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,66 @@
1
+ import { getAuthMode } from "./mode.js";
2
+ import { safeNext } from "./next-path.js";
3
+ import { SIGN_IN_PROBLEMS } from "./problems.js";
4
+ import { type MiiUser } from "./lookup.js";
5
+ import { type MiiIdentity } from "./plaza.js";
6
+ import { type UsersConfig } from "./users-config.js";
7
+ export type { MiiUser } from "./lookup.js";
8
+ export type { AuthMode } from "./mode.js";
9
+ export type { MiiIdentity, SignInFailure, SignInResult } from "./plaza.js";
10
+ export type { UsersConfig } from "./users-config.js";
11
+ export { SIGN_IN_PROBLEMS } from "./problems.js";
12
+ export { safeNext } from "./next-path.js";
13
+ export { getAuthMode } from "./mode.js";
14
+ export { SESSION_COOKIE, SESSION_TTL_MS } from "./lookup.js";
15
+ export { miiAuthConfig, type MiiAuthConfig } from "./config.js";
16
+ export { redeemWithPlaza, signInWithPlaza } from "./plaza.js";
17
+ export type CreateMiiAuthCoreOptions = {
18
+ /** Which table holds this app's people, if not the default `mii_auth_users`. */
19
+ readonly users?: UsersConfig;
20
+ /** Where to report failures that are ours, not the person's. Defaults to console.error. */
21
+ readonly reportError?: (error: unknown, context: Record<string, string>) => void;
22
+ };
23
+ export type MiiAuthCore = {
24
+ /** The user behind a session token, or null. The app reads its own cookie. */
25
+ resolveSession(token: string): Promise<MiiUser | null>;
26
+ /** Start a session; the app sets the cookie itself (see cookie notes below). */
27
+ issueSession(userId: string): Promise<{
28
+ token: string;
29
+ expiresAt: Date;
30
+ }>;
31
+ /** End one session by its token. */
32
+ revokeSession(token: string): Promise<void>;
33
+ upsertMemberFromIdentity(identity: MiiIdentity): Promise<{
34
+ id: string;
35
+ status: string;
36
+ }>;
37
+ deactivateUser(userId: string): Promise<void>;
38
+ /**
39
+ * The pane's silent sign-in: spend a ?mii_code= for an identity, upsert the
40
+ * member, start a session. Null when the code is spent/stale or the member
41
+ * is inactive (send them to /login).
42
+ */
43
+ redeemPaneCode(code: string): Promise<{
44
+ token: string;
45
+ expiresAt: Date;
46
+ } | null>;
47
+ getAuthMode: typeof getAuthMode;
48
+ readonly SESSION_COOKIE: string;
49
+ readonly SIGN_IN_PROBLEMS: typeof SIGN_IN_PROBLEMS;
50
+ readonly safeNext: typeof safeNext;
51
+ };
52
+ /**
53
+ * Cookie attributes the app must use with issueSession's token, mirrored from
54
+ * the Next adapter: inside Plaza's App pane the app is a third party, so the
55
+ * cookie must be SameSite=None + Secure + partitioned or the pane signs in
56
+ * forever; opened directly it is an ordinary Lax cookie. Decide by the
57
+ * request's `Sec-Fetch-Dest: iframe` header.
58
+ */
59
+ export declare function cookieAttributes(embedded: boolean): {
60
+ httpOnly: true;
61
+ path: "/";
62
+ sameSite: "none" | "lax";
63
+ secure: boolean;
64
+ partitioned: boolean;
65
+ };
66
+ export declare function createMiiAuthCore(options?: CreateMiiAuthCoreOptions): MiiAuthCore;
@@ -0,0 +1,62 @@
1
+ import { makeAuthSql } from "./db.js";
2
+ import { getAuthMode } from "./mode.js";
3
+ import { safeNext } from "./next-path.js";
4
+ import { SIGN_IN_PROBLEMS } from "./problems.js";
5
+ import { issueSession, resolveSession, SESSION_COOKIE, SESSION_TTL_MS, hashToken } from "./lookup.js";
6
+ import { redeemWithPlaza } from "./plaza.js";
7
+ import { deactivateUser, upsertMemberFromIdentity } from "./users.js";
8
+ import { resolveUsers } from "./users-config.js";
9
+ export { SIGN_IN_PROBLEMS } from "./problems.js";
10
+ export { safeNext } from "./next-path.js";
11
+ export { getAuthMode } from "./mode.js";
12
+ export { SESSION_COOKIE, SESSION_TTL_MS } from "./lookup.js";
13
+ export { miiAuthConfig } from "./config.js";
14
+ export { redeemWithPlaza, signInWithPlaza } from "./plaza.js";
15
+ /**
16
+ * Cookie attributes the app must use with issueSession's token, mirrored from
17
+ * the Next adapter: inside Plaza's App pane the app is a third party, so the
18
+ * cookie must be SameSite=None + Secure + partitioned or the pane signs in
19
+ * forever; opened directly it is an ordinary Lax cookie. Decide by the
20
+ * request's `Sec-Fetch-Dest: iframe` header.
21
+ */
22
+ export function cookieAttributes(embedded) {
23
+ return {
24
+ httpOnly: true,
25
+ path: "/",
26
+ sameSite: embedded ? "none" : "lax",
27
+ secure: embedded || process.env.NODE_ENV === "production",
28
+ partitioned: embedded
29
+ };
30
+ }
31
+ export function createMiiAuthCore(options = {}) {
32
+ const users = resolveUsers(options.users);
33
+ const ctx = {
34
+ getSql: makeAuthSql(users),
35
+ users,
36
+ reportError: options.reportError ??
37
+ ((error, context) => console.error("mii-auth error", context, error))
38
+ };
39
+ return {
40
+ resolveSession: (token) => resolveSession(ctx, token),
41
+ issueSession: (userId) => issueSession(ctx, userId),
42
+ revokeSession: async (token) => {
43
+ const sql = await ctx.getSql();
44
+ await sql `delete from mii_auth_sessions where token_hash = ${hashToken(token)}`;
45
+ },
46
+ upsertMemberFromIdentity: (identity) => upsertMemberFromIdentity(ctx, identity),
47
+ deactivateUser: (userId) => deactivateUser(ctx, userId),
48
+ redeemPaneCode: async (code) => {
49
+ const identity = await redeemWithPlaza(code);
50
+ if (identity === null)
51
+ return null;
52
+ const user = await upsertMemberFromIdentity(ctx, identity);
53
+ if (user.status !== "active")
54
+ return null;
55
+ return issueSession(ctx, user.id);
56
+ },
57
+ getAuthMode,
58
+ SESSION_COOKIE,
59
+ SIGN_IN_PROBLEMS,
60
+ safeNext
61
+ };
62
+ }
@@ -1,5 +1,6 @@
1
- /** Plaza origins allowed to frame an org app. Keep in step with the pane. */
2
- export declare const PLAZA_FRAME_ORIGINS: readonly ["https://plaza.miis.run", "https://miiplaza.vercel.app", "http://localhost:3000", "http://localhost:3111"];
1
+ import { PLAZA_FRAME_ORIGINS } from "../platform/index.js";
2
+ /** Re-exported for existing importers; the source of truth is ./platform. */
3
+ export { PLAZA_FRAME_ORIGINS };
3
4
  type Header = {
4
5
  key: string;
5
6
  value: string;
@@ -14,4 +15,3 @@ type NextConfigLike = {
14
15
  [k: string]: unknown;
15
16
  };
16
17
  export declare function withMiiPlatform(config?: NextConfigLike): NextConfigLike;
17
- export {};
@@ -10,23 +10,10 @@
10
10
  // Newmark SF set `frame-ancestors 'none'` + `X-Frame-Options: DENY` in its own
11
11
  // config and white-screened its pane. This makes that impossible: whatever the
12
12
  // app sets, the resulting headers frame-allow Plaza and carry no X-Frame-Options.
13
- /** Plaza origins allowed to frame an org app. Keep in step with the pane. */
14
- export const PLAZA_FRAME_ORIGINS = [
15
- "https://plaza.miis.run",
16
- "https://miiplaza.vercel.app",
17
- "http://localhost:3000",
18
- "http://localhost:3111"
19
- ];
20
- const FRAME_ANCESTORS = `frame-ancestors 'self' ${PLAZA_FRAME_ORIGINS.join(" ")}`;
21
- /** Force `frame-ancestors` to allow Plaza in a Content-Security-Policy value. */
22
- function forceFrameAncestors(csp) {
23
- const directives = csp
24
- .split(";")
25
- .map((d) => d.trim())
26
- .filter((d) => d !== "" && !d.toLowerCase().startsWith("frame-ancestors"));
27
- directives.push(FRAME_ANCESTORS);
28
- return directives.join("; ");
29
- }
13
+ import { FRAME_ANCESTORS, forceFrameAncestors as forceCsp, PLAZA_FRAME_ORIGINS } from "../platform/index.js";
14
+ /** Re-exported for existing importers; the source of truth is ./platform. */
15
+ export { PLAZA_FRAME_ORIGINS };
16
+ const forceFrameAncestors = forceCsp;
30
17
  /** Rewrite one route's headers: fix any CSP's frame-ancestors, drop XFO. */
31
18
  function enforce(headers) {
32
19
  let sawCsp = false;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Plaza origins allowed to frame an org app AND to drive its preview bridge.
3
+ * One list on purpose: who may frame the app and who may talk to it must never
4
+ * drift apart. localhost is here because Plaza is developed locally against
5
+ * real deployed org apps.
6
+ */
7
+ export declare const PLAZA_FRAME_ORIGINS: readonly ["https://plaza.miis.run", "https://miiplaza.vercel.app", "http://localhost:3000", "http://localhost:3111"];
8
+ export declare const FRAME_ANCESTORS: string;
9
+ /** Force a Content-Security-Policy value's frame-ancestors to allow Plaza. */
10
+ export declare function forceFrameAncestors(csp: string): string;
11
+ /**
12
+ * Enforce the framing contract on one response's headers, in place: any CSP
13
+ * keeps its own directives but frame-allows Plaza, X-Frame-Options is dropped
14
+ * (it cannot allowlist; CSP governs), and a response with no CSP gains one.
15
+ * Wire it wherever the app touches every response once — a Start server
16
+ * middleware, a Node server hook — and the Newmark white-pane class of bug
17
+ * has no mechanism left.
18
+ */
19
+ export declare function applyMiiFraming(headers: Headers): void;
20
+ export type PlatformEnv = {
21
+ /** Vercel's environment name; undefined locally. */
22
+ readonly vercelEnv?: string;
23
+ /** MII_ORG_ID / VITE_MII_ORG_ID — the tag that makes telemetry attributable. */
24
+ readonly orgId?: string;
25
+ };
26
+ export type MiiErrorPolicy = {
27
+ readonly enabled: boolean;
28
+ readonly environment: string;
29
+ readonly tracesSampleRate: 0;
30
+ readonly sendDefaultPii: false;
31
+ readonly initialScope: {
32
+ readonly tags: {
33
+ readonly org_id: string | undefined;
34
+ };
35
+ };
36
+ };
37
+ /**
38
+ * The Sentry init options an org app must not diverge from, for any Sentry
39
+ * SDK (`Sentry.init({ dsn, ...miiErrorPolicy(...) })`). The Sentry project is
40
+ * shared across every org app, so an untagged event is un-attributable: the
41
+ * policy stays OFF rather than emit one. Errors are the only quota the
42
+ * platform pays for — tracing stays off. `force` mirrors SENTRY_FORCE_ENABLE
43
+ * for testing locally.
44
+ */
45
+ export declare function miiErrorPolicy(env: PlatformEnv & {
46
+ readonly dsn?: string;
47
+ readonly force?: boolean;
48
+ }): MiiErrorPolicy;
49
+ export type MiiAnalyticsPolicy = {
50
+ readonly enabled: boolean;
51
+ /** posthog-js init options: `posthog.init("in-house", options)`. */
52
+ readonly options: {
53
+ readonly api_host: string;
54
+ readonly defaults: string;
55
+ readonly person_profiles: "identified_only";
56
+ readonly advanced_disable_flags: true;
57
+ readonly disable_external_dependency_loading: true;
58
+ readonly disable_surveys: true;
59
+ readonly disable_session_recording: true;
60
+ readonly capture_exceptions: false;
61
+ };
62
+ };
63
+ /**
64
+ * Analytics is in-house: posthog-js is purely the capture SDK, events go to
65
+ * the mii ingest endpoint and no analytics vendor is involved. Off in local
66
+ * dev unless forced, so clicking around locally doesn't pollute product data.
67
+ * Cloud-only SDK features stay off so the client never phones home.
68
+ */
69
+ export declare function miiAnalyticsPolicy(env: PlatformEnv & {
70
+ readonly ingestHost: string;
71
+ readonly force?: boolean;
72
+ }): MiiAnalyticsPolicy;
73
+ /**
74
+ * Whether this browser is automation (the org's own agents, E2E runs), which
75
+ * analytics must keep separable from real users (`is_agent=true`).
76
+ * `?mii_agent=1` is the manual override and persists via localStorage;
77
+ * Playwright-family browsers set `navigator.webdriver`.
78
+ */
79
+ export declare function isAgentBrowser(win: Window): boolean;
@@ -0,0 +1,101 @@
1
+ // The platform policies every mii org app must agree on, framework-free and
2
+ // dependency-free. The framing list, the error-reporting rules and the
3
+ // analytics rules are contracts: an app that drifts on any of them breaks its
4
+ // deal with Plaza (a pane it cannot be shown in, errors nobody can attribute,
5
+ // events that pollute product data). Frameworks come and go around this file;
6
+ // nothing in it may import one.
7
+ /**
8
+ * Plaza origins allowed to frame an org app AND to drive its preview bridge.
9
+ * One list on purpose: who may frame the app and who may talk to it must never
10
+ * drift apart. localhost is here because Plaza is developed locally against
11
+ * real deployed org apps.
12
+ */
13
+ export const PLAZA_FRAME_ORIGINS = [
14
+ "https://plaza.miis.run",
15
+ "https://miiplaza.vercel.app",
16
+ "http://localhost:3000",
17
+ "http://localhost:3111"
18
+ ];
19
+ export const FRAME_ANCESTORS = `frame-ancestors 'self' ${PLAZA_FRAME_ORIGINS.join(" ")}`;
20
+ /** Force a Content-Security-Policy value's frame-ancestors to allow Plaza. */
21
+ export function forceFrameAncestors(csp) {
22
+ const directives = csp
23
+ .split(";")
24
+ .map((d) => d.trim())
25
+ .filter((d) => d !== "" && !d.toLowerCase().startsWith("frame-ancestors"));
26
+ directives.push(FRAME_ANCESTORS);
27
+ return directives.join("; ");
28
+ }
29
+ /**
30
+ * Enforce the framing contract on one response's headers, in place: any CSP
31
+ * keeps its own directives but frame-allows Plaza, X-Frame-Options is dropped
32
+ * (it cannot allowlist; CSP governs), and a response with no CSP gains one.
33
+ * Wire it wherever the app touches every response once — a Start server
34
+ * middleware, a Node server hook — and the Newmark white-pane class of bug
35
+ * has no mechanism left.
36
+ */
37
+ export function applyMiiFraming(headers) {
38
+ headers.delete("x-frame-options");
39
+ const csp = headers.get("content-security-policy");
40
+ headers.set("content-security-policy", csp === null ? FRAME_ANCESTORS : forceFrameAncestors(csp));
41
+ }
42
+ const isDeployed = (env) => env.vercelEnv === "production" || env.vercelEnv === "preview";
43
+ /**
44
+ * The Sentry init options an org app must not diverge from, for any Sentry
45
+ * SDK (`Sentry.init({ dsn, ...miiErrorPolicy(...) })`). The Sentry project is
46
+ * shared across every org app, so an untagged event is un-attributable: the
47
+ * policy stays OFF rather than emit one. Errors are the only quota the
48
+ * platform pays for — tracing stays off. `force` mirrors SENTRY_FORCE_ENABLE
49
+ * for testing locally.
50
+ */
51
+ export function miiErrorPolicy(env) {
52
+ return {
53
+ enabled: Boolean(env.dsn) &&
54
+ Boolean(env.orgId) &&
55
+ (isDeployed(env) || env.force === true),
56
+ environment: env.vercelEnv ?? "development",
57
+ tracesSampleRate: 0,
58
+ sendDefaultPii: false,
59
+ initialScope: { tags: { org_id: env.orgId } }
60
+ };
61
+ }
62
+ /**
63
+ * Analytics is in-house: posthog-js is purely the capture SDK, events go to
64
+ * the mii ingest endpoint and no analytics vendor is involved. Off in local
65
+ * dev unless forced, so clicking around locally doesn't pollute product data.
66
+ * Cloud-only SDK features stay off so the client never phones home.
67
+ */
68
+ export function miiAnalyticsPolicy(env) {
69
+ return {
70
+ enabled: isDeployed(env) || env.force === true,
71
+ options: {
72
+ api_host: env.ingestHost,
73
+ defaults: "2026-06-25",
74
+ person_profiles: "identified_only",
75
+ advanced_disable_flags: true,
76
+ disable_external_dependency_loading: true,
77
+ disable_surveys: true,
78
+ disable_session_recording: true,
79
+ capture_exceptions: false
80
+ }
81
+ };
82
+ }
83
+ /**
84
+ * Whether this browser is automation (the org's own agents, E2E runs), which
85
+ * analytics must keep separable from real users (`is_agent=true`).
86
+ * `?mii_agent=1` is the manual override and persists via localStorage;
87
+ * Playwright-family browsers set `navigator.webdriver`.
88
+ */
89
+ export function isAgentBrowser(win) {
90
+ try {
91
+ if (new URLSearchParams(win.location.search).has("mii_agent")) {
92
+ win.localStorage.setItem("mii_agent", "1");
93
+ }
94
+ return (win.navigator.webdriver === true ||
95
+ win.localStorage.getItem("mii_agent") === "1");
96
+ }
97
+ catch {
98
+ // localStorage can be unavailable (privacy modes); never break the app.
99
+ return win.navigator.webdriver === true;
100
+ }
101
+ }
@@ -0,0 +1 @@
1
+ export { MiiPaneBridge } from "./pane-bridge.js";
@@ -0,0 +1,4 @@
1
+ // React pieces of the platform contract. Framework-free React: no Next, no
2
+ // TanStack imports — route changes are observed from the History API itself,
3
+ // so the same component is correct under any router.
4
+ export { MiiPaneBridge } from "./pane-bridge.js";
@@ -0,0 +1 @@
1
+ export declare function MiiPaneBridge(): null;
@@ -0,0 +1,206 @@
1
+ "use client";
2
+ // How an org app talks to Plaza when Plaza is showing it in a pane.
3
+ //
4
+ // Plaza embeds the deployment in an iframe. That iframe is a different origin,
5
+ // so the browser will not let Plaza read the route inside it, catch its
6
+ // errors, or find an element in it — a preview with none of those is a picture
7
+ // of an app rather than something you can work on. This posts the missing
8
+ // facts outward and answers the two questions Plaza can ask.
9
+ //
10
+ // Plaza speaks first. Until an allowed origin says hello this app posts
11
+ // nothing at all, so being framed by someone else leaks nothing: no route, no
12
+ // errors, no DOM. That handshake is also why the parent origin is never
13
+ // guessed from `document.referrer`, which an iframe can suppress.
14
+ //
15
+ // Deliberately no analytics — the ingest pipe already records what people do.
16
+ // This is only the live channel to the pane, and it leaves no trace.
17
+ import { useEffect, useRef } from "react";
18
+ import { PLAZA_FRAME_ORIGINS } from "../platform/index.js";
19
+ const PLAZA_ORIGINS = PLAZA_FRAME_ORIGINS;
20
+ /**
21
+ * Route changes without a router dependency: popstate covers back/forward,
22
+ * and pushState/replaceState are wrapped to announce themselves, which every
23
+ * SPA router ultimately calls. The wrap is installed once per mount and
24
+ * restored on unmount.
25
+ */
26
+ function onRouteChange(callback) {
27
+ const announce = () => queueMicrotask(callback);
28
+ const wrap = (method) => {
29
+ const original = window.history[method].bind(window.history);
30
+ const wrapped = (...args) => {
31
+ original(...args);
32
+ announce();
33
+ };
34
+ window.history[method] = wrapped;
35
+ return () => {
36
+ window.history[method] = original;
37
+ };
38
+ };
39
+ const restorePush = wrap("pushState");
40
+ const restoreReplace = wrap("replaceState");
41
+ window.addEventListener("popstate", announce);
42
+ return () => {
43
+ restorePush();
44
+ restoreReplace();
45
+ window.removeEventListener("popstate", announce);
46
+ };
47
+ }
48
+ export function MiiPaneBridge() {
49
+ // Set by the handshake, read by the route announcements. A ref rather than
50
+ // state: nothing renders from it.
51
+ const plazaRef = useRef(null);
52
+ useEffect(() => {
53
+ // `window.parent === window` when this app is the whole tab, which is the
54
+ // ordinary case — someone just using the app.
55
+ if (window.parent === window)
56
+ return;
57
+ const describe = () => ({
58
+ path: window.location.pathname + window.location.search,
59
+ title: document.title
60
+ });
61
+ const send = (message) => {
62
+ const plaza = plazaRef.current;
63
+ if (plaza !== null)
64
+ window.parent.postMessage(message, plaza);
65
+ };
66
+ // Runtime failures the pane would otherwise never hear about. Sentry gets
67
+ // these too, but Sentry is somewhere you go afterwards — an agent watching
68
+ // its own change land needs to know now.
69
+ const onError = (event) => send({
70
+ type: "mii-preview:error",
71
+ message: event.message,
72
+ source: `${event.filename}:${event.lineno}`
73
+ });
74
+ const onRejection = (event) => send({
75
+ type: "mii-preview:error",
76
+ message: String(event.reason),
77
+ source: "unhandled rejection"
78
+ });
79
+ // Select mode. Hovering paints one outline element — reused, never
80
+ // stacked — and clicking reports what was picked instead of activating
81
+ // it: you are pointing at a button to talk about it, not pressing it.
82
+ let selecting = false;
83
+ const outline = document.createElement("div");
84
+ outline.setAttribute("aria-hidden", "true");
85
+ // Injected imperatively and deliberately outside the design system: this
86
+ // paints over the app, so it must not inherit the app's own theming.
87
+ outline.style.cssText =
88
+ "position:fixed;pointer-events:none;z-index:2147483647;display:none;" +
89
+ "border:2px solid #4f7cff;border-radius:3px;background:rgba(79,124,255,0.12)";
90
+ const onMove = (event) => {
91
+ if (!selecting)
92
+ return;
93
+ const rect = event.target.getBoundingClientRect();
94
+ outline.style.display = "block";
95
+ outline.style.top = `${rect.top}px`;
96
+ outline.style.left = `${rect.left}px`;
97
+ outline.style.width = `${rect.width}px`;
98
+ outline.style.height = `${rect.height}px`;
99
+ };
100
+ const onClick = (event) => {
101
+ if (!selecting)
102
+ return;
103
+ event.preventDefault();
104
+ event.stopPropagation();
105
+ const target = event.target;
106
+ send({
107
+ type: "mii-preview:picked",
108
+ // `data-el` is the codebase's label convention — the analytics ingest
109
+ // reads the same attribute, so an element already named for a chart
110
+ // arrives here under the name it already has.
111
+ label: target.getAttribute("data-el") ??
112
+ (target.textContent ?? "").trim().slice(0, 80),
113
+ selector: selectorFor(target),
114
+ tag: target.tagName.toLowerCase(),
115
+ ...describe()
116
+ });
117
+ };
118
+ const onMessage = (event) => {
119
+ if (!PLAZA_ORIGINS.includes(event.origin))
120
+ return;
121
+ plazaRef.current = event.origin;
122
+ const message = event.data;
123
+ if (message.type === "mii-preview:hello") {
124
+ send({ type: "mii-preview:ready", ...describe() });
125
+ return;
126
+ }
127
+ if (message.type === "mii-preview:select") {
128
+ selecting = message.on;
129
+ document.body.style.cursor = selecting ? "crosshair" : "";
130
+ if (!selecting)
131
+ outline.style.display = "none";
132
+ return;
133
+ }
134
+ if (message.type === "mii-preview:locate") {
135
+ // Where is this element, right now, in this window? Plaza uses the
136
+ // answer to put a cursor on it. Asked by element rather than by
137
+ // coordinates so the answer stays right when this window is a
138
+ // different size than the one being replayed.
139
+ const found = document.querySelector(message.selector);
140
+ send({
141
+ type: "mii-preview:located",
142
+ id: message.id,
143
+ rect: found === null ? null : rectOf(found)
144
+ });
145
+ }
146
+ };
147
+ // A navigation reports itself; the listener set above stays put.
148
+ const stopRouteWatch = onRouteChange(() => {
149
+ const plaza = plazaRef.current;
150
+ if (plaza === null)
151
+ return;
152
+ window.parent.postMessage({ type: "mii-preview:route", ...describe() }, plaza);
153
+ });
154
+ document.body.appendChild(outline);
155
+ window.addEventListener("error", onError);
156
+ window.addEventListener("unhandledrejection", onRejection);
157
+ window.addEventListener("message", onMessage);
158
+ document.addEventListener("mousemove", onMove, true);
159
+ document.addEventListener("click", onClick, true);
160
+ return () => {
161
+ stopRouteWatch();
162
+ window.removeEventListener("error", onError);
163
+ window.removeEventListener("unhandledrejection", onRejection);
164
+ window.removeEventListener("message", onMessage);
165
+ document.removeEventListener("mousemove", onMove, true);
166
+ document.removeEventListener("click", onClick, true);
167
+ document.body.style.cursor = "";
168
+ outline.remove();
169
+ };
170
+ }, []);
171
+ return null;
172
+ }
173
+ function rectOf(element) {
174
+ const rect = element.getBoundingClientRect();
175
+ return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
176
+ }
177
+ /**
178
+ * A selector that finds this element again in another window. Prefers the
179
+ * names that survive a re-render — an id, the `data-el` label — and only
180
+ * counts siblings when an element carries no name of its own.
181
+ */
182
+ function selectorFor(element) {
183
+ const parts = [];
184
+ let node = element;
185
+ while (node !== null && node !== document.body) {
186
+ if (node.id !== "") {
187
+ parts.unshift(`#${CSS.escape(node.id)}`);
188
+ break;
189
+ }
190
+ const label = node.getAttribute("data-el");
191
+ if (label !== null) {
192
+ parts.unshift(`[data-el="${CSS.escape(label)}"]`);
193
+ break;
194
+ }
195
+ const parent = node.parentElement;
196
+ const tag = node.tagName.toLowerCase();
197
+ if (parent === null) {
198
+ parts.unshift(tag);
199
+ break;
200
+ }
201
+ const twins = [...parent.children].filter((child) => child.tagName === node?.tagName);
202
+ parts.unshift(twins.length === 1 ? tag : `${tag}:nth-of-type(${twins.indexOf(node) + 1})`);
203
+ node = parent;
204
+ }
205
+ return parts.join(" > ");
206
+ }
@@ -0,0 +1,9 @@
1
+ export declare const DB_RETRY_ATTEMPTS = 4;
2
+ export declare function isTransientConnectionError(error: unknown): boolean;
3
+ export type DbRetryOptions = {
4
+ readonly attempts?: number;
5
+ readonly baseDelayMs?: number;
6
+ /** Injected by tests so they do not spend real seconds sleeping. */
7
+ readonly sleep?: (ms: number) => Promise<void>;
8
+ };
9
+ export declare function withDbRetry<T>(operation: () => Promise<T>, options?: DbRetryOptions): Promise<T>;
@@ -0,0 +1,54 @@
1
+ // Ported from the Next template's src/lib/db-retry.ts, where it earned its
2
+ // shape in production (transient EAI_AGAIN across several orgs, 2026-08-22):
3
+ // postgres.js connects lazily, so a resolver blip surfaces on the first query
4
+ // and nothing underneath tries again. Retry the connect, and only the connect
5
+ // — a wrong password or a missing table must still fail on attempt one.
6
+ const TRANSIENT_CODES = new Set([
7
+ "EAI_AGAIN",
8
+ "ENOTFOUND",
9
+ "ETIMEDOUT",
10
+ "ECONNRESET",
11
+ "ECONNREFUSED",
12
+ "ENETUNREACH",
13
+ "EHOSTUNREACH",
14
+ "CONNECT_TIMEOUT"
15
+ ]);
16
+ export const DB_RETRY_ATTEMPTS = 4;
17
+ const BASE_DELAY_MS = 250;
18
+ function errorCode(error) {
19
+ let current = error;
20
+ for (let depth = 0; current !== null && current !== undefined && depth < 5; depth += 1) {
21
+ const code = current.code;
22
+ if (typeof code === "string")
23
+ return code;
24
+ current = current.cause;
25
+ }
26
+ return undefined;
27
+ }
28
+ export function isTransientConnectionError(error) {
29
+ const code = errorCode(error);
30
+ return code !== undefined && TRANSIENT_CODES.has(code);
31
+ }
32
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
33
+ export async function withDbRetry(operation, options = {}) {
34
+ const attempts = options.attempts ?? DB_RETRY_ATTEMPTS;
35
+ const baseDelayMs = options.baseDelayMs ?? BASE_DELAY_MS;
36
+ const sleep = options.sleep ?? wait;
37
+ let lastError;
38
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
39
+ try {
40
+ return await operation();
41
+ }
42
+ catch (error) {
43
+ if (!isTransientConnectionError(error))
44
+ throw error;
45
+ lastError = error;
46
+ if (attempt < attempts)
47
+ await sleep(baseDelayMs * 2 ** (attempt - 1));
48
+ }
49
+ }
50
+ throw new Error(`Could not reach the database after ${attempts} attempts ` +
51
+ `(${errorCode(lastError) ?? "unknown"}). The host did not resolve or ` +
52
+ `accept a connection. This is a transient network fault, not a ` +
53
+ `credential, schema or permission problem — run the command again.`, { cause: lastError });
54
+ }
@@ -0,0 +1,19 @@
1
+ import { type DbRetryOptions } from "./db-retry.js";
2
+ export { withDbRetry, isTransientConnectionError, DB_RETRY_ATTEMPTS } from "./db-retry.js";
3
+ export type { DbRetryOptions } from "./db-retry.js";
4
+ export type HealthHandlerOptions = {
5
+ /** Defaults to process.env.DATABASE_URL, read per request. */
6
+ readonly databaseUrl?: () => string | undefined;
7
+ /** Defaults to process.env.MII_ORG_ID. */
8
+ readonly orgId?: () => string | undefined;
9
+ /** Test hook: shrink attempts/delays so failure paths don't spend seconds. */
10
+ readonly retry?: DbRetryOptions;
11
+ };
12
+ /**
13
+ * GET /api/health — the readiness gate. The sandbox refuses to report an
14
+ * instance as up, and Plaza refuses to wake one, until this answers ok. It
15
+ * proves the one dependency that page loads actually need: the database
16
+ * answers a query. A transient DNS fault must not read as an unhealthy app,
17
+ * hence the connect retry.
18
+ */
19
+ export declare function createHealthHandler(options?: HealthHandlerOptions): () => Promise<Response>;
@@ -0,0 +1,43 @@
1
+ // Web-standard server handlers (Request → Response) for the routes the
2
+ // platform itself calls on every org app. Framework-free: a TanStack Start
3
+ // server route, a Next route handler, or a bare Node server can mount these
4
+ // verbatim — which is the point, because the platform's probes must behave
5
+ // identically on every stack.
6
+ import postgres from "postgres";
7
+ import { withDbRetry } from "./db-retry.js";
8
+ export { withDbRetry, isTransientConnectionError, DB_RETRY_ATTEMPTS } from "./db-retry.js";
9
+ /**
10
+ * GET /api/health — the readiness gate. The sandbox refuses to report an
11
+ * instance as up, and Plaza refuses to wake one, until this answers ok. It
12
+ * proves the one dependency that page loads actually need: the database
13
+ * answers a query. A transient DNS fault must not read as an unhealthy app,
14
+ * hence the connect retry.
15
+ */
16
+ export function createHealthHandler(options = {}) {
17
+ const databaseUrl = options.databaseUrl ?? (() => process.env.DATABASE_URL);
18
+ const orgId = options.orgId ?? (() => process.env.MII_ORG_ID);
19
+ return async function health() {
20
+ const url = databaseUrl();
21
+ if (!url) {
22
+ return Response.json({ ok: false, error: "DATABASE_URL is not configured" }, { status: 503 });
23
+ }
24
+ const sql = postgres(url, { max: 1, prepare: false, connect_timeout: 10 });
25
+ try {
26
+ const [result] = await withDbRetry(() => sql `
27
+ select current_database() as database, now()::text as now
28
+ `, options.retry);
29
+ return Response.json({
30
+ ok: true,
31
+ orgId: orgId() ?? null,
32
+ database: result?.database ?? null,
33
+ databaseTime: result?.now ?? null
34
+ });
35
+ }
36
+ catch (err) {
37
+ return Response.json({ ok: false, error: err instanceof Error ? err.message : "Unknown error" }, { status: 503 });
38
+ }
39
+ finally {
40
+ await sql.end();
41
+ }
42
+ };
43
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@shubh90/app-runtime",
3
- "version": "0.2.2",
4
- "description": "The platform contract every mii org app depends on \u2014 sign-in, and the Next.js config an app must not diverge from. A versioned package, not files copied into each repo.",
3
+ "version": "0.4.0",
4
+ "description": "The platform contract every mii org app depends on sign-in, and the Next.js config an app must not diverge from. A versioned package, not files copied into each repo.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
7
7
  "publishConfig": {
@@ -20,9 +20,25 @@
20
20
  "types": "./dist/auth/index.d.ts",
21
21
  "import": "./dist/auth/index.js"
22
22
  },
23
+ "./auth/core": {
24
+ "types": "./dist/auth/core.d.ts",
25
+ "import": "./dist/auth/core.js"
26
+ },
23
27
  "./next": {
24
28
  "types": "./dist/next/index.d.ts",
25
29
  "import": "./dist/next/index.js"
30
+ },
31
+ "./platform": {
32
+ "types": "./dist/platform/index.d.ts",
33
+ "import": "./dist/platform/index.js"
34
+ },
35
+ "./server": {
36
+ "types": "./dist/server/index.d.ts",
37
+ "import": "./dist/server/index.js"
38
+ },
39
+ "./react": {
40
+ "types": "./dist/react/index.d.ts",
41
+ "import": "./dist/react/index.js"
26
42
  }
27
43
  },
28
44
  "scripts": {
@@ -33,12 +49,23 @@
33
49
  },
34
50
  "peerDependencies": {
35
51
  "next": ">=15",
36
- "postgres": ">=3"
52
+ "postgres": ">=3",
53
+ "react": ">=18"
54
+ },
55
+ "peerDependenciesMeta": {
56
+ "next": {
57
+ "optional": true
58
+ },
59
+ "react": {
60
+ "optional": "true"
61
+ }
37
62
  },
38
63
  "devDependencies": {
39
64
  "@types/node": "^22",
65
+ "@types/react": "^19",
40
66
  "next": "^15",
41
67
  "postgres": "^3.4.9",
68
+ "react": "^19",
42
69
  "tsx": "^4",
43
70
  "typescript": "^5.6"
44
71
  }