@holo-js/adapter-next 0.1.8 → 0.2.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,74 @@
1
+ // src/client-errors.ts
2
+ import { normalizeHoloHttpError } from "@holo-js/core/errors";
3
+ var nextHttpAccessFallbackStatuses = /* @__PURE__ */ new Set([401, 403, 404]);
4
+ function normalizeNextClientHttpError(error) {
5
+ return normalizeHoloHttpError(error);
6
+ }
7
+ function createNextRenderableError(error) {
8
+ if (!nextHttpAccessFallbackStatuses.has(error.status)) {
9
+ return new Error(error.message, { cause: error.cause });
10
+ }
11
+ const nextError = new Error(error.message, { cause: error.cause });
12
+ nextError.digest = `NEXT_HTTP_ERROR_FALLBACK;${error.status}`;
13
+ return nextError;
14
+ }
15
+ function renderNextClientHttpErrorPage(error) {
16
+ const browserDocument = globalThis.document;
17
+ if (!browserDocument) {
18
+ return;
19
+ }
20
+ browserDocument.title = `${error.status}: ${error.message}`;
21
+ const existingRoot = browserDocument.getElementById("__holo_next_client_http_error__");
22
+ const root = existingRoot ?? browserDocument.createElement("main");
23
+ root.id = "__holo_next_client_http_error__";
24
+ root.setAttribute("role", "alert");
25
+ root.style.cssText = [
26
+ "position:fixed",
27
+ "inset:0",
28
+ "z-index:2147483647",
29
+ "display:grid",
30
+ "place-items:center",
31
+ "margin:0",
32
+ "background:#fff",
33
+ "color:#000",
34
+ "font-family:Arial,Helvetica,sans-serif"
35
+ ].join(";");
36
+ const wrapper = browserDocument.createElement("div");
37
+ wrapper.style.cssText = "display:flex;align-items:center;gap:1.5rem;padding:1.5rem";
38
+ const status = browserDocument.createElement("h1");
39
+ status.className = "next-error-h1";
40
+ status.textContent = String(error.status);
41
+ status.style.cssText = [
42
+ "display:inline-block",
43
+ "margin:0 1.25rem 0 0",
44
+ "padding:0 1.5rem 0 0",
45
+ "font-size:24px",
46
+ "font-weight:500",
47
+ "line-height:49px",
48
+ "vertical-align:top",
49
+ "border-right:1px solid rgba(0,0,0,.3)"
50
+ ].join(";");
51
+ const description = browserDocument.createElement("div");
52
+ description.style.cssText = "display:inline-block;text-align:left;line-height:49px;height:49px;vertical-align:middle";
53
+ const message = browserDocument.createElement("h2");
54
+ message.textContent = error.message;
55
+ message.style.cssText = "font-size:14px;font-weight:400;line-height:49px;margin:0";
56
+ description.append(message);
57
+ wrapper.append(status, description);
58
+ root.replaceChildren(wrapper);
59
+ for (const child of Array.from(browserDocument.body.children)) {
60
+ if (child.id === root.id) {
61
+ continue;
62
+ }
63
+ child.style.display = "none";
64
+ }
65
+ if (!existingRoot) {
66
+ browserDocument.body.append(root);
67
+ }
68
+ }
69
+
70
+ export {
71
+ normalizeNextClientHttpError,
72
+ createNextRenderableError,
73
+ renderNextClientHttpErrorPage
74
+ };
package/dist/client.mjs CHANGED
@@ -1,4 +1,9 @@
1
1
  "use client";
2
+ import {
3
+ createNextRenderableError,
4
+ normalizeNextClientHttpError,
5
+ renderNextClientHttpErrorPage
6
+ } from "./chunk-3RI2KDLY.mjs";
2
7
 
3
8
  // src/client.ts
4
9
  import { useEffect, useRef, useState } from "react";
