flamefront 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -3,19 +3,30 @@
3
3
  Flamefront brings routing, server rendering, and static pages to Octane.
4
4
  One route list connects your pages to the server, browser router, and build.
5
5
 
6
+ Use only the rendering your project needs. Pre-rendering, server-side rendering
7
+ (SSR), and client-side rendering (CSR) are available as requirements evolve;
8
+ you do not need to use all three to benefit. The same framework can serve
9
+ many or all of your Octane projects, even when each uses a different mode.
10
+
6
11
  ## Why try it?
7
12
 
8
13
  - **Render each page where it makes sense.** On the server, at build time, or
9
14
  in the browser.
10
15
  - **React Router-style loaders.** Load data beside your page component and read
11
16
  it with `useLoaderData`.
17
+ - **Typed server actions and forms.** Call validated server functions from
18
+ browser code, or use forms that work without JavaScript and gain pending
19
+ states and loader refreshes when enhanced. [Add a mutation](./docs/forms-and-mutations.md).
20
+ - **Reuse unchanged static pages between builds.** Cache prerendered content and regenerate the deployment output on each build.
21
+ [Enable incremental prerendering](./docs/incremental-prerendering.md).
12
22
  - **Shared layouts.** Keep navigation and shared UI in place as pages change.
13
23
  - **Persistent shell state.** Keep players running, uploads progressing, and
14
24
  other shared UI state intact between pages without making the whole app
15
25
  client-rendered.
16
- - **Control interactivity.** Activate a page immediately, when it becomes
17
- visible, or when someone interacts with it.
18
- - **Markdown routes.** Use Markdown and MDX files as pages.
26
+ - **Choose when parts of a page become interactive.** Defer hydration until
27
+ needed—for example, when content becomes visible or someone interacts with it.
28
+ - **Write pages in Markdown or MDX.** Include them alongside your Octane
29
+ components in the route list.
19
30
 
20
31
  ## One route list
21
32
 
@@ -37,16 +48,27 @@ and chooses how it renders.
37
48
 
38
49
  ## Quickstart
39
50
 
40
- [Try the included app](./docs/getting-started.md): build a static page, inspect
41
- its generated HTML, and serve it locally. Then [create your own app](./docs/create-app.md).
51
+ Create and start an app with Node.js 26 or newer:
52
+
53
+ ```sh
54
+ pnpm create flamefront@latest my-app
55
+ cd my-app
56
+ pnpm dev
57
+ ```
58
+
59
+ See [Create a one-page app](./docs/create-app.md) for the generated files and
60
+ how the server-rendered route works. To evaluate Flamefront without creating a
61
+ project, [try the included app](./docs/getting-started.md).
42
62
 
43
63
  ## Before you try it
44
64
 
45
- Flamefront is an early alpha and requires Node.js 26+. Expect changes before
46
- 1.0. Follow the setup guide for matching packages.
65
+ Flamefront is an early alpha and requires Node.js 26+. Octane, Vite, and
66
+ `@octanejs/remix-router` are required peer dependencies. Follow the
67
+ [setup guide](./docs/create-app.md) for matching packages. Expect changes before 1.0.
47
68
 
48
- There is no built-in form action or mutation API yet. If your current framework
49
- already covers your needs, there's no need to switch.
69
+ Flamefront supports [server actions and forms](./docs/forms-and-mutations.md).
70
+ Static-only hosting still needs a server-backed route or an application-owned
71
+ endpoint for writes.
50
72
 
51
73
  Licensed under [MIT](./LICENSE.md).
52
74
 
@@ -54,5 +76,6 @@ Licensed under [MIT](./LICENSE.md).
54
76
 
55
77
  - [How Flamefront fits](./docs/index.md)
56
78
  - [Route rendering and data](./docs/routes.md)
79
+ - [Forms and mutations](./docs/forms-and-mutations.md)
57
80
  - [Build and deployment](./docs/deployment.md)
58
81
  - [Migrating an existing app](./docs/brownfield-migration.md)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flamefront",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "private": false,
5
5
  "description": "Typed centralized route manifests for Octane.",
6
6
  "license": "MIT",
