@fierst/c7t 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/bin/c7t.d.mts +1 -0
- package/bin/c7t.mjs +107 -0
- package/bin/create.d.mts +9 -0
- package/bin/create.mjs +344 -0
- package/dist/adapters/bun.d.mts +40 -0
- package/dist/adapters/bun.mjs +114 -0
- package/dist/adapters/cloudflare.d.mts +29 -0
- package/dist/adapters/cloudflare.mjs +28 -0
- package/dist/adapters/node.d.mts +31 -0
- package/dist/adapters/node.mjs +139 -0
- package/dist/adapters/static.d.mts +34 -0
- package/dist/adapters/static.mjs +53 -0
- package/dist/adapters/vercel.d.mts +40 -0
- package/dist/adapters/vercel.mjs +79 -0
- package/dist/client.d.mts +78 -0
- package/dist/client.mjs +181 -0
- package/dist/head-CUiNFY7Q.mjs +142 -0
- package/dist/index.d.mts +77 -0
- package/dist/index.mjs +25 -0
- package/dist/multipart-CwqTb3AQ.mjs +72 -0
- package/dist/protocol-B6QOAMGj.d.mts +115 -0
- package/dist/protocol-CZANZJ5x.mjs +126 -0
- package/dist/router-19ZZ3woS.d.mts +148 -0
- package/dist/router-B50LekA_.mjs +680 -0
- package/dist/router.d.mts +2 -0
- package/dist/router.mjs +1 -0
- package/dist/search-params-C03mU47i.mjs +79 -0
- package/dist/server.d.mts +146 -0
- package/dist/server.mjs +850 -0
- package/dist/ssg-DFBgqaob.d.mts +40 -0
- package/dist/ssg.d.mts +2 -0
- package/dist/ssg.mjs +179 -0
- package/dist/vite.d.mts +95 -0
- package/dist/vite.mjs +920 -0
- package/docs/README.md +26 -0
- package/docs/guides/01-getting-started.md +164 -0
- package/docs/guides/02-data-fetching-and-mutations.md +258 -0
- package/docs/guides/03-streaming-and-workflows.md +198 -0
- package/docs/guides/04-routing-layouts-and-state.md +236 -0
- package/docs/guides/05-auth-sessions-and-security.md +179 -0
- package/docs/guides/06-ssg-and-deployment.md +247 -0
- package/docs/guides/07-databases-and-drizzle.md +200 -0
- package/docs/reference.md +112 -0
- package/llms.txt +1627 -0
- package/package.json +121 -4
- package/template/gitignore +11 -0
- package/template/package.json +22 -0
- package/template/src/routes/404.tsx +16 -0
- package/template/src/routes/about.tsx +22 -0
- package/template/src/routes/index.tsx +41 -0
- package/template/src/routes/layout.tsx +14 -0
- package/template/src/styles.css +39 -0
- package/template/tsconfig.json +18 -0
- package/template/vite.config.ts +16 -0
package/dist/client.mjs
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { a as createServerCall, n as RedirectSignal, r as ValidationError, t as HttpStatusError } from "./protocol-CZANZJ5x.mjs";
|
|
2
|
+
import { r as encodeMultipartRpcArgs, t as containsBinaryData } from "./multipart-CwqTb3AQ.mjs";
|
|
3
|
+
import { f as installReceiptResolver, l as navigate, s as installClientRouter } from "./router-B50LekA_.mjs";
|
|
4
|
+
import { t as _notifySearchParamsChanged } from "./search-params-C03mU47i.mjs";
|
|
5
|
+
import { _getActiveOwner } from "@fierst/blokd";
|
|
6
|
+
import { installRevival } from "@fierst/blokd/revive";
|
|
7
|
+
// src/client.ts
|
|
8
|
+
let clientConfig = {};
|
|
9
|
+
function configureClient(config) {
|
|
10
|
+
clientConfig = {
|
|
11
|
+
...clientConfig,
|
|
12
|
+
...config
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
function getRpcUrl(fnId) {
|
|
16
|
+
return `${(clientConfig.rpcBase ?? "/_c7t/rpc").replace(/\/$/, "")}/${encodeURIComponent(fnId)}`;
|
|
17
|
+
}
|
|
18
|
+
function getFetch() {
|
|
19
|
+
return clientConfig.fetch ?? globalThis.fetch.bind(globalThis);
|
|
20
|
+
}
|
|
21
|
+
function reconstructWireError(errPayload) {
|
|
22
|
+
if (errPayload.name === "ValidationError" && errPayload.issues) return new ValidationError(errPayload.issues, errPayload.message);
|
|
23
|
+
if (errPayload.status !== void 0) return new HttpStatusError(errPayload.status, errPayload.message, errPayload.data);
|
|
24
|
+
const err = new Error(errPayload.message);
|
|
25
|
+
err.name = errPayload.name || "ServerError";
|
|
26
|
+
return err;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Create a lightweight client RPC stub for a `server(...)` or `*.server.ts` function.
|
|
30
|
+
* Supports both `yield* stub(...args)` (0-tick SSR receipt revival + live fallback)
|
|
31
|
+
* and `await stub(...args)` (live HTTP POST RPC).
|
|
32
|
+
*/
|
|
33
|
+
function createRpcStub(fnId) {
|
|
34
|
+
return (...args) => {
|
|
35
|
+
const callerOwner = _getActiveOwner();
|
|
36
|
+
return createServerCall(fnId, args, async (stepSignal) => {
|
|
37
|
+
const signal = stepSignal ?? callerOwner?.signal;
|
|
38
|
+
const isMultipart = containsBinaryData(args);
|
|
39
|
+
const headers = {
|
|
40
|
+
Accept: "application/json",
|
|
41
|
+
"X-C7T-RPC": "1"
|
|
42
|
+
};
|
|
43
|
+
if (!isMultipart) headers["Content-Type"] = "application/json";
|
|
44
|
+
const res = await getFetch()(getRpcUrl(fnId), {
|
|
45
|
+
method: "POST",
|
|
46
|
+
headers,
|
|
47
|
+
credentials: "same-origin",
|
|
48
|
+
body: isMultipart ? encodeMultipartRpcArgs(args) : JSON.stringify({ args }),
|
|
49
|
+
signal
|
|
50
|
+
});
|
|
51
|
+
const payload = await res.json();
|
|
52
|
+
if (!payload.ok) {
|
|
53
|
+
if (payload.redirect) {
|
|
54
|
+
navigate(payload.redirect.location, { replace: payload.redirect.status === 303 });
|
|
55
|
+
throw new RedirectSignal(payload.redirect.location, payload.redirect.status);
|
|
56
|
+
}
|
|
57
|
+
if (payload.error) throw reconstructWireError(payload.error);
|
|
58
|
+
throw new HttpStatusError(res.status || 500, `RPC ${fnId} failed`);
|
|
59
|
+
}
|
|
60
|
+
return payload.value;
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Create a lightweight client streaming stub for an `async function*` server workflow.
|
|
66
|
+
* Consumed via `for await (const chunk of streamStub(...args))`:
|
|
67
|
+
* - Streams `application/x-ndjson` frames over standard `fetch()`.
|
|
68
|
+
* - Automatically schedules compiled DOM slot patches on the calling component after each chunk!
|
|
69
|
+
* - Aborts the HTTP stream automatically on component unmount OR `break`/`return` out of `for await`,
|
|
70
|
+
* triggering Hono's `onAbort` -> server `gen.return()` -> backend `finally` cleanup!
|
|
71
|
+
*/
|
|
72
|
+
function createStreamStub(fnId) {
|
|
73
|
+
return function(...args) {
|
|
74
|
+
const callerOwner = _getActiveOwner();
|
|
75
|
+
const ac = new AbortController();
|
|
76
|
+
const onOwnerAbort = () => ac.abort();
|
|
77
|
+
if (callerOwner?.signal.aborted) ac.abort();
|
|
78
|
+
else callerOwner?.signal.addEventListener("abort", onOwnerAbort, { once: true });
|
|
79
|
+
async function* streamGenerator() {
|
|
80
|
+
let yieldedOnce = false;
|
|
81
|
+
try {
|
|
82
|
+
const res = await getFetch()(getRpcUrl(fnId), {
|
|
83
|
+
method: "POST",
|
|
84
|
+
headers: {
|
|
85
|
+
"Content-Type": "application/json",
|
|
86
|
+
Accept: "application/x-ndjson",
|
|
87
|
+
"X-C7T-RPC": "stream"
|
|
88
|
+
},
|
|
89
|
+
credentials: "same-origin",
|
|
90
|
+
body: JSON.stringify({ args }),
|
|
91
|
+
signal: ac.signal
|
|
92
|
+
});
|
|
93
|
+
if (!res.ok && !res.headers.get("content-type")?.includes("application/x-ndjson")) {
|
|
94
|
+
let errBody = null;
|
|
95
|
+
try {
|
|
96
|
+
errBody = await res.json();
|
|
97
|
+
} catch {}
|
|
98
|
+
if (errBody && !errBody.ok && errBody.error) throw reconstructWireError(errBody.error);
|
|
99
|
+
throw new HttpStatusError(res.status, `Stream RPC ${fnId} failed (${res.status})`);
|
|
100
|
+
}
|
|
101
|
+
if (!res.body) return void 0;
|
|
102
|
+
const reader = res.body.getReader();
|
|
103
|
+
const decoder = new TextDecoder();
|
|
104
|
+
let buffer = "";
|
|
105
|
+
try {
|
|
106
|
+
while (true) {
|
|
107
|
+
if (yieldedOnce && !callerOwner?.signal.aborted) callerOwner?.schedule();
|
|
108
|
+
const { done, value } = await reader.read();
|
|
109
|
+
if (done) break;
|
|
110
|
+
buffer += decoder.decode(value, { stream: true });
|
|
111
|
+
let newlineIdx;
|
|
112
|
+
while ((newlineIdx = buffer.indexOf("\n")) !== -1) {
|
|
113
|
+
const line = buffer.slice(0, newlineIdx).trim();
|
|
114
|
+
buffer = buffer.slice(newlineIdx + 1);
|
|
115
|
+
if (!line) continue;
|
|
116
|
+
const frame = JSON.parse(line);
|
|
117
|
+
if (frame.type === "yield") {
|
|
118
|
+
yieldedOnce = true;
|
|
119
|
+
yield frame.value;
|
|
120
|
+
} else if (frame.type === "return") {
|
|
121
|
+
if (yieldedOnce && !callerOwner?.signal.aborted) callerOwner?.schedule();
|
|
122
|
+
return frame.value;
|
|
123
|
+
} else if (frame.type === "error") {
|
|
124
|
+
if (frame.redirect) {
|
|
125
|
+
navigate(frame.redirect.location);
|
|
126
|
+
throw new RedirectSignal(frame.redirect.location, frame.redirect.status);
|
|
127
|
+
}
|
|
128
|
+
if (frame.name === "ValidationError" && frame.issues) throw new ValidationError(frame.issues, frame.message);
|
|
129
|
+
if (frame.status !== void 0) throw new HttpStatusError(frame.status, frame.message);
|
|
130
|
+
const err = new Error(frame.message);
|
|
131
|
+
err.name = frame.name || "StreamError";
|
|
132
|
+
throw err;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
} finally {
|
|
137
|
+
ac.abort();
|
|
138
|
+
try {
|
|
139
|
+
await reader.cancel();
|
|
140
|
+
} catch {}
|
|
141
|
+
}
|
|
142
|
+
return void 0;
|
|
143
|
+
} finally {
|
|
144
|
+
ac.abort();
|
|
145
|
+
callerOwner?.signal.removeEventListener("abort", onOwnerAbort);
|
|
146
|
+
if (yieldedOnce && !callerOwner?.signal.aborted) callerOwner?.schedule();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return streamGenerator();
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Bootstrap c7t on the client:
|
|
154
|
+
* 1. Installs 0-tick `$ref` State Receipt decoding into `@fierst/blokd`.
|
|
155
|
+
* 2. Installs event-delegated Lazy Revival (`installRevival`).
|
|
156
|
+
* 3. Optionally installs persistent nested `<c7t-outlet>` client routing.
|
|
157
|
+
*/
|
|
158
|
+
function installC7t(options = {}) {
|
|
159
|
+
if (options.rpcBase || options.fetch) configureClient({
|
|
160
|
+
rpcBase: options.rpcBase,
|
|
161
|
+
fetch: options.fetch
|
|
162
|
+
});
|
|
163
|
+
const defaultRuntimeUrl = typeof document !== "undefined" && document.querySelector("script[type=\"importmap\"]") ? "@fierst/blokd" : "/@id/@fierst/blokd";
|
|
164
|
+
const uninstallReceipts = installReceiptResolver(options.receiptStore);
|
|
165
|
+
const uninstallRevival = typeof document !== "undefined" ? installRevival(options.runtimeUrl ?? defaultRuntimeUrl) : () => {};
|
|
166
|
+
const uninstallRouter = options.routes ? installClientRouter({
|
|
167
|
+
routes: options.routes,
|
|
168
|
+
errorComponent: options.errorComponent,
|
|
169
|
+
rootElement: options.rootElement,
|
|
170
|
+
initialUrl: options.initialUrl,
|
|
171
|
+
transitions: options.transitions,
|
|
172
|
+
fetch: getFetch(),
|
|
173
|
+
onNavigate: _notifySearchParamsChanged
|
|
174
|
+
}) : () => {};
|
|
175
|
+
return () => {
|
|
176
|
+
uninstallRouter();
|
|
177
|
+
uninstallRevival();
|
|
178
|
+
uninstallReceipts();
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
export { configureClient, createRpcStub, createStreamStub, installC7t, installReceiptResolver };
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// src/env.ts
|
|
2
|
+
let requestEnvReader = null;
|
|
3
|
+
/** @internal Registered by `@fierst/c7t/server` to expose Cloudflare Workers per-request `c.env` bindings. */
|
|
4
|
+
function _setRequestEnvReader(reader) {
|
|
5
|
+
requestEnvReader = reader;
|
|
6
|
+
}
|
|
7
|
+
function validateSyncOrThrow(key, schema, rawVal) {
|
|
8
|
+
const result = schema["~standard"].validate(rawVal);
|
|
9
|
+
if (result && typeof result.then === "function") throw new TypeError(`[c7t env] Environment schema for "${key}" must be synchronous.`);
|
|
10
|
+
const syncResult = result;
|
|
11
|
+
if (syncResult.issues) {
|
|
12
|
+
const details = syncResult.issues.map((i) => i.message).join("; ");
|
|
13
|
+
throw new Error(`[c7t env] Invalid environment variable "${key}": ${details}`);
|
|
14
|
+
}
|
|
15
|
+
return syncResult.value;
|
|
16
|
+
}
|
|
17
|
+
function readRawEnvValue(key, explicit) {
|
|
18
|
+
if (explicit && key in explicit) return explicit[key];
|
|
19
|
+
const cfEnv = requestEnvReader?.();
|
|
20
|
+
if (cfEnv && key in cfEnv) return cfEnv[key];
|
|
21
|
+
if (typeof process !== "undefined" && process.env && key in process.env) return process.env[key];
|
|
22
|
+
const metaEnv = typeof import.meta !== "undefined" ? import.meta.env : void 0;
|
|
23
|
+
if (metaEnv) {
|
|
24
|
+
if (key in metaEnv) return metaEnv[key];
|
|
25
|
+
if (`VITE_${key}` in metaEnv) return metaEnv[`VITE_${key}`];
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Define and validate environment variables across Node (`process.env`),
|
|
30
|
+
* Cloudflare Workers (`req.env` bindings), and Vite (`import.meta.env`) using Standard Schema v1.
|
|
31
|
+
*
|
|
32
|
+
* Accessing any `server` variable inside browser code throws an immediate security error.
|
|
33
|
+
*/
|
|
34
|
+
function defineEnv(options) {
|
|
35
|
+
const serverSchemas = options.server ?? {};
|
|
36
|
+
const publicSchemas = options.public ?? {};
|
|
37
|
+
const isBrowserRuntime = () => typeof window !== "undefined" && typeof document !== "undefined";
|
|
38
|
+
function readValidated(key) {
|
|
39
|
+
if (key in serverSchemas) {
|
|
40
|
+
if (isBrowserRuntime()) throw new Error(`[c7t env] Cannot access server-only environment variable "${key}" in browser code.`);
|
|
41
|
+
const raw = readRawEnvValue(key, options.runtimeEnv);
|
|
42
|
+
return validateSyncOrThrow(key, serverSchemas[key], raw);
|
|
43
|
+
}
|
|
44
|
+
if (key in publicSchemas) {
|
|
45
|
+
const raw = readRawEnvValue(key, options.runtimeEnv);
|
|
46
|
+
return validateSyncOrThrow(key, publicSchemas[key], raw);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function validateAll() {
|
|
50
|
+
for (const key of Object.keys(publicSchemas)) readValidated(key);
|
|
51
|
+
if (!isBrowserRuntime()) for (const key of Object.keys(serverSchemas)) readValidated(key);
|
|
52
|
+
}
|
|
53
|
+
return new Proxy({ validateAll }, {
|
|
54
|
+
get(target, prop) {
|
|
55
|
+
if (typeof prop === "symbol") return void 0;
|
|
56
|
+
if (prop === "validateAll") return target.validateAll;
|
|
57
|
+
return readValidated(prop);
|
|
58
|
+
},
|
|
59
|
+
has(_target, prop) {
|
|
60
|
+
if (typeof prop === "symbol") return false;
|
|
61
|
+
return prop === "validateAll" || prop in serverSchemas || prop in publicSchemas;
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
// src/head.ts
|
|
66
|
+
let serverHeadHook = null;
|
|
67
|
+
/** @internal Installed by `@fierst/c7t/server` to capture `head()` calls per SSR request via AsyncLocalStorage. */
|
|
68
|
+
function _setServerHeadHook(hook) {
|
|
69
|
+
serverHeadHook = hook;
|
|
70
|
+
}
|
|
71
|
+
const PROPERTY_PREFIXES = [
|
|
72
|
+
"og:",
|
|
73
|
+
"article:",
|
|
74
|
+
"book:",
|
|
75
|
+
"profile:",
|
|
76
|
+
"music:",
|
|
77
|
+
"video:"
|
|
78
|
+
];
|
|
79
|
+
function metaAttrKind(key) {
|
|
80
|
+
return PROPERTY_PREFIXES.some((p) => key.startsWith(p)) ? "property" : "name";
|
|
81
|
+
}
|
|
82
|
+
function applyHeadToState(state, config) {
|
|
83
|
+
if (config.title !== void 0) state.title = config.title;
|
|
84
|
+
if (config.canonical !== void 0) state.canonical = config.canonical;
|
|
85
|
+
if (config.description !== void 0) state.meta.set("description", {
|
|
86
|
+
attr: "name",
|
|
87
|
+
content: config.description
|
|
88
|
+
});
|
|
89
|
+
if (config.meta) for (const [key, val] of Object.entries(config.meta)) if (val === null || val === void 0) state.meta.delete(key);
|
|
90
|
+
else state.meta.set(key, {
|
|
91
|
+
attr: metaAttrKind(key),
|
|
92
|
+
content: val
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
function escapeHtmlAttr(str) {
|
|
96
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
97
|
+
}
|
|
98
|
+
function renderCollectedHeadTags(state) {
|
|
99
|
+
const parts = [];
|
|
100
|
+
for (const [key, { attr, content }] of state.meta.entries()) parts.push(`<meta ${attr}="${escapeHtmlAttr(key)}" content="${escapeHtmlAttr(content)}" />`);
|
|
101
|
+
if (state.canonical) parts.push(`<link rel="canonical" href="${escapeHtmlAttr(state.canonical)}" />`);
|
|
102
|
+
return parts.join("");
|
|
103
|
+
}
|
|
104
|
+
function upsertClientMeta(key, val) {
|
|
105
|
+
const attr = metaAttrKind(key);
|
|
106
|
+
const selector = `meta[${attr}=${JSON.stringify(key)}]`;
|
|
107
|
+
const existing = document.head.querySelector(selector);
|
|
108
|
+
if (val === null || val === void 0) {
|
|
109
|
+
existing?.remove();
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (existing) {
|
|
113
|
+
if (existing.content !== val) existing.content = val;
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const meta = document.createElement("meta");
|
|
117
|
+
meta.setAttribute(attr, key);
|
|
118
|
+
meta.content = val;
|
|
119
|
+
document.head.appendChild(meta);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Set page `<title>`, `<meta>`, and `<link rel="canonical">` inline inside any layout or route generator.
|
|
123
|
+
* - **During SSR:** Merges outer-to-inner across matched layouts and routes into `<head>`.
|
|
124
|
+
* - **On Client Navigation:** Updates `document.title` and `<head>` tags in place.
|
|
125
|
+
*/
|
|
126
|
+
function head(config) {
|
|
127
|
+
if (serverHeadHook?.(config)) return;
|
|
128
|
+
if (typeof document === "undefined") return;
|
|
129
|
+
if (config.title !== void 0 && document.title !== config.title) document.title = config.title;
|
|
130
|
+
if (config.description !== void 0) upsertClientMeta("description", config.description);
|
|
131
|
+
if (config.canonical !== void 0) {
|
|
132
|
+
let link = document.head.querySelector("link[rel=\"canonical\"]");
|
|
133
|
+
if (!link) {
|
|
134
|
+
link = document.createElement("link");
|
|
135
|
+
link.rel = "canonical";
|
|
136
|
+
document.head.appendChild(link);
|
|
137
|
+
}
|
|
138
|
+
if (link.href !== config.canonical) link.setAttribute("href", config.canonical);
|
|
139
|
+
}
|
|
140
|
+
if (config.meta) for (const [k, v] of Object.entries(config.meta)) upsertClientMeta(k, v);
|
|
141
|
+
}
|
|
142
|
+
export { _setRequestEnvReader as a, renderCollectedHeadTags as i, applyHeadToState as n, defineEnv as o, head as r, _setServerHeadHook as t };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { a as ServerCall, c as ValidationError, d as httpError, f as notFound, i as RpcWireResponse, l as all, m as unauthorized, n as InferCallValue, o as StandardSchemaV1, p as redirect, r as RedirectSignal, s as StreamWireFrame, t as HttpStatusError, u as forbidden } from "./protocol-B6QOAMGj.mjs";
|
|
2
|
+
import { C as matchNestedRoutes, S as installClientRouter, T as useRoute, _ as buildApiRoutes, a as CompiledApiRoute, b as c7tRouteContext, c as ExtractRouteParams, d as MatchedSegment, f as NestedRouteMatch, h as RouteProps, l as HttpMethod, m as RouteModuleEntry, n as BuildRoutesOptions, o as CompiledRoute, p as Outlet, r as C7tRouteInfo, s as CsrMode, t as ApiRouteHandler, v as buildMatchedRouteView, w as navigate, y as buildRoutes } from "./router-19ZZ3woS.mjs";
|
|
3
|
+
import { ComponentFn, Context, Ctx, ErrorBoundary, Provider, Signal, Signal as Signal$1, View, createContext, provide, signal, useContext } from "@fierst/blokd";
|
|
4
|
+
type EnvSchemaMap = Record<string, StandardSchemaV1<any, any>>;
|
|
5
|
+
type InferEnvMap<TMap extends EnvSchemaMap> = { readonly [K in keyof TMap]: StandardSchemaV1.InferOutput<TMap[K]>; };
|
|
6
|
+
interface DefineEnvOptions<TServer extends EnvSchemaMap = {}, TPublic extends EnvSchemaMap = {}> {
|
|
7
|
+
/** Server-only secrets (throws immediately if accessed in browser code!) */
|
|
8
|
+
server?: TServer;
|
|
9
|
+
/** Public configuration accessible on both server and client */
|
|
10
|
+
public?: TPublic;
|
|
11
|
+
/** Optional explicit source dictionary (overrides `req.env` / `process.env` / `import.meta.env`) */
|
|
12
|
+
runtimeEnv?: Record<string, unknown>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Define and validate environment variables across Node (`process.env`),
|
|
16
|
+
* Cloudflare Workers (`req.env` bindings), and Vite (`import.meta.env`) using Standard Schema v1.
|
|
17
|
+
*
|
|
18
|
+
* Accessing any `server` variable inside browser code throws an immediate security error.
|
|
19
|
+
*/
|
|
20
|
+
export declare function defineEnv<TServer extends EnvSchemaMap = {}, TPublic extends EnvSchemaMap = {}>(options: DefineEnvOptions<TServer, TPublic>): InferEnvMap<TServer> & InferEnvMap<TPublic> & {
|
|
21
|
+
validateAll(): void;
|
|
22
|
+
};
|
|
23
|
+
interface HeadConfig {
|
|
24
|
+
/** Sets `<title>` on SSR and `document.title` on client navigation */
|
|
25
|
+
title?: string;
|
|
26
|
+
/** Shorthand for `<meta name="description" content="...">` */
|
|
27
|
+
description?: string;
|
|
28
|
+
/** Canonical URL `<link rel="canonical" href="...">` */
|
|
29
|
+
canonical?: string;
|
|
30
|
+
/**
|
|
31
|
+
* Key-value `<meta>` tags.
|
|
32
|
+
* Keys starting with `og:`, `article:`, `book:`, `profile:`, `music:`, or `video:` emit `property="..."`;
|
|
33
|
+
* all other keys (e.g. `twitter:card`, `theme-color`, `robots`) emit `name="..."`.
|
|
34
|
+
* Passing `null` or `undefined` removes a previously set tag.
|
|
35
|
+
*/
|
|
36
|
+
meta?: Record<string, string | null | undefined>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Set page `<title>`, `<meta>`, and `<link rel="canonical">` inline inside any layout or route generator.
|
|
40
|
+
* - **During SSR:** Merges outer-to-inner across matched layouts and routes into `<head>`.
|
|
41
|
+
* - **On Client Navigation:** Updates `document.title` and `<head>` tags in place.
|
|
42
|
+
*/
|
|
43
|
+
export declare function head(config: HeadConfig): void;
|
|
44
|
+
interface SearchParamOptions<T> {
|
|
45
|
+
/** `'replace'` (default, ideal for typing/filtering) or `'push'` (creates browser Back entry) */
|
|
46
|
+
history?: "replace" | "push";
|
|
47
|
+
parse?: (raw: string) => T;
|
|
48
|
+
serialize?: (value: T) => string;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Create a reactive `Signal<T>` synchronized with a URL query parameter (`?key=...`).
|
|
52
|
+
*
|
|
53
|
+
* Works directly with Blokd two-way bindings (`<input bind:value={q} />`, `<input type="checkbox" bind:checked={done} />`)!
|
|
54
|
+
* - **During SSR:** Reads initial value from the request URL search params.
|
|
55
|
+
* - **On Client:** Updates reactive DOM slots immediately and syncs `window.location.search`
|
|
56
|
+
* cleanly (removing the parameter when equal to `defaultValue`).
|
|
57
|
+
*/
|
|
58
|
+
export declare function searchParam<T extends string | number | boolean>(key: string, defaultValue: T, options?: SearchParamOptions<T>): Signal$1<T>;
|
|
59
|
+
/**
|
|
60
|
+
* Define a server boundary function or `async function*` streaming workflow.
|
|
61
|
+
*
|
|
62
|
+
* - **Inside components (`function*` / `async function*`):** `const data = yield* myFn(arg)`
|
|
63
|
+
* executes on the server during SSR, records a deterministic State Receipt, and revives
|
|
64
|
+
* synchronously in **0 microtasks** on the client!
|
|
65
|
+
* - **Inside event handlers (`onSubmit`, `onClick`):** `const saved = await myFn(arg)`
|
|
66
|
+
* invokes `POST /_c7t/rpc/:id` directly!
|
|
67
|
+
* - **Streaming workflows (`async function*`):** `for await (const chunk of myStream(arg))`
|
|
68
|
+
* streams NDJSON chunks and aborts automatically on unmount!
|
|
69
|
+
*
|
|
70
|
+
* When built with `@fierst/c7t/vite`, server bodies and server-only imports are automatically
|
|
71
|
+
* stripped from client bundles and replaced with tiny RPC/stream stubs.
|
|
72
|
+
*/
|
|
73
|
+
export declare function server<TArgs extends unknown[], TYield, TReturn = void>(fn: (...args: TArgs) => AsyncGenerator<TYield, TReturn, any>): (...args: TArgs) => AsyncGenerator<TYield, TReturn, void>;
|
|
74
|
+
export declare function server<TSchema extends StandardSchemaV1, TYield, TReturn = void>(schema: TSchema, fn: (input: StandardSchemaV1.InferOutput<TSchema>) => AsyncGenerator<TYield, TReturn, any>): (input: StandardSchemaV1.InferInput<TSchema>) => AsyncGenerator<TYield, TReturn, void>;
|
|
75
|
+
export declare function server<TSchema extends StandardSchemaV1, TReturn>(schema: TSchema, fn: (input: StandardSchemaV1.InferOutput<TSchema>) => TReturn | Promise<TReturn>): (input: StandardSchemaV1.InferInput<TSchema>) => ServerCall<Awaited<TReturn>>;
|
|
76
|
+
export declare function server<TArgs extends unknown[], TReturn>(fn: (...args: TArgs) => TReturn | Promise<TReturn>): (...args: TArgs) => ServerCall<Awaited<TReturn>>;
|
|
77
|
+
export { type ApiRouteHandler, type BuildRoutesOptions, type C7tRouteInfo, type CompiledApiRoute, type CompiledRoute, type ComponentFn, type Context, type CsrMode, type Ctx, type DefineEnvOptions, type EnvSchemaMap, ErrorBoundary, type ExtractRouteParams, type HeadConfig, type HttpMethod, HttpStatusError, type InferCallValue, type MatchedSegment, type NestedRouteMatch, Outlet, Provider, RedirectSignal, type RouteModuleEntry, type RouteProps, type RpcWireResponse, type SearchParamOptions, type ServerCall, type Signal, type StandardSchemaV1, type StreamWireFrame, ValidationError, type View, all, buildApiRoutes, buildMatchedRouteView, buildRoutes, c7tRouteContext, createContext, forbidden, httpError, installClientRouter, matchNestedRoutes, navigate, notFound, provide, redirect, signal, unauthorized, useContext, useRoute };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { o as defineEnv, r as head } from "./head-CUiNFY7Q.mjs";
|
|
2
|
+
import { a as createServerCall, c as isStandardSchema, d as unauthorized, f as validateSchema, i as all, l as notFound, n as RedirectSignal, o as forbidden, r as ValidationError, s as httpError, t as HttpStatusError, u as redirect } from "./protocol-CZANZJ5x.mjs";
|
|
3
|
+
import { a as c7tRouteContext, c as matchNestedRoutes, i as buildRoutes, l as navigate, n as buildApiRoutes, r as buildMatchedRouteView, s as installClientRouter, t as Outlet, u as useRoute } from "./router-B50LekA_.mjs";
|
|
4
|
+
import { n as searchParam } from "./search-params-C03mU47i.mjs";
|
|
5
|
+
import { ErrorBoundary, Provider, createContext, provide, signal, useContext } from "@fierst/blokd";
|
|
6
|
+
// src/index.ts
|
|
7
|
+
let fallbackSeq = 0;
|
|
8
|
+
function isAsyncGenFn(fn) {
|
|
9
|
+
return fn?.constructor?.name === "AsyncGeneratorFunction";
|
|
10
|
+
}
|
|
11
|
+
function server(schemaOrFn, maybeFn) {
|
|
12
|
+
const hasSchema = isStandardSchema(schemaOrFn);
|
|
13
|
+
const schema = hasSchema ? schemaOrFn : void 0;
|
|
14
|
+
const rawFn = hasSchema ? maybeFn : schemaOrFn;
|
|
15
|
+
const localId = `c7t_local_${++fallbackSeq}_${rawFn?.name || "anon"}`;
|
|
16
|
+
if (isAsyncGenFn(rawFn)) return async function* (...args) {
|
|
17
|
+
const finalArgs = schema ? [await validateSchema(schema, args[0])] : args;
|
|
18
|
+
return yield* rawFn(...finalArgs);
|
|
19
|
+
};
|
|
20
|
+
return (...args) => createServerCall(localId, args, async () => {
|
|
21
|
+
const finalArgs = schema ? [await validateSchema(schema, args[0])] : args;
|
|
22
|
+
return rawFn(...finalArgs);
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
export { ErrorBoundary, HttpStatusError, Outlet, Provider, RedirectSignal, ValidationError, all, buildApiRoutes, buildMatchedRouteView, buildRoutes, c7tRouteContext, createContext, defineEnv, forbidden, head, httpError, installClientRouter, matchNestedRoutes, navigate, notFound, provide, redirect, searchParam, server, signal, unauthorized, useContext, useRoute };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// src/multipart.ts
|
|
2
|
+
function isBlobLike(val) {
|
|
3
|
+
return typeof Blob !== "undefined" && val instanceof Blob;
|
|
4
|
+
}
|
|
5
|
+
function isFormDataLike(val) {
|
|
6
|
+
return typeof FormData !== "undefined" && val instanceof FormData;
|
|
7
|
+
}
|
|
8
|
+
function containsBinaryData(val) {
|
|
9
|
+
if (!val || typeof val !== "object") return false;
|
|
10
|
+
if (isBlobLike(val) || isFormDataLike(val)) return true;
|
|
11
|
+
if (Array.isArray(val)) return val.some(containsBinaryData);
|
|
12
|
+
const proto = Object.getPrototypeOf(val);
|
|
13
|
+
if (proto === null || proto === Object.prototype) return Object.values(val).some(containsBinaryData);
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
function encodeMultipartRpcArgs(args) {
|
|
17
|
+
const fd = new FormData();
|
|
18
|
+
let blobIdx = 0;
|
|
19
|
+
function replaceBlobs(val) {
|
|
20
|
+
if (isBlobLike(val)) {
|
|
21
|
+
const partName = `__c7t_b${blobIdx++}`;
|
|
22
|
+
if (typeof File !== "undefined" && val instanceof File) fd.append(partName, val, val.name);
|
|
23
|
+
else fd.append(partName, val);
|
|
24
|
+
return { $c7tBlob: partName };
|
|
25
|
+
}
|
|
26
|
+
if (isFormDataLike(val)) {
|
|
27
|
+
const entries = [];
|
|
28
|
+
val.forEach((v, k) => {
|
|
29
|
+
entries.push([k, replaceBlobs(v)]);
|
|
30
|
+
});
|
|
31
|
+
return { $c7tFormData: entries };
|
|
32
|
+
}
|
|
33
|
+
if (Array.isArray(val)) return val.map(replaceBlobs);
|
|
34
|
+
if (val && typeof val === "object") {
|
|
35
|
+
const proto = Object.getPrototypeOf(val);
|
|
36
|
+
if (proto === null || proto === Object.prototype) {
|
|
37
|
+
const out = {};
|
|
38
|
+
for (const [k, v] of Object.entries(val)) out[k] = replaceBlobs(v);
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return val;
|
|
43
|
+
}
|
|
44
|
+
const manifest = args.map(replaceBlobs);
|
|
45
|
+
fd.append("__c7t_args__", JSON.stringify(manifest));
|
|
46
|
+
return fd;
|
|
47
|
+
}
|
|
48
|
+
function decodeMultipartRpcArgs(fd) {
|
|
49
|
+
const rawManifest = fd.get("__c7t_args__");
|
|
50
|
+
if (typeof rawManifest !== "string") throw new Error("Missing __c7t_args__ manifest in multipart RPC payload");
|
|
51
|
+
const parsed = JSON.parse(rawManifest);
|
|
52
|
+
function restoreBlobs(val) {
|
|
53
|
+
if (!val || typeof val !== "object") return val;
|
|
54
|
+
if (Array.isArray(val)) return val.map(restoreBlobs);
|
|
55
|
+
const rec = val;
|
|
56
|
+
if (typeof rec.$c7tBlob === "string" && Object.keys(rec).length === 1) return fd.get(rec.$c7tBlob);
|
|
57
|
+
if (Array.isArray(rec.$c7tFormData) && Object.keys(rec).length === 1) {
|
|
58
|
+
const innerFd = new FormData();
|
|
59
|
+
for (const [k, v] of rec.$c7tFormData) {
|
|
60
|
+
const restored = restoreBlobs(v);
|
|
61
|
+
if (isBlobLike(restored)) innerFd.append(k, restored);
|
|
62
|
+
else innerFd.append(k, typeof restored === "string" ? restored : JSON.stringify(restored ?? ""));
|
|
63
|
+
}
|
|
64
|
+
return innerFd;
|
|
65
|
+
}
|
|
66
|
+
const out = {};
|
|
67
|
+
for (const [k, v] of Object.entries(rec)) out[k] = restoreBlobs(v);
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
return parsed.map(restoreBlobs);
|
|
71
|
+
}
|
|
72
|
+
export { decodeMultipartRpcArgs as n, encodeMultipartRpcArgs as r, containsBinaryData as t };
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { StepEffect } from "@fierst/blokd";
|
|
2
|
+
interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
3
|
+
readonly "~standard": StandardSchemaV1.Props<Input, Output>;
|
|
4
|
+
}
|
|
5
|
+
declare namespace StandardSchemaV1 {
|
|
6
|
+
interface Props<Input = unknown, Output = Input> {
|
|
7
|
+
readonly version: 1;
|
|
8
|
+
readonly vendor: string;
|
|
9
|
+
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
|
|
10
|
+
readonly types?: Types<Input, Output> | undefined;
|
|
11
|
+
}
|
|
12
|
+
type Result<Output> = SuccessResult<Output> | FailureResult;
|
|
13
|
+
interface SuccessResult<Output> {
|
|
14
|
+
readonly value: Output;
|
|
15
|
+
readonly issues?: undefined;
|
|
16
|
+
}
|
|
17
|
+
interface FailureResult {
|
|
18
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
19
|
+
}
|
|
20
|
+
interface Issue {
|
|
21
|
+
readonly message: string;
|
|
22
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
|
23
|
+
}
|
|
24
|
+
interface PathSegment {
|
|
25
|
+
readonly key: PropertyKey;
|
|
26
|
+
}
|
|
27
|
+
interface Types<Input = unknown, Output = Input> {
|
|
28
|
+
readonly input: Input;
|
|
29
|
+
readonly output: Output;
|
|
30
|
+
}
|
|
31
|
+
type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
|
|
32
|
+
type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
|
|
33
|
+
}
|
|
34
|
+
declare class RedirectSignal extends Error {
|
|
35
|
+
readonly __c7tControlFlow = true;
|
|
36
|
+
readonly location: string;
|
|
37
|
+
readonly status: 301 | 302 | 303 | 307 | 308;
|
|
38
|
+
constructor(location: string, status?: 301 | 302 | 303 | 307 | 308);
|
|
39
|
+
}
|
|
40
|
+
declare function redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): RedirectSignal;
|
|
41
|
+
declare class HttpStatusError extends Error {
|
|
42
|
+
readonly __c7tControlFlow: boolean;
|
|
43
|
+
readonly status: number;
|
|
44
|
+
readonly data?: unknown;
|
|
45
|
+
constructor(status: number, message?: string, data?: unknown, isControlFlow?: boolean);
|
|
46
|
+
}
|
|
47
|
+
declare function httpError(status: number, message?: string, data?: unknown): HttpStatusError;
|
|
48
|
+
declare function notFound(message?: string): HttpStatusError;
|
|
49
|
+
declare function unauthorized(message?: string): HttpStatusError;
|
|
50
|
+
declare function forbidden(message?: string): HttpStatusError;
|
|
51
|
+
declare class ValidationError extends Error {
|
|
52
|
+
#private;
|
|
53
|
+
readonly status = 400;
|
|
54
|
+
readonly issues: readonly StandardSchemaV1.Issue[];
|
|
55
|
+
constructor(issues: readonly StandardSchemaV1.Issue[], message?: string);
|
|
56
|
+
/**
|
|
57
|
+
* Flat map of field dot-paths to their first validation message
|
|
58
|
+
* (e.g. `{ title: "Title must be at least 2 characters" }`, or `_root` for top-level issues).
|
|
59
|
+
*/
|
|
60
|
+
get fields(): Record<string, string>;
|
|
61
|
+
}
|
|
62
|
+
type RpcWireResponse<T = unknown> = {
|
|
63
|
+
readonly ok: true;
|
|
64
|
+
readonly value: T;
|
|
65
|
+
} | {
|
|
66
|
+
readonly ok: false;
|
|
67
|
+
readonly redirect?: {
|
|
68
|
+
readonly location: string;
|
|
69
|
+
readonly status: number;
|
|
70
|
+
};
|
|
71
|
+
readonly error?: {
|
|
72
|
+
readonly name: string;
|
|
73
|
+
readonly message: string;
|
|
74
|
+
readonly status?: number;
|
|
75
|
+
readonly data?: unknown;
|
|
76
|
+
readonly issues?: readonly StandardSchemaV1.Issue[];
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
type StreamWireFrame<TYield = unknown, TReturn = unknown> = {
|
|
80
|
+
readonly type: "yield";
|
|
81
|
+
readonly value: TYield;
|
|
82
|
+
} | {
|
|
83
|
+
readonly type: "return";
|
|
84
|
+
readonly value: TReturn;
|
|
85
|
+
} | {
|
|
86
|
+
readonly type: "error";
|
|
87
|
+
readonly name: string;
|
|
88
|
+
readonly message: string;
|
|
89
|
+
readonly status?: number;
|
|
90
|
+
readonly issues?: readonly StandardSchemaV1.Issue[];
|
|
91
|
+
readonly redirect?: {
|
|
92
|
+
readonly location: string;
|
|
93
|
+
readonly status: number;
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
declare const CALL_META: unique symbol;
|
|
97
|
+
interface ServerCallMeta<T = unknown> {
|
|
98
|
+
readonly id: string;
|
|
99
|
+
readonly args: readonly unknown[];
|
|
100
|
+
readonly execute: (signal?: AbortSignal) => T | Promise<T>;
|
|
101
|
+
}
|
|
102
|
+
interface ServerCall<T> extends PromiseLike<T> {
|
|
103
|
+
readonly [CALL_META]: ServerCallMeta<T>;
|
|
104
|
+
[Symbol.iterator](): Generator<StepEffect<T>, T, any>;
|
|
105
|
+
[Symbol.asyncIterator](): AsyncGenerator<StepEffect<T>, T, any>;
|
|
106
|
+
catch<TResult = never>(onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<T | TResult>;
|
|
107
|
+
finally(onfinally?: (() => void) | null): Promise<T>;
|
|
108
|
+
}
|
|
109
|
+
type InferCallValue<C> = C extends ServerCall<infer T> ? T : C extends PromiseLike<infer P> ? P : never;
|
|
110
|
+
/**
|
|
111
|
+
* Execute multiple `ServerCall` steps concurrently (`Promise.all` on SSR / live navigation)
|
|
112
|
+
* while recording a single deterministic tuple receipt that revives in 0 ticks on the client.
|
|
113
|
+
*/
|
|
114
|
+
declare function all<const TCalls extends readonly ServerCall<any>[]>(calls: TCalls): ServerCall<{ -readonly [K in keyof TCalls]: InferCallValue<TCalls[K]>; }>;
|
|
115
|
+
export { ServerCall as a, ValidationError as c, httpError as d, notFound as f, RpcWireResponse as i, all as l, unauthorized as m, InferCallValue as n, StandardSchemaV1 as o, redirect as p, RedirectSignal as r, StreamWireFrame as s, HttpStatusError as t, forbidden as u };
|