@@ -31,13 +36,22 @@ function areEqual(left, right) {
31
36
  function areOptionsEqual(left, right) {
32
37
  return left.action === right.action && left.method === right.method && left.validateOn === right.validateOn && Boolean(left.submitter) === Boolean(right.submitter) && areEqual(left.initialValues, right.initialValues) && areEqual(left.initialState, right.initialState);
33
38
  }
34
- function createSubmitterBridge(optionsRef) {
35
- return (context) => {
39
+ function createSubmitterBridge(optionsRef, onHttpError) {
40
+ return async (context) => {
36
41
  const submitter = optionsRef.current?.submitter;
37
42
  if (!submitter) {
38
43
  throw new TypeError("Expected submitter to be defined.");
39
44
  }
40
- return submitter(context);
45
+ try {
46
+ return await submitter(context);
47
+ } catch (error) {
48
+ const httpError = normalizeNextClientHttpError(error);
49
+ if (httpError) {
50
+ renderNextClientHttpErrorPage(httpError);
51
+ onHttpError(createNextRenderableError(httpError));
52
+ }
53
+ throw error;
54
+ }
41
55
  };
42
56
  }
43
57
  function useForm(schemaDefinition, options = {}) {
@@ -46,10 +60,14 @@ function useForm(schemaDefinition, options = {}) {
46
60
  const previousOptionsRef = useRef(void 0);
47
61
  const latestOptionsRef = useRef(void 0);
48
62
  const submitterBridgeRef = useRef(void 0);
63
+ const [httpError, setHttpError] = useState(void 0);
49
64
  const [, setVersion] = useState(0);
65
+ if (httpError) {
66
+ throw httpError;
67
+ }
50
68
  latestOptionsRef.current = options;
51
69
  if (options.submitter && !submitterBridgeRef.current) {
52
- submitterBridgeRef.current = createSubmitterBridge(latestOptionsRef);
70
+ submitterBridgeRef.current = createSubmitterBridge(latestOptionsRef, setHttpError);
53
71
  }
54
72
  const resolvedOptions = options.submitter ? {
55
73
  ...options,
package/dist/config.d.ts CHANGED
@@ -4,16 +4,30 @@ interface TurbopackIgnoreIssueRule {
4
4
  }
5
5
  interface TurbopackConfig {
6
6
  readonly ignoreIssue?: readonly TurbopackIgnoreIssueRule[];
7
+ readonly rules?: Record<string, unknown>;
7
8
  readonly [key: string]: unknown;
8
9
  }
9
10
  interface NextConfig {
10
11
  readonly serverExternalPackages?: string[];
12
+ readonly transpilePackages?: string[];
11
13
  readonly outputFileTracingExcludes?: Record<string, string[]>;
12
14
  readonly experimental?: Record<string, unknown>;
13
15
  readonly turbopack?: TurbopackConfig;
14
16
  readonly rewrites?: () => Promise<unknown>;
17
+ readonly webpack?: (config: WebpackConfig, context: WebpackConfigContext) => WebpackConfig;
15
18
  readonly [key: string]: unknown;
16
19
  }
20
+ type WebpackConfig = {
21
+ module?: {
22
+ rules?: unknown[];
23
+ [key: string]: unknown;
24
+ };
25
+ [key: string]: unknown;
26
+ };
27
+ type WebpackConfigContext = {
28
+ readonly isServer: boolean;
29
+ readonly [key: string]: unknown;
30
+ };
17
31
  declare function withHolo<TConfig extends NextConfig>(nextConfig?: TConfig): TConfig;
18
32
 
19
33
  export { withHolo };
package/dist/config.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // src/config.ts
2
2
  import { readFileSync } from "fs";
3
+ import { fileURLToPath } from "url";
3
4
  import { join } from "path";
4
5
  var HOLO_SERVER_EXTERNAL_PACKAGES = [
5
6
  "@holo-js/core",
@@ -9,7 +10,6 @@ var HOLO_SERVER_EXTERNAL_PACKAGES = [
9
10
  "esbuild"
10
11
  ];
11
12
  var HOLO_OPTIONAL_SERVER_EXTERNAL_PACKAGES = [
12
- "@holo-js/auth",
13
13
  "@holo-js/auth-clerk",
14
14
  "@holo-js/auth-social",
15
15
  "@holo-js/auth-social-apple",
@@ -31,12 +31,18 @@ var HOLO_OPTIONAL_SERVER_EXTERNAL_PACKAGES = [
31
31
  "@holo-js/queue",
32
32
  "@holo-js/queue-db",
33
33
  "@holo-js/queue-redis",
34
+ "@holo-js/realtime",
34
35
  "@holo-js/security",
35
36
  "@holo-js/session",
36
37
  "@holo-js/storage",
37
38
  "@holo-js/storage-s3",
38
39
  "@holo-js/validation"
39
40
  ];
41
+ var HOLO_TRANSPILED_PACKAGES = [
42
+ "@holo-js/auth"
43
+ ];
44
+ var HOLO_TRANSPILED_PACKAGE_SET = new Set(HOLO_TRANSPILED_PACKAGES);
45
+ var NEXT_AUTH_INTERRUPTS_ENV = "__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS";
40
46
  var PACKAGE_DEPENDENCY_FIELDS = [
41
47
  "dependencies",
42
48
  "devDependencies",
@@ -67,12 +73,36 @@ function readProjectPackageManifest() {
67
73
  function isOptionalServerExternalPackageInstalled(packageName, manifest) {
68
74
  return PACKAGE_DEPENDENCY_FIELDS.some((field) => Boolean(manifest?.[field]?.[packageName]));
69
75
  }
76
+ function createRealtimeDefinitionWebpackRule(loaderPath) {
77
+ return {
78
+ test: /(?:^|[\\/])server[\\/]realtime[\\/].+\.[cm]?[jt]sx?$/,
79
+ use: [loaderPath]
80
+ };
81
+ }
82
+ function createRealtimeDefinitionTurbopackRule(loaderPath) {
83
+ return {
84
+ condition: {
85
+ all: [
86
+ "browser",
87
+ {
88
+ path: /(?:^|[\\/])server[\\/]realtime[\\/]/
89
+ }
90
+ ]
91
+ },
92
+ loaders: [loaderPath],
93
+ as: "*.js"
94
+ };
95
+ }
70
96
  function withHolo(nextConfig = {}) {
97
+ process.env[NEXT_AUTH_INTERRUPTS_ENV] = "1";
71
98
  const existingExternal = nextConfig.serverExternalPackages ?? [];
72
99
  const packageManifest = readProjectPackageManifest();
73
100
  const installedOptionalExternal = HOLO_OPTIONAL_SERVER_EXTERNAL_PACKAGES.filter((packageName) => isOptionalServerExternalPackageInstalled(packageName, packageManifest));
74
101
  const mergedExternal = [
75
102
  .../* @__PURE__ */ new Set([...HOLO_SERVER_EXTERNAL_PACKAGES, ...installedOptionalExternal, ...existingExternal])
103
+ ].filter((packageName) => !HOLO_TRANSPILED_PACKAGE_SET.has(packageName));
104
+ const mergedTranspilePackages = [
105
+ .../* @__PURE__ */ new Set([...HOLO_TRANSPILED_PACKAGES, ...nextConfig.transpilePackages ?? []])
76
106
  ];
77
107
  const existingExcludes = nextConfig.outputFileTracingExcludes ?? {};
78
108
  const existingGlobalExcludes = existingExcludes["/*"] ?? [];
@@ -82,8 +112,18 @@ function withHolo(nextConfig = {}) {
82
112
  };
83
113
  const existingTurbopack = nextConfig.turbopack ?? {};
84
114
  const existingIgnoreIssue = existingTurbopack.ignoreIssue ?? [];
115
+ const hasRealtime = isOptionalServerExternalPackageInstalled("@holo-js/realtime", packageManifest);
116
+ const realtimeDefinitionLoader = fileURLToPath(new URL("./realtime-definition-loader.mjs", import.meta.url));
85
117
  const mergedTurbopack = {
86
118
  ...existingTurbopack,
119
+ rules: {
120
+ ...existingTurbopack.rules ?? {},
121
+ ...hasRealtime ? {
122
+ "*.{ts,tsx,js,jsx,mts,mjs,cts,cjs}": [
123
+ createRealtimeDefinitionTurbopackRule(realtimeDefinitionLoader)
124
+ ]
125
+ } : {}
126
+ },
87
127
  ignoreIssue: [
88
128
  ...existingIgnoreIssue,
89
129
  {
@@ -93,6 +133,7 @@ function withHolo(nextConfig = {}) {
93
133
  ]
94
134
  };
95
135
  const userRewrites = nextConfig.rewrites;
136
+ const userWebpack = nextConfig.webpack;
96
137
  return {
97
138
  ...nextConfig,
98
139
  experimental: {
@@ -100,8 +141,21 @@ function withHolo(nextConfig = {}) {
100
141
  authInterrupts: true
101
142
  },
102
143
  serverExternalPackages: mergedExternal,
144
+ transpilePackages: mergedTranspilePackages,
103
145
  outputFileTracingExcludes: mergedExcludes,
104
146
  turbopack: mergedTurbopack,
147
+ webpack(config, context) {
148
+ const nextWebpackConfig = userWebpack?.(config, context) ?? config;
149
+ if (!hasRealtime || context.isServer) {
150
+ return nextWebpackConfig;
151
+ }
152
+ nextWebpackConfig.module = nextWebpackConfig.module ?? {};
153
+ nextWebpackConfig.module.rules = [
154
+ ...nextWebpackConfig.module.rules ?? [],
155
+ createRealtimeDefinitionWebpackRule(realtimeDefinitionLoader)
156
+ ];
157
+ return nextWebpackConfig;
158
+ },
105
159
  async rewrites() {
106
160
  const userResult = await userRewrites?.call(this);
107
161
  const raw = process.env.STORAGE_ROUTE_PREFIX?.trim() ?? "/storage";
@@ -0,0 +1,6 @@
1
+ type LoaderContext = {
2
+ cacheable?: () => void;
3
+ };
4
+ declare function realtimeDefinitionLoader(this: LoaderContext, source: string): string;
5
+
6
+ export { realtimeDefinitionLoader as default };
@@ -0,0 +1,279 @@
1
+ // src/realtime-definition-transform.ts
2
+ var serverOnlyRealtimeProperties = /* @__PURE__ */ new Set(["handler", "authorize"]);
3
+ function isIdentifierBoundary(value) {
4
+ return !value || !/[$\w]/.test(value);
5
+ }
6
+ function skipString(source, index, quote) {
7
+ let cursor = index + 1;
8
+ while (cursor < source.length) {
9
+ const char = source[cursor];
10
+ if (char === "\\") {
11
+ cursor += 2;
12
+ continue;
13
+ }
14
+ if (char === quote) {
15
+ return cursor + 1;
16
+ }
17
+ cursor += 1;
18
+ }
19
+ return cursor;
20
+ }
21
+ function skipLineComment(source, index) {
22
+ const end = source.indexOf("\n", index + 2);
23
+ return end === -1 ? source.length : end + 1;
24
+ }
25
+ function skipBlockComment(source, index) {
26
+ const end = source.indexOf("*/", index + 2);
27
+ return end === -1 ? source.length : end + 2;
28
+ }
29
+ function findRealtimePropertyValueEnd(source, index) {
30
+ let cursor = index;
31
+ let braceDepth = 0;
32
+ let bracketDepth = 0;
33
+ let parenDepth = 0;
34
+ while (cursor < source.length) {
35
+ const char = source[cursor];
36
+ const next = source[cursor + 1];
37
+ if (char === '"' || char === "'" || char === "`") {
38
+ cursor = skipString(source, cursor, char);
39
+ continue;
40
+ }
41
+ if (char === "/" && next === "/") {
42
+ cursor = skipLineComment(source, cursor);
43
+ continue;
44
+ }
45
+ if (char === "/" && next === "*") {
46
+ cursor = skipBlockComment(source, cursor);
47
+ continue;
48
+ }
49
+ if (char === "{") {
50
+ braceDepth += 1;
51
+ } else if (char === "}") {
52
+ if (braceDepth === 0 && bracketDepth === 0 && parenDepth === 0) {
53
+ return cursor;
54
+ }
55
+ braceDepth -= 1;
56
+ } else if (char === "[") {
57
+ bracketDepth += 1;
58
+ } else if (char === "]") {
59
+ bracketDepth -= 1;
60
+ } else if (char === "(") {
61
+ parenDepth += 1;
62
+ } else if (char === ")") {
63
+ parenDepth -= 1;
64
+ } else if (char === "," && braceDepth === 0 && bracketDepth === 0 && parenDepth === 0) {
65
+ return cursor;
66
+ }
67
+ cursor += 1;
68
+ }
69
+ return source.length;
70
+ }
71
+ function findClosingBrace(source, index) {
72
+ let cursor = index;
73
+ let depth = 0;
74
+ while (cursor < source.length) {
75
+ const char = source[cursor];
76
+ const next = source[cursor + 1];
77
+ if (char === '"' || char === "'" || char === "`") {
78
+ cursor = skipString(source, cursor, char);
79
+ continue;
80
+ }
81
+ if (char === "/" && next === "/") {
82
+ cursor = skipLineComment(source, cursor);
83
+ continue;
84
+ }
85
+ if (char === "/" && next === "*") {
86
+ cursor = skipBlockComment(source, cursor);
87
+ continue;
88
+ }
89
+ if (char === "{") {
90
+ depth += 1;
91
+ } else if (char === "}") {
92
+ depth -= 1;
93
+ if (depth === 0) {
94
+ return cursor;
95
+ }
96
+ }
97
+ cursor += 1;
98
+ }
99
+ return -1;
100
+ }
101
+ function applyReplacements(source, replacements) {
102
+ if (replacements.length === 0) {
103
+ return source;
104
+ }
105
+ let output = "";
106
+ let cursor = 0;
107
+ const ordered = [...replacements].sort((left, right) => left.start - right.start);
108
+ for (const replacement of ordered) {
109
+ output += source.slice(cursor, replacement.start);
110
+ output += replacement.text;
111
+ cursor = replacement.end;
112
+ }
113
+ return output + source.slice(cursor);
114
+ }
115
+ function extractObjectPropertyValue(objectSource, propertyName) {
116
+ let cursor = 1;
117
+ while (cursor < objectSource.length - 1) {
118
+ const char = objectSource[cursor];
119
+ const next = objectSource[cursor + 1];
120
+ if (char === '"' || char === "'" || char === "`") {
121
+ cursor = skipString(objectSource, cursor, char);
122
+ continue;
123
+ }
124
+ if (char === "/" && next === "/") {
125
+ cursor = skipLineComment(objectSource, cursor);
126
+ continue;
127
+ }
128
+ if (char === "/" && next === "*") {
129
+ cursor = skipBlockComment(objectSource, cursor);
130
+ continue;
131
+ }
132
+ const match = objectSource.slice(cursor).match(/^[$A-Z_a-z][$\w]*/);
133
+ const name = match?.[0];
134
+ if (!name || name !== propertyName) {
135
+ cursor += 1;
136
+ continue;
137
+ }
138
+ const afterName = cursor + name.length;
139
+ if (!isIdentifierBoundary(objectSource[cursor - 1]) || !isIdentifierBoundary(objectSource[afterName])) {
140
+ cursor += name.length;
141
+ continue;
142
+ }
143
+ let colon = afterName;
144
+ while (/\s/.test(objectSource[colon] ?? "")) {
145
+ colon += 1;
146
+ }
147
+ if (objectSource[colon] !== ":") {
148
+ cursor += name.length;
149
+ continue;
150
+ }
151
+ const valueStart = colon + 1;
152
+ const valueEnd = findRealtimePropertyValueEnd(objectSource, valueStart);
153
+ return objectSource.slice(valueStart, valueEnd).trim();
154
+ }
155
+ return void 0;
156
+ }
157
+ function collectRealtimeDefinitionExports(source) {
158
+ const definitions = [];
159
+ let cursor = 0;
160
+ while (cursor < source.length) {
161
+ const char = source[cursor];
162
+ const next = source[cursor + 1];
163
+ if (char === '"' || char === "'" || char === "`") {
164
+ cursor = skipString(source, cursor, char);
165
+ continue;
166
+ }
167
+ if (char === "/" && next === "/") {
168
+ cursor = skipLineComment(source, cursor);
169
+ continue;
170
+ }
171
+ if (char === "/" && next === "*") {
172
+ cursor = skipBlockComment(source, cursor);
173
+ continue;
174
+ }
175
+ const match = source.slice(cursor).match(/^export\s+const\s+([$A-Z_a-z][$\w]*)\s*=\s*(query|mutation)\s*\(/);
176
+ const exportedName = match?.[1];
177
+ const factoryName = match?.[2];
178
+ if (!exportedName || !factoryName) {
179
+ cursor += 1;
180
+ continue;
181
+ }
182
+ let objectStart = cursor + match[0].length;
183
+ while (/\s/.test(source[objectStart] ?? "")) {
184
+ objectStart += 1;
185
+ }
186
+ if (source[objectStart] !== "{") {
187
+ cursor += match[0].length;
188
+ continue;
189
+ }
190
+ const objectEnd = findClosingBrace(source, objectStart);
191
+ if (objectEnd === -1) {
192
+ cursor += match[0].length;
193
+ continue;
194
+ }
195
+ const objectSource = source.slice(objectStart, objectEnd + 1);
196
+ definitions.push({
197
+ exportedName,
198
+ factoryName,
199
+ nameValue: extractObjectPropertyValue(objectSource, "name")
200
+ });
201
+ cursor = objectEnd + 1;
202
+ }
203
+ return definitions;
204
+ }
205
+ function createRealtimeClientDefinitionModule(source) {
206
+ const definitions = collectRealtimeDefinitionExports(source);
207
+ if (definitions.length === 0) {
208
+ return stripRealtimeServerHandlers(source);
209
+ }
210
+ const factories = [...new Set(definitions.map((definition) => definition.factoryName))];
211
+ return [
212
+ `import { ${factories.join(", ")} } from '@holo-js/adapter-next/realtime'`,
213
+ "",
214
+ ...definitions.flatMap((definition) => [
215
+ `export const ${definition.exportedName} = ${definition.factoryName}({`,
216
+ ...definition.nameValue ? [` name: ${definition.nameValue},`] : [],
217
+ " handler: undefined,",
218
+ "})",
219
+ ""
220
+ ])
221
+ ].join("\n");
222
+ }
223
+ function stripRealtimeServerHandlers(source) {
224
+ const replacements = [];
225
+ let cursor = 0;
226
+ while (cursor < source.length) {
227
+ const char = source[cursor];
228
+ const next = source[cursor + 1];
229
+ if (char === '"' || char === "'" || char === "`") {
230
+ cursor = skipString(source, cursor, char);
231
+ continue;
232
+ }
233
+ if (char === "/" && next === "/") {
234
+ cursor = skipLineComment(source, cursor);
235
+ continue;
236
+ }
237
+ if (char === "/" && next === "*") {
238
+ cursor = skipBlockComment(source, cursor);
239
+ continue;
240
+ }
241
+ const match = source.slice(cursor).match(/^[$A-Z_a-z][$\w]*/);
242
+ const name = match?.[0];
243
+ if (!name || !serverOnlyRealtimeProperties.has(name)) {
244
+ cursor += 1;
245
+ continue;
246
+ }
247
+ const afterName = cursor + name.length;
248
+ if (!isIdentifierBoundary(source[cursor - 1]) || !isIdentifierBoundary(source[afterName])) {
249
+ cursor += name.length;
250
+ continue;
251
+ }
252
+ let colon = afterName;
253
+ while (/\s/.test(source[colon] ?? "")) {
254
+ colon += 1;
255
+ }
256
+ if (source[colon] !== ":") {
257
+ cursor += name.length;
258
+ continue;
259
+ }
260
+ const valueStart = colon + 1;
261
+ const valueEnd = findRealtimePropertyValueEnd(source, valueStart);
262
+ replacements.push({
263
+ start: valueStart,
264
+ end: valueEnd,
265
+ text: " undefined"
266
+ });
267
+ cursor = valueEnd;
268
+ }
269
+ return applyReplacements(source, replacements);
270
+ }
271
+
272
+ // src/realtime-definition-loader.ts
273
+ function realtimeDefinitionLoader(source) {
274
+ this.cacheable?.();
275
+ return createRealtimeClientDefinitionModule(source);
276
+ }
277
+ export {
278
+ realtimeDefinitionLoader as default
279
+ };
@@ -0,0 +1,7 @@
1
+ import * as _holo_js_realtime from '@holo-js/realtime';
2
+ import { mutation as mutation$1 } from '@holo-js/realtime';
3
+
4
+ declare const query: typeof _holo_js_realtime.defineRealtimeQuery;
5
+ declare const mutation: typeof mutation$1;
6
+
7
+ export { mutation, query };
@@ -0,0 +1,113 @@
1
+ "use client";
2
+ import {
3
+ createNextRenderableError,
4
+ normalizeNextClientHttpError,
5
+ renderNextClientHttpErrorPage
6
+ } from "./chunk-3RI2KDLY.mjs";
7
+
8
+ // src/realtime.ts
9
+ import { useEffect, useSyncExternalStore } from "react";
10
+ import {
11
+ configureRealtimeClientRuntime,
12
+ configureRealtimeClientTransport,
13
+ createBroadcastRealtimeTransport,
14
+ getRealtimeQueryStore
15
+ } from "@holo-js/realtime/client";
16
+ import {
17
+ mutation as createRealtimeMutation,
18
+ query as createRealtimeQuery
19
+ } from "@holo-js/realtime";
20
+ var currentRealtimeError;
21
+ var realtimeErrorListeners = /* @__PURE__ */ new Set();
22
+ function subscribeRealtimeError(listener) {
23
+ realtimeErrorListeners.add(listener);
24
+ return () => {
25
+ realtimeErrorListeners.delete(listener);
26
+ };
27
+ }
28
+ function emitRealtimeError(error) {
29
+ const httpError = normalizeNextClientHttpError(error);
30
+ if (!httpError) {
31
+ return;
32
+ }
33
+ currentRealtimeError = createNextRenderableError(httpError);
34
+ renderNextClientHttpErrorPage(httpError);
35
+ for (const listener of realtimeErrorListeners) {
36
+ listener();
37
+ }
38
+ }
39
+ function getRealtimeErrorSnapshot() {
40
+ return currentRealtimeError;
41
+ }
42
+ function consumeRealtimeError() {
43
+ const error = currentRealtimeError;
44
+ currentRealtimeError = void 0;
45
+ return error;
46
+ }
47
+ function createErrorHandlingRealtimeTransport(transport) {
48
+ return {
49
+ async query(name, args) {
50
+ try {
51
+ return await transport.query(name, args);
52
+ } catch (error) {
53
+ emitRealtimeError(error);
54
+ throw error;
55
+ }
56
+ },
57
+ async mutate(name, args) {
58
+ try {
59
+ return await transport.mutate(name, args);
60
+ } catch (error) {
61
+ emitRealtimeError(error);
62
+ throw error;
63
+ }
64
+ },
65
+ subscribe(name, args, listener, onError) {
66
+ return transport.subscribe(name, args, listener, (error) => {
67
+ emitRealtimeError(error);
68
+ onError(error);
69
+ });
70
+ }
71
+ };
72
+ }
73
+ var query = createRealtimeQuery;
74
+ var mutation = ((input) => {
75
+ const definition = createRealtimeMutation(input);
76
+ const wrappedDefinition = ((...args) => {
77
+ const result = Reflect.apply(definition, void 0, args);
78
+ void result.catch(emitRealtimeError);
79
+ return result;
80
+ });
81
+ Object.defineProperties(wrappedDefinition, Object.getOwnPropertyDescriptors(definition));
82
+ return wrappedDefinition;
83
+ });
84
+ function useReactiveRealtimeQuery(definition, args) {
85
+ const realtimeError = useSyncExternalStore(
86
+ subscribeRealtimeError,
87
+ getRealtimeErrorSnapshot,
88
+ getRealtimeErrorSnapshot
89
+ );
90
+ if (realtimeError) {
91
+ consumeRealtimeError();
92
+ throw realtimeError;
93
+ }
94
+ const store = getRealtimeQueryStore(definition, args);
95
+ useEffect(() => {
96
+ store.connect();
97
+ }, [store]);
98
+ const snapshot = useSyncExternalStore(
99
+ store.subscribe,
100
+ () => store.snapshot,
101
+ () => store.snapshot
102
+ );
103
+ return snapshot?.data;
104
+ }
105
+ configureRealtimeClientRuntime({
106
+ handleError: emitRealtimeError,
107
+ useQuery: useReactiveRealtimeQuery
108
+ });
109
+ configureRealtimeClientTransport(createErrorHandlingRealtimeTransport(createBroadcastRealtimeTransport()));
110
+ export {
111
+ mutation,
112
+ query
113
+ };
package/dist/runtime.d.ts CHANGED
@@ -55,6 +55,7 @@ interface GeneratedChannelRegistryEntry {
55
55
  readonly sourcePath: string;
56
56
  readonly pattern: string;
57
57
  readonly exportName?: string;
58
+ readonly guard?: string;
58
59
  readonly type: 'private' | 'presence';
59
60
  readonly params: readonly string[];
60
61
  readonly whispers: readonly string[];
@@ -115,6 +116,7 @@ declare function runWithNextRequest<TValue>(request: NextRequestLike, callback:
115
116
  type NextHoloRuntimeOptions = CreateHoloOptions & {
116
117
  readonly projectRoot: string;
117
118
  };
119
+ declare function createNextRequestContext(request: Request): NextRequestLike;
118
120
  declare function createNextHoloHelpers<TCustom extends HoloConfigMap = HoloConfigMap>(options: NextHoloRuntimeOptions): {
119
121
  getApp(): Promise<{
120
122
  projectRoot: string;
@@ -134,4 +136,4 @@ declare function createNextHoloHelpers<TCustom extends HoloConfigMap = HoloConfi
134
136
  config: <TPath extends DotPath<LoadedHoloConfig<TCustom>["all"]>>(path: TPath) => Promise<ValueAtPath<LoadedHoloConfig<TCustom>["all"], TPath>>;
135
137
  };
136
138
 
137
- export { type NextHoloRuntimeOptions, type NextRequestLike, createNextHoloHelpers, runWithNextRequest };
139
+ export { type NextHoloRuntimeOptions, type NextRequestLike, createNextHoloHelpers, createNextRequestContext, runWithNextRequest };
package/dist/runtime.mjs CHANGED
@@ -1,6 +1,4 @@
1
1
  // src/runtime.ts
2
- import { cookies, headers } from "next/headers";
3
- import { forbidden, notFound } from "next/navigation";
4
2
  import { initializeHolo } from "@holo-js/core";
5
3
 
6
4
  // src/request-context.ts
@@ -18,6 +16,11 @@ function runWithNextRequest(request, callback) {
18
16
  }
19
17
 
20
18
  // src/runtime.ts
19
+ function createNextHttpAccessFallbackError(status, message) {
20
+ const error = new Error(message);
21
+ error.digest = `NEXT_HTTP_ERROR_FALLBACK;${status}`;
22
+ throw error;
23
+ }
21
24
  function safeDecodeCookieSegment(value) {
22
25
  try {
23
26
  return decodeURIComponent(value);
@@ -83,6 +86,38 @@ function parseResponseCookie(cookie) {
83
86
  options
84
87
  };
85
88
  }
89
+ function parseRequestCookies(header) {
90
+ const cookies = /* @__PURE__ */ new Map();
91
+ for (const segment of header?.split(";") ?? []) {
92
+ const separator = segment.indexOf("=");
93
+ if (separator <= 0) {
94
+ continue;
95
+ }
96
+ const name = safeDecodeCookieSegment(segment.slice(0, separator).trim());
97
+ const value = safeDecodeCookieSegment(segment.slice(separator + 1).trim());
98
+ if (name) {
99
+ cookies.set(name, value);
100
+ }
101
+ }
102
+ return cookies;
103
+ }
104
+ function createNextRequestContext(request) {
105
+ const nextRequest = request;
106
+ const parsedCookies = nextRequest.cookies ? void 0 : parseRequestCookies(request.headers.get("cookie"));
107
+ return {
108
+ headers: request.headers,
109
+ cookies: {
110
+ get(name) {
111
+ const nextCookie = nextRequest.cookies?.get(name);
112
+ if (nextCookie && typeof nextCookie.value === "string") {
113
+ return { value: nextCookie.value };
114
+ }
115
+ const value = parsedCookies?.get(name);
116
+ return typeof value === "string" ? { value } : void 0;
117
+ }
118
+ }
119
+ };
120
+ }
86
121
  function resolveNextAuthRequestAccessors() {
87
122
  return {
88
123
  async getCookie(name) {
@@ -90,6 +125,7 @@ function resolveNextAuthRequestAccessors() {
90
125
  if (request) {
91
126
  return request.cookies.get(name)?.value;
92
127
  }
128
+ const { cookies } = await import("next/headers.js");
93
129
  const store = await cookies();
94
130
  return store.get(name)?.value;
95
131
  },
@@ -98,6 +134,7 @@ function resolveNextAuthRequestAccessors() {
98
134
  if (request) {
99
135
  return request.headers.get(name) ?? void 0;
100
136
  }
137
+ const { headers } = await import("next/headers.js");
101
138
  const requestHeaders = await headers();
102
139
  return requestHeaders.get(name) ?? void 0;
103
140
  },
@@ -106,11 +143,12 @@ function resolveNextAuthRequestAccessors() {
106
143
  if (!parsed) {
107
144
  return;
108
145
  }
146
+ const { cookies } = await import("next/headers.js");
109
147
  const store = await cookies();
110
148
  store.set(parsed.name, parsed.value, parsed.options);
111
149
  },
112
150
  async redirectResponse(url) {
113
- const { redirect } = await import("next/navigation");
151
+ const { redirect } = await import("next/navigation.js");
114
152
  redirect(url);
115
153
  }
116
154
  };
@@ -122,9 +160,9 @@ function createNextHoloHelpers(options) {
122
160
  authorizationError: options.authorizationError ?? {
123
161
  createError(decision) {
124
162
  if (decision.status === 404) {
125
- notFound();
163
+ return createNextHttpAccessFallbackError(404, decision.message ?? "Resource not found.");
126
164
  }
127
- forbidden();
165
+ return createNextHttpAccessFallbackError(403, decision.message ?? "Forbidden");
128
166
  }
129
167
  }
130
168
  });
@@ -132,24 +170,21 @@ function createNextHoloHelpers(options) {
132
170
  const runtime = await resolveRuntime();
133
171
  return runtime.config(path);
134
172
  };
173
+ const resolveRuntimeProjection = async () => {
174
+ const runtime = await resolveRuntime();
175
+ return {
176
+ projectRoot: runtime.projectRoot,
177
+ config: runtime.loadedConfig,
178
+ registry: runtime.registry,
179
+ runtime
180
+ };
181
+ };
135
182
  return {
136
183
  async getApp() {
137
- const runtime = await resolveRuntime();
138
- return {
139
- projectRoot: runtime.projectRoot,
140
- config: runtime.loadedConfig,
141
- registry: runtime.registry,
142
- runtime
143
- };
184
+ return await resolveRuntimeProjection();
144
185
  },
145
186
  async getProject() {
146
- const runtime = await resolveRuntime();
147
- return {
148
- projectRoot: runtime.projectRoot,
149
- config: runtime.loadedConfig,
150
- registry: runtime.registry,
151
- runtime
152
- };
187
+ return await resolveRuntimeProjection();
153
188
  },
154
189
  async getSession() {
155
190
  const runtime = await resolveRuntime();
@@ -165,5 +200,6 @@ function createNextHoloHelpers(options) {
165
200
  }
166
201
  export {
167
202
  createNextHoloHelpers,
203
+ createNextRequestContext,
168
204
  runWithNextRequest
169
205
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@holo-js/adapter-next",
3
- "version": "0.1.8",
3
+ "version": "0.2.0",
4
4
  "description": "Holo-JS Framework - Next.js adapter",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,6 +20,11 @@
20
20
  "import": "./dist/client.mjs",
21
21
  "default": "./dist/client.mjs"
22
22
  },
23
+ "./realtime": {
24
+ "types": "./dist/realtime.d.ts",
25
+ "import": "./dist/realtime.mjs",
26
+ "default": "./dist/realtime.mjs"
27
+ },
23
28
  "./runtime": {
24
29
  "types": "./dist/runtime.d.ts",
25
30
  "import": "./dist/runtime.mjs",
@@ -38,20 +43,25 @@
38
43
  "test": "vitest --run"
39
44
  },
40
45
  "dependencies": {
41
- "@holo-js/config": "^0.1.8",
42
- "@holo-js/core": "^0.1.8"
46
+ "@holo-js/config": "^0.2.0",
47
+ "@holo-js/core": "^0.2.0"
43
48
  },
44
49
  "peerDependencies": {
45
- "@holo-js/forms": "^0.1.8",
50
+ "@holo-js/forms": "^0.2.0",
51
+ "@holo-js/realtime": "^0.2.0",
46
52
  "next": "^16.2.4",
47
53
  "react": "^19.2.6"
48
54
  },
49
55
  "peerDependenciesMeta": {
50
56
  "@holo-js/forms": {
51
57
  "optional": true
58
+ },
59
+ "@holo-js/realtime": {
60
+ "optional": true
52
61
  }
53
62
  },
54
63
  "devDependencies": {
64
+ "@holo-js/realtime": "^0.2.0",
55
65
  "@types/node": "^22.10.2",
56
66
  "next": "^16.2.4",
57
67
  "tsup": "^8.3.5",