@@ -21,6 +21,7 @@
21
21
  "type": "module",
22
22
  "exports": {
23
23
  ".": "./src/index.ts",
24
+ "./action-client": "./src/action-client.ts",
24
25
  "./entry": "./src/entry.ts",
25
26
  "./fetch": "./src/fetch.ts",
26
27
  "./fragment": "./src/fragment.tsx",
@@ -32,6 +33,7 @@
32
33
  "./server": "./src/server.ts",
33
34
  "./output": "./src/output.ts",
34
35
  "./srvx": "./src/srvx.ts",
36
+ "./prerender": "./src/prerender.ts",
35
37
  "./vite": "./src/vite.ts"
36
38
  },
37
39
  "scripts": {
@@ -54,6 +56,7 @@
54
56
  "@babel/types": "^8.0.5",
55
57
  "@remix-run/route-pattern": "^0.24.0",
56
58
  "babel-dead-code-elimination": "^2.0.0",
59
+ "devalue": "^5.8.2",
57
60
  "satteri": "^0.10.5",
58
61
  "srvx": "^1.0.4",
59
62
  "vite-plugin-satteri": "^0.3.5"
@@ -80,10 +83,5 @@
80
83
  "@octanejs/remix-router": ">=0.1.48",
81
84
  "octane": ">=0.2.7",
82
85
  "vite": ">=8.3.0"
83
- },
84
- "peerDependenciesMeta": {
85
- "@octanejs/remix-router": {
86
- "optional": true
87
- }
88
86
  }
89
87
  }
