@webtypen/webframez-react 0.0.1 → 0.0.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.
@@ -0,0 +1,309 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from "node:fs";
4
+ import fsp from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { spawn } from "node:child_process";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
+
9
+ const binFilePath = fileURLToPath(import.meta.url);
10
+ const packageRoot = path.resolve(path.dirname(binFilePath), "..");
11
+ const projectRoot = process.cwd();
12
+
13
+ const command = process.argv[2];
14
+ const passthroughStart = process.argv[3] === "--" ? 4 : 3;
15
+ const passthroughArgs = process.argv.slice(passthroughStart);
16
+ const customArgPrefixes = ["--client-entry", "--server-entry"];
17
+
18
+ function printHelp() {
19
+ console.log(
20
+ [
21
+ "webframez-react CLI",
22
+ "",
23
+ "Usage:",
24
+ " webframez-react build:server",
25
+ " webframez-react watch:server",
26
+ " webframez-react build:client",
27
+ " webframez-react watch:client",
28
+ " webframez-react build:server:webpack",
29
+ " webframez-react watch:server:webpack",
30
+ "",
31
+ "Config fallback order:",
32
+ " 1) project root override file",
33
+ " 2) package default in @webtypen/webframez-react/defaults",
34
+ "",
35
+ "Override file names:",
36
+ " - tsconfig.server.json",
37
+ " - webpack.client.cjs",
38
+ " - webpack.server.cjs",
39
+ "",
40
+ "Optional project config file:",
41
+ " - webframez-react.config.mjs|cjs|js|json",
42
+ "",
43
+ "Optional CLI overrides:",
44
+ " --client-entry=src/client.tsx",
45
+ " --server-entry=src/server.ts",
46
+ ].join("\n"),
47
+ );
48
+ }
49
+
50
+ function hasFlag(flag) {
51
+ return passthroughArgs.includes(flag);
52
+ }
53
+
54
+ function normalizeRelativePath(value) {
55
+ return value.replace(/\\/g, "/");
56
+ }
57
+
58
+ function readCustomArg(name) {
59
+ const withEquals = `${name}=`;
60
+ for (let index = 0; index < passthroughArgs.length; index += 1) {
61
+ const value = passthroughArgs[index];
62
+ if (value === name) {
63
+ return passthroughArgs[index + 1] || null;
64
+ }
65
+ if (value.startsWith(withEquals)) {
66
+ return value.slice(withEquals.length);
67
+ }
68
+ }
69
+ return null;
70
+ }
71
+
72
+ function stripCustomArgs(args) {
73
+ const filtered = [];
74
+ for (let index = 0; index < args.length; index += 1) {
75
+ const value = args[index];
76
+ const matchedPrefix = customArgPrefixes.find(
77
+ (prefix) => value === prefix || value.startsWith(`${prefix}=`),
78
+ );
79
+ if (!matchedPrefix) {
80
+ filtered.push(value);
81
+ continue;
82
+ }
83
+
84
+ if (value === matchedPrefix) {
85
+ index += 1;
86
+ }
87
+ }
88
+ return filtered;
89
+ }
90
+
91
+ function resolveConfig(localFileName, fallbackFileName) {
92
+ const localPath = path.resolve(projectRoot, localFileName);
93
+ if (fs.existsSync(localPath)) {
94
+ return {
95
+ path: localPath,
96
+ source: "project",
97
+ name: localFileName,
98
+ };
99
+ }
100
+
101
+ return {
102
+ path: path.resolve(packageRoot, "defaults", fallbackFileName),
103
+ source: "package",
104
+ name: fallbackFileName,
105
+ };
106
+ }
107
+
108
+ function resolveBinary(name) {
109
+ const extension = process.platform === "win32" ? ".cmd" : "";
110
+ const localBinary = path.resolve(projectRoot, "node_modules", ".bin", `${name}${extension}`);
111
+ if (fs.existsSync(localBinary)) {
112
+ return localBinary;
113
+ }
114
+
115
+ return name;
116
+ }
117
+
118
+ async function loadProjectConfig() {
119
+ const configFiles = [
120
+ "webframez-react.config.mjs",
121
+ "webframez-react.config.cjs",
122
+ "webframez-react.config.js",
123
+ "webframez-react.config.json",
124
+ ];
125
+
126
+ for (const fileName of configFiles) {
127
+ const filePath = path.resolve(projectRoot, fileName);
128
+ if (!fs.existsSync(filePath)) {
129
+ continue;
130
+ }
131
+
132
+ if (fileName.endsWith(".json")) {
133
+ return JSON.parse(await fsp.readFile(filePath, "utf8"));
134
+ }
135
+
136
+ const imported = await import(pathToFileURL(filePath).href);
137
+ return imported.default ?? imported;
138
+ }
139
+
140
+ return {};
141
+ }
142
+
143
+ function resolveEntryPath(projectConfig, customArgValue, configKey, defaults) {
144
+ const configuredValue = customArgValue || projectConfig?.[configKey];
145
+ if (configuredValue && typeof configuredValue === "string") {
146
+ return path.resolve(projectRoot, configuredValue);
147
+ }
148
+
149
+ for (const defaultPath of defaults) {
150
+ const resolved = path.resolve(projectRoot, defaultPath);
151
+ if (fs.existsSync(resolved)) {
152
+ return resolved;
153
+ }
154
+ }
155
+
156
+ return path.resolve(projectRoot, defaults[0]);
157
+ }
158
+
159
+ async function createServerTsConfig(baseConfig, serverEntryPath, clientEntryPath) {
160
+ const generatedPath = path.resolve(projectRoot, ".webframez-react.tsconfig.server.json");
161
+ const extendsPath =
162
+ baseConfig.source === "project"
163
+ ? `./${normalizeRelativePath(path.basename(baseConfig.path))}`
164
+ : normalizeRelativePath(path.relative(projectRoot, baseConfig.path));
165
+
166
+ const include = [
167
+ normalizeRelativePath(path.relative(projectRoot, serverEntryPath)),
168
+ "src/components/**/*.tsx",
169
+ "pages/**/*.tsx",
170
+ "src/types.d.ts",
171
+ ];
172
+
173
+ const exclude = [
174
+ normalizeRelativePath(path.relative(projectRoot, clientEntryPath)),
175
+ "dist",
176
+ "node_modules",
177
+ ];
178
+
179
+ const generatedConfig = {
180
+ extends: extendsPath,
181
+ include: Array.from(new Set(include)),
182
+ exclude: Array.from(new Set(exclude)),
183
+ };
184
+
185
+ await fsp.writeFile(generatedPath, JSON.stringify(generatedConfig, null, 2));
186
+ return generatedPath;
187
+ }
188
+
189
+ function run(binaryName, args, envAdditions = {}) {
190
+ const binary = resolveBinary(binaryName);
191
+
192
+ return new Promise((resolve, reject) => {
193
+ const child = spawn(binary, args, {
194
+ cwd: projectRoot,
195
+ stdio: "inherit",
196
+ shell: false,
197
+ env: {
198
+ ...process.env,
199
+ ...envAdditions,
200
+ },
201
+ });
202
+
203
+ child.on("error", (error) => {
204
+ reject(error);
205
+ });
206
+
207
+ child.on("close", (code) => {
208
+ resolve(code || 0);
209
+ });
210
+ });
211
+ }
212
+
213
+ async function main() {
214
+ if (!command || command === "--help" || command === "-h") {
215
+ printHelp();
216
+ return;
217
+ }
218
+
219
+ const projectConfig = await loadProjectConfig();
220
+ const customClientEntry = readCustomArg("--client-entry");
221
+ const customServerEntry = readCustomArg("--server-entry");
222
+ const passthroughArgsClean = stripCustomArgs(passthroughArgs);
223
+
224
+ const clientEntryPath = resolveEntryPath(
225
+ projectConfig,
226
+ customClientEntry,
227
+ "clientEntryPath",
228
+ ["src/client.tsx"],
229
+ );
230
+ const serverEntryPath = resolveEntryPath(
231
+ projectConfig,
232
+ customServerEntry,
233
+ "serverEntryPath",
234
+ ["src/server.ts", "src/server.tsx"],
235
+ );
236
+
237
+ if (command === "build:server" || command === "watch:server") {
238
+ const config = resolveConfig("tsconfig.server.json", "tsconfig.server.json");
239
+ const generatedConfigPath = await createServerTsConfig(
240
+ config,
241
+ serverEntryPath,
242
+ clientEntryPath,
243
+ );
244
+ console.log(`[webframez-react] tsc config (${config.source}): ${config.path}`);
245
+ console.log(`[webframez-react] server entry: ${serverEntryPath}`);
246
+
247
+ const args = ["-p", generatedConfigPath, ...passthroughArgsClean];
248
+ if (command === "watch:server") {
249
+ if (!hasFlag("--watch")) {
250
+ args.push("--watch");
251
+ }
252
+ if (!hasFlag("--preserveWatchOutput")) {
253
+ args.push("--preserveWatchOutput");
254
+ }
255
+ }
256
+
257
+ const code = await run("tsc", args);
258
+ process.exit(code);
259
+ return;
260
+ }
261
+
262
+ if (command === "build:client" || command === "watch:client") {
263
+ const config = resolveConfig("webpack.client.cjs", "webpack.client.cjs");
264
+ console.log(`[webframez-react] webpack config (${config.source}): ${config.path}`);
265
+ console.log(`[webframez-react] client entry: ${clientEntryPath}`);
266
+
267
+ const args = ["--config", config.path, ...passthroughArgsClean];
268
+ if (command === "watch:client" && !hasFlag("--watch")) {
269
+ args.push("--watch");
270
+ }
271
+
272
+ const code = await run("webpack", args, {
273
+ WEBFRAMEZ_REACT_CLIENT_ENTRY: clientEntryPath,
274
+ });
275
+ process.exit(code);
276
+ return;
277
+ }
278
+
279
+ if (command === "build:server:webpack" || command === "watch:server:webpack") {
280
+ const config = resolveConfig("webpack.server.cjs", "webpack.server.cjs");
281
+ console.log(`[webframez-react] webpack server config (${config.source}): ${config.path}`);
282
+ console.log(`[webframez-react] server entry: ${serverEntryPath}`);
283
+
284
+ const args = ["--config", config.path, ...passthroughArgsClean];
285
+ if (command === "watch:server:webpack" && !hasFlag("--watch")) {
286
+ args.push("--watch");
287
+ }
288
+
289
+ const code = await run("webpack", args, {
290
+ WEBFRAMEZ_REACT_SERVER_ENTRY: serverEntryPath,
291
+ });
292
+ process.exit(code);
293
+ return;
294
+ }
295
+
296
+ console.error(`[webframez-react] Unknown command: ${command}`);
297
+ printHelp();
298
+ process.exit(1);
299
+ }
300
+
301
+ main().catch((error) => {
302
+ console.error("[webframez-react] Build command failed.");
303
+ if (error && typeof error === "object" && "message" in error) {
304
+ console.error(String(error.message));
305
+ } else {
306
+ console.error(error);
307
+ }
308
+ process.exit(1);
309
+ });
@@ -0,0 +1,46 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "CommonJS",
5
+ "moduleResolution": "Node",
6
+ "baseUrl": ".",
7
+ "paths": {
8
+ "@webtypen/webframez-react": [
9
+ "./node_modules/@webtypen/webframez-react/dist/index.d.ts"
10
+ ],
11
+ "@webtypen/webframez-react/types": [
12
+ "./node_modules/@webtypen/webframez-react/dist/types.d.ts"
13
+ ],
14
+ "@webtypen/webframez-react/router": [
15
+ "./node_modules/@webtypen/webframez-react/dist/router.d.ts"
16
+ ],
17
+ "@webtypen/webframez-react/client": [
18
+ "./node_modules/@webtypen/webframez-react/dist/client.d.ts"
19
+ ],
20
+ "@webtypen/webframez-react/navigation": [
21
+ "./node_modules/@webtypen/webframez-react/dist/navigation.d.ts"
22
+ ],
23
+ "@webtypen/webframez-react/webframez-core": [
24
+ "./node_modules/@webtypen/webframez-react/dist/webframez-core.d.ts"
25
+ ]
26
+ },
27
+ "jsx": "react-jsx",
28
+ "strict": true,
29
+ "esModuleInterop": true,
30
+ "skipLibCheck": true,
31
+ "outDir": "dist",
32
+ "rootDir": "."
33
+ },
34
+ "include": [
35
+ "src/server.ts",
36
+ "src/server.tsx",
37
+ "src/components/**/*.tsx",
38
+ "pages/**/*.tsx",
39
+ "src/types.d.ts"
40
+ ],
41
+ "exclude": [
42
+ "src/client.tsx",
43
+ "dist",
44
+ "node_modules"
45
+ ]
46
+ }
@@ -0,0 +1,64 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "CommonJS",
5
+ "moduleResolution": "Node",
6
+ "baseUrl": ".",
7
+ "paths": {
8
+ "@webtypen/webframez-react": [
9
+ "./node_modules/@webtypen/webframez-react/dist/index.d.ts"
10
+ ],
11
+ "@webtypen/webframez-react/types": [
12
+ "./node_modules/@webtypen/webframez-react/dist/types.d.ts"
13
+ ],
14
+ "@webtypen/webframez-react/router": [
15
+ "./node_modules/@webtypen/webframez-react/dist/router.d.ts"
16
+ ],
17
+ "@webtypen/webframez-react/client": [
18
+ "./node_modules/@webtypen/webframez-react/dist/client.d.ts"
19
+ ],
20
+ "@webtypen/webframez-react/navigation": [
21
+ "./node_modules/@webtypen/webframez-react/dist/navigation.d.ts"
22
+ ],
23
+ "@webtypen/webframez-react/webframez-core": [
24
+ "./node_modules/@webtypen/webframez-react/dist/webframez-core.d.ts"
25
+ ],
26
+ "webframez-react": [
27
+ "./node_modules/@webtypen/webframez-react/dist/index.d.ts"
28
+ ],
29
+ "webframez-react/types": [
30
+ "./node_modules/@webtypen/webframez-react/dist/types.d.ts"
31
+ ],
32
+ "webframez-react/router": [
33
+ "./node_modules/@webtypen/webframez-react/dist/router.d.ts"
34
+ ],
35
+ "webframez-react/client": [
36
+ "./node_modules/@webtypen/webframez-react/dist/client.d.ts"
37
+ ],
38
+ "webframez-react/navigation": [
39
+ "./node_modules/@webtypen/webframez-react/dist/navigation.d.ts"
40
+ ],
41
+ "webframez-react/webframez-core": [
42
+ "./node_modules/@webtypen/webframez-react/dist/webframez-core.d.ts"
43
+ ]
44
+ },
45
+ "jsx": "react-jsx",
46
+ "strict": true,
47
+ "esModuleInterop": true,
48
+ "skipLibCheck": true,
49
+ "outDir": "dist",
50
+ "rootDir": "."
51
+ },
52
+ "include": [
53
+ "src/server.ts",
54
+ "src/server.tsx",
55
+ "src/components/**/*.tsx",
56
+ "pages/**/*.tsx",
57
+ "src/types.d.ts"
58
+ ],
59
+ "exclude": [
60
+ "src/client.tsx",
61
+ "dist",
62
+ "node_modules"
63
+ ]
64
+ }
@@ -0,0 +1,64 @@
1
+ const path = require("path");
2
+ const ReactFlightWebpackPlugin = require("react-server-dom-webpack/plugin");
3
+
4
+ const projectRoot = process.cwd();
5
+ const frameworkDistDir = path.resolve(__dirname, "..", "dist");
6
+ const clientEntry = process.env.WEBFRAMEZ_REACT_CLIENT_ENTRY
7
+ ? path.resolve(projectRoot, process.env.WEBFRAMEZ_REACT_CLIENT_ENTRY)
8
+ : path.resolve(projectRoot, "src/client.tsx");
9
+
10
+ module.exports = {
11
+ mode: process.env.NODE_ENV === "production" ? "production" : "development",
12
+ entry: {
13
+ client: clientEntry,
14
+ },
15
+ output: {
16
+ path: path.resolve(projectRoot, "dist"),
17
+ filename: "[name].js",
18
+ chunkFilename: "chunks/[name]-[contenthash].js",
19
+ publicPath: "auto",
20
+ },
21
+ resolve: {
22
+ extensions: [".tsx", ".ts", ".js"],
23
+ },
24
+ module: {
25
+ rules: [
26
+ {
27
+ test: /\.[tj]sx?$/,
28
+ exclude: /node_modules/,
29
+ use: {
30
+ loader: "ts-loader",
31
+ options: {
32
+ transpileOnly: true,
33
+ },
34
+ },
35
+ },
36
+ ],
37
+ },
38
+ optimization: {
39
+ splitChunks: false,
40
+ runtimeChunk: false,
41
+ },
42
+ plugins: [
43
+ new ReactFlightWebpackPlugin({
44
+ isServer: false,
45
+ clientReferences: [
46
+ {
47
+ directory: path.resolve(projectRoot, "dist/pages"),
48
+ recursive: true,
49
+ include: /\.js$/,
50
+ },
51
+ {
52
+ directory: path.resolve(projectRoot, "dist/src/components"),
53
+ recursive: true,
54
+ include: /\.js$/,
55
+ },
56
+ {
57
+ directory: frameworkDistDir,
58
+ recursive: false,
59
+ include: /navigation\.(js|cjs)$/,
60
+ },
61
+ ],
62
+ }),
63
+ ],
64
+ };
@@ -0,0 +1,40 @@
1
+ const path = require("path");
2
+ const fs = require("fs");
3
+
4
+ const projectRoot = process.cwd();
5
+ const defaultServerEntry = fs.existsSync(path.resolve(projectRoot, "src/server.ts"))
6
+ ? path.resolve(projectRoot, "src/server.ts")
7
+ : path.resolve(projectRoot, "src/server.tsx");
8
+ const serverEntry = process.env.WEBFRAMEZ_REACT_SERVER_ENTRY
9
+ ? path.resolve(projectRoot, process.env.WEBFRAMEZ_REACT_SERVER_ENTRY)
10
+ : defaultServerEntry;
11
+
12
+ module.exports = {
13
+ mode: process.env.NODE_ENV === "production" ? "production" : "development",
14
+ target: "node",
15
+ entry: serverEntry,
16
+ output: {
17
+ path: path.resolve(projectRoot, "dist"),
18
+ filename: "server.cjs",
19
+ libraryTarget: "commonjs2",
20
+ },
21
+ resolve: {
22
+ extensions: [".tsx", ".ts", ".js"],
23
+ conditionNames: ["react-server", "node", "import", "require", "default"],
24
+ },
25
+ module: {
26
+ rules: [
27
+ {
28
+ test: /\.[tj]sx?$/,
29
+ exclude: /node_modules/,
30
+ use: {
31
+ loader: "ts-loader",
32
+ options: {
33
+ transpileOnly: true,
34
+ },
35
+ },
36
+ },
37
+ ],
38
+ },
39
+ externalsPresets: { node: true },
40
+ };
package/dist/client.cjs CHANGED
@@ -1 +1 @@
1
- var _=Object.create;var d=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var S=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty;var b=(e,n)=>{for(var t in n)d(e,t,{get:n[t],enumerable:!0})},g=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of O(n))!U.call(e,r)&&r!==t&&d(e,r,{get:()=>n[r],enumerable:!(o=k(n,r))||o.enumerable});return e};var A=(e,n,t)=>(t=e!=null?_(S(e)):{},g(n||!e||!e.__esModule?d(t,"default",{value:e,enumerable:!0}):t,e)),L=e=>g(d({},"__esModule",{value:!0}),e);var B={};b(B,{mountWebframezClient:()=>W,useCookie:()=>T,useRouter:()=>F});module.exports=L(B);var a=A(require("react"),1),x=require("react-dom/client"),v=require("react-server-dom-webpack/client"),i=require("react/jsx-runtime"),$={push:()=>{},replace:()=>{},refresh:()=>{}},l=typeof a.default.createContext=="function"?a.default.createContext(null):null,E="__WEBFRAMEZ_ROUTER__";function I(){return typeof window>"u"?null:window[E]??null}function P(e){typeof window>"u"||(window[E]=e)}function w(){let e={},n=typeof document>"u"?"":document.cookie;if(!n||n.trim()==="")return e;for(let t of n.split(";")){let o=t.trim();if(!o)continue;let r=o.indexOf("="),c=r>=0?o.slice(0,r).trim():o,u=r>=0?o.slice(r+1):"";c&&(e[c]=decodeURIComponent(u))}return e}function h(e,n,t={}){let o=[`${e}=${encodeURIComponent(n)}`];return t.path&&o.push(`Path=${t.path}`),t.domain&&o.push(`Domain=${t.domain}`),typeof t.maxAge=="number"&&o.push(`Max-Age=${Math.floor(t.maxAge)}`),t.expires&&o.push(`Expires=${t.expires.toUTCString()}`),t.sameSite&&o.push(`SameSite=${t.sameSite}`),t.secure&&o.push("Secure"),o.join("; ")}function T(){return a.default.useMemo(()=>({all:()=>w(),get:e=>w()[e],set:(e,n,t)=>{typeof document>"u"||(document.cookie=h(e,n,t))},remove:(e,n)=>{typeof document>"u"||(document.cookie=h(e,"",{...n??{},maxAge:0}))}}),[])}function F(){let e=l?a.default.useContext(l):null;if(!e){let n=I();if(n)return n;if(typeof window>"u")return $;throw new Error("useRouter must be used inside mountWebframezClient()")}return e}function C({active:e}){return(0,i.jsx)("div",{style:{position:"fixed",top:0,left:0,width:"100%",height:3,zIndex:9999,transformOrigin:"left",transform:e?"scaleX(1)":"scaleX(0)",transition:"transform 180ms ease",background:"linear-gradient(90deg, #0ea5e9, #22c55e)"}})}function M(e){return function(){let[t,o]=(0,a.useState)(null),[r,c]=(0,a.useState)(!1);async function u(s,f="push"){c(!0);try{let y=await(0,v.createFromFetch)(fetch(`${e}?path=${encodeURIComponent(s.pathname)}&search=${encodeURIComponent(s.search)}`,{headers:{Accept:"text/x-component"}}));o(y);let R=`${s.pathname}${s.search}`;f==="replace"?history.replaceState(null,"",R):f==="push"&&history.pushState(null,"",R)}catch(m){console.error("[webframez-react] Failed to render route",m),o((0,i.jsx)("p",{children:"Failed to load route."}))}finally{c(!1)}}(0,a.useEffect)(()=>{let s=()=>{u(new URL(window.location.href),"none")};return window.addEventListener("popstate",s),u(new URL(window.location.href),"none"),()=>{window.removeEventListener("popstate",s)}},[]);let p=a.default.useMemo(()=>({push:s=>{u(new URL(s,window.location.origin),"push")},replace:s=>{u(new URL(s,window.location.origin),"replace")},refresh:()=>{u(new URL(window.location.href),"none")}}),[]);return P(p),l?(0,i.jsxs)(l.Provider,{value:p,children:[(0,i.jsx)(C,{active:r}),t??(0,i.jsx)("p",{style:{padding:24},children:"Loading..."})]}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(C,{active:r}),t??(0,i.jsx)("p",{style:{padding:24},children:"Loading..."})]})}}function W(e={}){let n=e.rootId??"root",t=document.getElementById(n);if(!t)throw new Error(`Missing #${n} element`);let o=typeof window<"u"&&window.__RSC_ENDPOINT,r=e.rscEndpoint??o??"/rsc",c=M(r),u=(0,x.createRoot)(t);return u.render((0,i.jsx)(c,{})),u}
1
+ var k=Object.create;var d=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var S=Object.getPrototypeOf,L=Object.prototype.hasOwnProperty;var T=(e,t)=>{for(var n in t)d(e,n,{get:t[n],enumerable:!0})},R=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of O(t))!L.call(e,r)&&r!==n&&d(e,r,{get:()=>t[r],enumerable:!(o=A(t,r))||o.enumerable});return e};var U=(e,t,n)=>(n=e!=null?k(S(e)):{},R(t||!e||!e.__esModule?d(n,"default",{value:e,enumerable:!0}):n,e)),M=e=>R(d({},"__esModule",{value:!0}),e);var D={};T(D,{mountWebframezClient:()=>F,useCookie:()=>B,useRouter:()=>H});module.exports=M(D);var s=U(require("react"),1),E=require("react-dom/client"),_=require("react-server-dom-webpack/client"),i=require("react/jsx-runtime"),$={push:()=>{},replace:()=>{},refresh:()=>{}},l=typeof s.default.createContext=="function"?s.default.createContext(null):null,b="__WEBFRAMEZ_ROUTER__",I="[data-webframez-head='true']";function P(){return typeof window>"u"?null:window[b]??null}function N(e){typeof window>"u"||(window[b]=e)}function h(){let e={},t=typeof document>"u"?"":document.cookie;if(!t||t.trim()==="")return e;for(let n of t.split(";")){let o=n.trim();if(!o)continue;let r=o.indexOf("="),u=r>=0?o.slice(0,r).trim():o,c=r>=0?o.slice(r+1):"";u&&(e[u]=decodeURIComponent(c))}return e}function C(e,t,n={}){let o=[`${e}=${encodeURIComponent(t)}`];return n.path&&o.push(`Path=${n.path}`),n.domain&&o.push(`Domain=${n.domain}`),typeof n.maxAge=="number"&&o.push(`Max-Age=${Math.floor(n.maxAge)}`),n.expires&&o.push(`Expires=${n.expires.toUTCString()}`),n.sameSite&&o.push(`SameSite=${n.sameSite}`),n.secure&&o.push("Secure"),o.join("; ")}function B(){return s.default.useMemo(()=>({all:()=>h(),get:e=>h()[e],set:(e,t,n)=>{typeof document>"u"||(document.cookie=C(e,t,n))},remove:(e,t)=>{typeof document>"u"||(document.cookie=C(e,"",{...t??{},maxAge:0}))}}),[])}function H(){let e=l?s.default.useContext(l):null;if(!e){let t=P();if(t)return t;if(typeof window>"u")return $;throw new Error("useRouter must be used inside mountWebframezClient()")}return e}function v({active:e}){return(0,i.jsx)("div",{style:{position:"fixed",top:0,left:0,width:"100%",height:3,zIndex:9999,transformOrigin:"left",transform:e?"scaleX(1)":"scaleX(0)",transition:"transform 180ms ease",background:"linear-gradient(90deg, #0ea5e9, #22c55e)"}})}function y(e){let t=document.createElement("meta");t.setAttribute("data-webframez-head","true");let n=Object.entries(e).filter(([,o])=>!!o);for(let[o,r]of n)t.setAttribute(o,String(r));document.head.appendChild(t)}function x(e){let t=document.createElement("link");t.setAttribute("data-webframez-head","true");let n=Object.entries(e).filter(([,o])=>!!o);for(let[o,r]of n)t.setAttribute(o,String(r));document.head.appendChild(t)}function W(e){if(!(typeof document>"u")){document.title=e.title||"Webframez React";for(let t of document.head.querySelectorAll(I))t.remove();e.description&&y({name:"description",content:e.description}),e.favicon&&x({rel:"icon",href:e.favicon});for(let t of e.meta??[])y(t);for(let t of e.links??[])x(t)}}function z(e){return function(){let[n,o]=(0,s.useState)(null),[r,u]=(0,s.useState)(!1);async function c(a,p="push"){u(!0);try{let g=await(0,_.createFromFetch)(fetch(`${e}?path=${encodeURIComponent(a.pathname)}&search=${encodeURIComponent(a.search)}`,{headers:{Accept:"text/x-component"}}));W(g.head),o(g.model);let w=`${a.pathname}${a.search}`;p==="replace"?history.replaceState(null,"",w):p==="push"&&history.pushState(null,"",w)}catch(m){console.error("[webframez-react] Failed to render route",m),o((0,i.jsx)("p",{children:"Failed to load route."}))}finally{u(!1)}}(0,s.useEffect)(()=>{let a=()=>{c(new URL(window.location.href),"none")};return window.addEventListener("popstate",a),c(new URL(window.location.href),"none"),()=>{window.removeEventListener("popstate",a)}},[]);let f=s.default.useMemo(()=>({push:a=>{c(new URL(a,window.location.origin),"push")},replace:a=>{c(new URL(a,window.location.origin),"replace")},refresh:()=>{c(new URL(window.location.href),"none")}}),[]);return N(f),l?(0,i.jsxs)(l.Provider,{value:f,children:[(0,i.jsx)(v,{active:r}),n??(0,i.jsx)("p",{style:{padding:24},children:"Loading..."})]}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(v,{active:r}),n??(0,i.jsx)("p",{style:{padding:24},children:"Loading..."})]})}}function F(e={}){let t=e.rootId??"root",n=document.getElementById(t);if(!n)throw new Error(`Missing #${t} element`);let o=typeof window<"u"&&window.__RSC_ENDPOINT,r=e.rscEndpoint??o??"/rsc",u=z(r),c=(0,E.createRoot)(n);return c.render((0,i.jsx)(u,{})),c}
package/dist/client.js CHANGED
@@ -1 +1 @@
1
- import c,{useEffect as E,useState as R}from"react";import{createRoot as y}from"react-dom/client";import{createFromFetch as _}from"react-server-dom-webpack/client";import{Fragment as b,jsx as u,jsxs as C}from"react/jsx-runtime";var k={push:()=>{},replace:()=>{},refresh:()=>{}},d=typeof c.createContext=="function"?c.createContext(null):null,x="__WEBFRAMEZ_ROUTER__";function O(){return typeof window>"u"?null:window[x]??null}function S(e){typeof window>"u"||(window[x]=e)}function g(){let e={},o=typeof document>"u"?"":document.cookie;if(!o||o.trim()==="")return e;for(let t of o.split(";")){let n=t.trim();if(!n)continue;let s=n.indexOf("="),a=s>=0?n.slice(0,s).trim():n,i=s>=0?n.slice(s+1):"";a&&(e[a]=decodeURIComponent(i))}return e}function w(e,o,t={}){let n=[`${e}=${encodeURIComponent(o)}`];return t.path&&n.push(`Path=${t.path}`),t.domain&&n.push(`Domain=${t.domain}`),typeof t.maxAge=="number"&&n.push(`Max-Age=${Math.floor(t.maxAge)}`),t.expires&&n.push(`Expires=${t.expires.toUTCString()}`),t.sameSite&&n.push(`SameSite=${t.sameSite}`),t.secure&&n.push("Secure"),n.join("; ")}function I(){return c.useMemo(()=>({all:()=>g(),get:e=>g()[e],set:(e,o,t)=>{typeof document>"u"||(document.cookie=w(e,o,t))},remove:(e,o)=>{typeof document>"u"||(document.cookie=w(e,"",{...o??{},maxAge:0}))}}),[])}function P(){let e=d?c.useContext(d):null;if(!e){let o=O();if(o)return o;if(typeof window>"u")return k;throw new Error("useRouter must be used inside mountWebframezClient()")}return e}function h({active:e}){return u("div",{style:{position:"fixed",top:0,left:0,width:"100%",height:3,zIndex:9999,transformOrigin:"left",transform:e?"scaleX(1)":"scaleX(0)",transition:"transform 180ms ease",background:"linear-gradient(90deg, #0ea5e9, #22c55e)"}})}function U(e){return function(){let[t,n]=R(null),[s,a]=R(!1);async function i(r,p="push"){a(!0);try{let v=await _(fetch(`${e}?path=${encodeURIComponent(r.pathname)}&search=${encodeURIComponent(r.search)}`,{headers:{Accept:"text/x-component"}}));n(v);let m=`${r.pathname}${r.search}`;p==="replace"?history.replaceState(null,"",m):p==="push"&&history.pushState(null,"",m)}catch(f){console.error("[webframez-react] Failed to render route",f),n(u("p",{children:"Failed to load route."}))}finally{a(!1)}}E(()=>{let r=()=>{i(new URL(window.location.href),"none")};return window.addEventListener("popstate",r),i(new URL(window.location.href),"none"),()=>{window.removeEventListener("popstate",r)}},[]);let l=c.useMemo(()=>({push:r=>{i(new URL(r,window.location.origin),"push")},replace:r=>{i(new URL(r,window.location.origin),"replace")},refresh:()=>{i(new URL(window.location.href),"none")}}),[]);return S(l),d?C(d.Provider,{value:l,children:[u(h,{active:s}),t??u("p",{style:{padding:24},children:"Loading..."})]}):C(b,{children:[u(h,{active:s}),t??u("p",{style:{padding:24},children:"Loading..."})]})}}function T(e={}){let o=e.rootId??"root",t=document.getElementById(o);if(!t)throw new Error(`Missing #${o} element`);let n=typeof window<"u"&&window.__RSC_ENDPOINT,s=e.rscEndpoint??n??"/rsc",a=U(s),i=y(t);return i.render(u(a,{})),i}export{T as mountWebframezClient,I as useCookie,P as useRouter};
1
+ import u,{useEffect as _,useState as w}from"react";import{createRoot as b}from"react-dom/client";import{createFromFetch as k}from"react-server-dom-webpack/client";import{Fragment as M,jsx as c,jsxs as x}from"react/jsx-runtime";var A={push:()=>{},replace:()=>{},refresh:()=>{}},d=typeof u.createContext=="function"?u.createContext(null):null,E="__WEBFRAMEZ_ROUTER__",O="[data-webframez-head='true']";function S(){return typeof window>"u"?null:window[E]??null}function L(e){typeof window>"u"||(window[E]=e)}function R(){let e={},t=typeof document>"u"?"":document.cookie;if(!t||t.trim()==="")return e;for(let o of t.split(";")){let n=o.trim();if(!n)continue;let r=n.indexOf("="),s=r>=0?n.slice(0,r).trim():n,a=r>=0?n.slice(r+1):"";s&&(e[s]=decodeURIComponent(a))}return e}function h(e,t,o={}){let n=[`${e}=${encodeURIComponent(t)}`];return o.path&&n.push(`Path=${o.path}`),o.domain&&n.push(`Domain=${o.domain}`),typeof o.maxAge=="number"&&n.push(`Max-Age=${Math.floor(o.maxAge)}`),o.expires&&n.push(`Expires=${o.expires.toUTCString()}`),o.sameSite&&n.push(`SameSite=${o.sameSite}`),o.secure&&n.push("Secure"),n.join("; ")}function N(){return u.useMemo(()=>({all:()=>R(),get:e=>R()[e],set:(e,t,o)=>{typeof document>"u"||(document.cookie=h(e,t,o))},remove:(e,t)=>{typeof document>"u"||(document.cookie=h(e,"",{...t??{},maxAge:0}))}}),[])}function B(){let e=d?u.useContext(d):null;if(!e){let t=S();if(t)return t;if(typeof window>"u")return A;throw new Error("useRouter must be used inside mountWebframezClient()")}return e}function C({active:e}){return c("div",{style:{position:"fixed",top:0,left:0,width:"100%",height:3,zIndex:9999,transformOrigin:"left",transform:e?"scaleX(1)":"scaleX(0)",transition:"transform 180ms ease",background:"linear-gradient(90deg, #0ea5e9, #22c55e)"}})}function v(e){let t=document.createElement("meta");t.setAttribute("data-webframez-head","true");let o=Object.entries(e).filter(([,n])=>!!n);for(let[n,r]of o)t.setAttribute(n,String(r));document.head.appendChild(t)}function y(e){let t=document.createElement("link");t.setAttribute("data-webframez-head","true");let o=Object.entries(e).filter(([,n])=>!!n);for(let[n,r]of o)t.setAttribute(n,String(r));document.head.appendChild(t)}function T(e){if(!(typeof document>"u")){document.title=e.title||"Webframez React";for(let t of document.head.querySelectorAll(O))t.remove();e.description&&v({name:"description",content:e.description}),e.favicon&&y({rel:"icon",href:e.favicon});for(let t of e.meta??[])v(t);for(let t of e.links??[])y(t)}}function U(e){return function(){let[o,n]=w(null),[r,s]=w(!1);async function a(i,f="push"){s(!0);try{let m=await k(fetch(`${e}?path=${encodeURIComponent(i.pathname)}&search=${encodeURIComponent(i.search)}`,{headers:{Accept:"text/x-component"}}));T(m.head),n(m.model);let g=`${i.pathname}${i.search}`;f==="replace"?history.replaceState(null,"",g):f==="push"&&history.pushState(null,"",g)}catch(p){console.error("[webframez-react] Failed to render route",p),n(c("p",{children:"Failed to load route."}))}finally{s(!1)}}_(()=>{let i=()=>{a(new URL(window.location.href),"none")};return window.addEventListener("popstate",i),a(new URL(window.location.href),"none"),()=>{window.removeEventListener("popstate",i)}},[]);let l=u.useMemo(()=>({push:i=>{a(new URL(i,window.location.origin),"push")},replace:i=>{a(new URL(i,window.location.origin),"replace")},refresh:()=>{a(new URL(window.location.href),"none")}}),[]);return L(l),d?x(d.Provider,{value:l,children:[c(C,{active:r}),o??c("p",{style:{padding:24},children:"Loading..."})]}):x(M,{children:[c(C,{active:r}),o??c("p",{style:{padding:24},children:"Loading..."})]})}}function H(e={}){let t=e.rootId??"root",o=document.getElementById(t);if(!o)throw new Error(`Missing #${t} element`);let n=typeof window<"u"&&window.__RSC_ENDPOINT,r=e.rscEndpoint??n??"/rsc",s=U(r),a=b(o);return a.render(c(s,{})),a}export{H as mountWebframezClient,N as useCookie,B as useRouter};