@@ -0,0 +1,187 @@
1
+ import * as devalue from "devalue"
2
+ import { data } from "@octanejs/remix-router"
3
+ import {
4
+ actionProtocolEnvelope,
5
+ actionResponseInit,
6
+ type ActionEnvelope,
7
+ type ActionFunction,
8
+ } from "./action.ts"
9
+ import {
10
+ invalidateRouteDataCache,
11
+ type RouteDataRoutingOptions,
12
+ } from "./route-data-client.ts"
13
+ import { invalidateRouteFragments } from "./fragment-client.ts"
14
+
15
+ export interface ActionRequestOptions extends RouteDataRoutingOptions {
16
+ readonly signal?: AbortSignal
17
+ /** Return router data helpers for page action submissions. */
18
+ readonly router?: boolean
19
+ }
20
+
21
+ function resolveOrigin(url: string | URL): URL {
22
+ const browserOrigin =
23
+ typeof location === "undefined" ? undefined : location.origin
24
+
25
+ if (!browserOrigin && typeof url === "string" && !URL.canParse(url)) {
26
+ throw new TypeError(
27
+ "flamefront action requests require an absolute URL outside the browser.",
28
+ )
29
+ }
30
+
31
+ return new URL(url, browserOrigin)
32
+ }
33
+
34
+ function actionEndpoint(
35
+ routing: RouteDataRoutingOptions,
36
+ origin: string | URL,
37
+ ): URL {
38
+ return new URL(
39
+ routing.dataPath ?? "/__flamefront/data",
40
+ resolveOrigin(origin).origin,
41
+ )
42
+ }
43
+
44
+ function isRedirect(response: Response): boolean {
45
+ return response.status >= 300 && response.status < 400
46
+ }
47
+
48
+ function headersFromEnvelope(envelope: ActionEnvelope): Headers | undefined {
49
+ return envelope.headers.length > 0
50
+ ? new Headers(
51
+ envelope.headers.map(
52
+ ([name, value]) => [name, value] as [string, string],
53
+ ),
54
+ )
55
+ : undefined
56
+ }
57
+
58
+ function actionError(envelope: ActionEnvelope): Error {
59
+ const serialized = envelope.error
60
+ const error = new Error(
61
+ serialized?.message ?? "Flamefront action request failed.",
62
+ )
63
+
64
+ error.name = serialized?.name ?? "ActionError"
65
+ Object.defineProperty(error, "status", {
66
+ configurable: true,
67
+ enumerable: true,
68
+ value: envelope.status,
69
+ })
70
+
71
+ if (serialized?.issues) {
72
+ Object.defineProperty(error, "issues", {
73
+ configurable: false,
74
+ enumerable: true,
75
+ value: serialized.issues,
76
+ })
77
+ }
78
+
79
+ return error
80
+ }
81
+
82
+ async function decodeActionResponse(
83
+ response: Response,
84
+ options: ActionRequestOptions,
85
+ ): Promise<unknown> {
86
+ if (isRedirect(response)) {
87
+ invalidateRouteDataCache()
88
+ invalidateRouteFragments()
89
+ throw response
90
+ }
91
+
92
+ const contentType = response.headers.get("Content-Type") ?? ""
93
+
94
+ if (
95
+ !contentType
96
+ .toLowerCase()
97
+ .includes("application/vnd.flamefront.action+devalue")
98
+ ) {
99
+ if (response.ok) {
100
+ invalidateRouteDataCache()
101
+ invalidateRouteFragments()
102
+ }
103
+
104
+ return response
105
+ }
106
+
107
+ let value: unknown
108
+
109
+ try {
110
+ value = devalue.parse(await response.text())
111
+ } catch (error) {
112
+ throw new Error(
113
+ `flamefront action request returned an invalid response (${response.status}).`,
114
+ { cause: error },
115
+ )
116
+ }
117
+
118
+ if (!actionProtocolEnvelope(value)) {
119
+ throw new Error("flamefront action response has an invalid protocol.")
120
+ }
121
+
122
+ const headers = headersFromEnvelope(value)
123
+ const init = actionResponseInit(value)
124
+
125
+ if (value.type === "error") {
126
+ if (options.router && value.value !== undefined) {
127
+ throw data(value.value, init)
128
+ }
129
+
130
+ throw actionError(value)
131
+ }
132
+
133
+ if (value.status >= 200 && value.status < 300) {
134
+ invalidateRouteDataCache()
135
+ invalidateRouteFragments()
136
+ }
137
+
138
+ if (options.router && (value.status !== 200 || headers)) {
139
+ return data(value.value, init)
140
+ }
141
+
142
+ return value.value
143
+ }
144
+
145
+ /** Call a generated action proxy from browser code. */
146
+ export function createActionProxy<
147
+ Args extends readonly unknown[] = readonly unknown[],
148
+ Result = unknown,
149
+ >(
150
+ actionId: string,
151
+ routing: RouteDataRoutingOptions = {},
152
+ ): ActionFunction<Args, Result> {
153
+ return (async (...args: Args): Promise<Result> => {
154
+ const endpoint = actionEndpoint(routing, location.href)
155
+
156
+ endpoint.searchParams.set("action", actionId)
157
+ const response = await globalThis.fetch(endpoint, {
158
+ method: "POST",
159
+ credentials: "same-origin",
160
+ redirect: "manual",
161
+ headers: {
162
+ "Content-Type": "application/vnd.flamefront.action+devalue",
163
+ Accept: "application/vnd.flamefront.action+devalue",
164
+ },
165
+ body: devalue.stringify(args),
166
+ })
167
+
168
+ return (await decodeActionResponse(response, {})) as Result
169
+ }) as ActionFunction<Args, Result>
170
+ }
171
+
172
+ /** Submit a page action request from the generated router action binding. */
173
+ export async function submitRouteAction(
174
+ { request }: { readonly request: Request },
175
+ options: ActionRequestOptions = {},
176
+ ): Promise<unknown> {
177
+ const url = new URL(request.url)
178
+
179
+ url.searchParams.set("__flamefront_action", "1")
180
+ const source = request.clone()
181
+ const response = await globalThis.fetch(new Request(url, source), {
182
+ redirect: "manual",
183
+ credentials: "same-origin",
184
+ })
185
+
186
+ return decodeActionResponse(response, { ...options, router: true })
187
+ }
@@ -0,0 +1,258 @@
1
+ import { createHash } from "node:crypto"
2
+ import { stringLiteral } from "@babel/types"
3
+ import { generate, parse, traverse, type Babel } from "./babel.ts"
4
+ import type { NormalizedRoutingOptions } from "./index.ts"
5
+
6
+ export interface ActionExport {
7
+ readonly exportedName: string
8
+ readonly localName: string
9
+ readonly id: string
10
+ readonly call: Babel.CallExpression
11
+ }
12
+
13
+ export interface ActionModuleTransform {
14
+ readonly code: string
15
+ readonly map: unknown
16
+ readonly actions: readonly ActionExport[]
17
+ }
18
+
19
+ const actionModuleNames = new Set(["flamefront", "flamefront/server"])
20
+
21
+ function cleanModuleId(id: string): string {
22
+ return id.split("?", 1)[0].replaceAll("\\", "/")
23
+ }
24
+
25
+ function exportedName(node: Babel.Identifier | Babel.StringLiteral): string {
26
+ return node.type === "Identifier" ? node.name : node.value
27
+ }
28
+
29
+ function unwrapExpression(
30
+ node: Babel.Expression | null,
31
+ ): Babel.Expression | null {
32
+ let current = node
33
+
34
+ while (
35
+ current &&
36
+ (current.type === "TSAsExpression" ||
37
+ current.type === "TSTypeAssertion" ||
38
+ current.type === "TypeCastExpression")
39
+ ) {
40
+ current = current.expression
41
+ }
42
+
43
+ return current
44
+ }
45
+
46
+ function actionCall(
47
+ node: Babel.Expression | null | undefined,
48
+ bindings: ReadonlySet<string>,
49
+ ): Babel.CallExpression | undefined {
50
+ const expression = unwrapExpression(node ?? null)
51
+
52
+ if (
53
+ !expression ||
54
+ expression.type !== "CallExpression" ||
55
+ expression.callee.type !== "Identifier" ||
56
+ !bindings.has(expression.callee.name)
57
+ ) {
58
+ return undefined
59
+ }
60
+
61
+ return expression
62
+ }
63
+
64
+ function actionId(moduleId: string, localName: string): string {
65
+ const digest = createHash("sha256")
66
+ .update(`${cleanModuleId(moduleId)}#${localName}`)
67
+ .digest("hex")
68
+ .slice(0, 24)
69
+
70
+ return `flamefront:action:${digest}`
71
+ }
72
+
73
+ /** Find named action exports in a module that can be proxied to the browser. */
74
+ export function findActionExports(
75
+ source: string,
76
+ id = "action.ts",
77
+ ): readonly ActionExport[] {
78
+ const ast = parse(source, {
79
+ sourceFilename: id,
80
+ sourceType: "module",
81
+ plugins: ["typescript", "jsx"],
82
+ })
83
+ const actionBindings = new Set<string>()
84
+
85
+ traverse(ast, {
86
+ ImportDeclaration(path) {
87
+ if (!actionModuleNames.has(path.node.source.value)) {
88
+ return
89
+ }
90
+
91
+ for (const specifier of path.node.specifiers) {
92
+ if (specifier.type !== "ImportSpecifier") {
93
+ continue
94
+ }
95
+
96
+ const imported = specifier.imported
97
+ const importedName =
98
+ imported.type === "Identifier" ? imported.name : imported.value
99
+
100
+ if (importedName === "action") {
101
+ actionBindings.add(specifier.local.name)
102
+ }
103
+ }
104
+ },
105
+ })
106
+
107
+ if (actionBindings.size === 0) {
108
+ return []
109
+ }
110
+
111
+ const calls = new Map<string, Babel.CallExpression>()
112
+ const addDeclaration = (declaration: Babel.VariableDeclaration) => {
113
+ for (const declarator of declaration.declarations) {
114
+ if (declarator.id.type !== "Identifier") {
115
+ continue
116
+ }
117
+
118
+ const call = actionCall(declarator.init, actionBindings)
119
+
120
+ if (call) {
121
+ calls.set(declarator.id.name, call)
122
+ }
123
+ }
124
+ }
125
+
126
+ for (const statement of ast.program.body) {
127
+ if (statement.type === "VariableDeclaration") {
128
+ addDeclaration(statement)
129
+ } else if (
130
+ statement.type === "ExportNamedDeclaration" &&
131
+ statement.declaration?.type === "VariableDeclaration"
132
+ ) {
133
+ addDeclaration(statement.declaration)
134
+ }
135
+ }
136
+
137
+ const exports: ActionExport[] = []
138
+ const seen = new Set<string>()
139
+ const addExport = (localName: string, name: string) => {
140
+ const call = calls.get(localName)
141
+
142
+ if (!call || !name || name === "default") {
143
+ return
144
+ }
145
+
146
+ const key = `${name}\0${localName}`
147
+
148
+ if (seen.has(key)) {
149
+ return
150
+ }
151
+
152
+ seen.add(key)
153
+ exports.push({
154
+ exportedName: name,
155
+ localName,
156
+ id: actionId(id, localName),
157
+ call,
158
+ })
159
+ }
160
+
161
+ for (const statement of ast.program.body) {
162
+ if (statement.type !== "ExportNamedDeclaration") {
163
+ continue
164
+ }
165
+
166
+ if (statement.declaration?.type === "VariableDeclaration") {
167
+ for (const declarator of statement.declaration.declarations) {
168
+ if (declarator.id.type === "Identifier") {
169
+ addExport(declarator.id.name, declarator.id.name)
170
+ }
171
+ }
172
+ }
173
+
174
+ for (const specifier of statement.specifiers) {
175
+ if (specifier.type !== "ExportSpecifier") {
176
+ continue
177
+ }
178
+
179
+ if (specifier.local.type === "Identifier") {
180
+ addExport(specifier.local.name, exportedName(specifier.exported))
181
+ }
182
+ }
183
+ }
184
+
185
+ return exports
186
+ }
187
+
188
+ /** Attach stable IDs to server-side action calls. */
189
+ export function transformServerActions(
190
+ source: string,
191
+ id = "action.ts",
192
+ ): ActionModuleTransform | null {
193
+ const ast = parse(source, {
194
+ sourceFilename: id,
195
+ sourceType: "module",
196
+ plugins: ["typescript", "jsx"],
197
+ })
198
+ const actions = findActionExports(source, id)
199
+
200
+ if (actions.length === 0) {
201
+ return null
202
+ }
203
+
204
+ const actionIds = new Map(
205
+ actions.map((action) => [action.localName, action.id] as const),
206
+ )
207
+
208
+ traverse(ast, {
209
+ VariableDeclarator(path) {
210
+ if (path.node.id.type !== "Identifier") {
211
+ return
212
+ }
213
+
214
+ const id = actionIds.get(path.node.id.name)
215
+ const call = unwrapExpression(path.node.init ?? null)
216
+
217
+ if (!id || !call || call.type !== "CallExpression") {
218
+ return
219
+ }
220
+
221
+ const first = call.arguments[0]
222
+
223
+ if (first?.type === "StringLiteral" && first.value === id) {
224
+ return
225
+ }
226
+
227
+ call.arguments.unshift(stringLiteral(id))
228
+ },
229
+ })
230
+
231
+ const generated = generate(ast, {
232
+ sourceMaps: true,
233
+ filename: id,
234
+ sourceFileName: cleanModuleId(id),
235
+ })
236
+
237
+ return { code: generated.code, map: generated.map, actions }
238
+ }
239
+
240
+ function validExportName(name: string): boolean {
241
+ return /^[$A-Z_a-z][$\w]*$/.test(name)
242
+ }
243
+
244
+ /** Generate a browser module containing typed-at-source action proxies. */
245
+ export function generateActionProxyModule(
246
+ actions: readonly ActionExport[],
247
+ routing: NormalizedRoutingOptions,
248
+ ): string {
249
+ const exports = actions
250
+ .filter((action) => validExportName(action.exportedName))
251
+ .map(
252
+ (action) =>
253
+ `export const ${action.exportedName} = createActionProxy(${JSON.stringify(action.id)}, routing);`,
254
+ )
255
+ .join("\n")
256
+
257
+ return `// Generated by Flamefront.\nimport { createActionProxy } from "flamefront/action-client";\nconst routing = ${JSON.stringify(routing)};\n\n${exports}\n`
258
+ }