@alpaca-headless/alpaca-headless-nextjs 1.0.281 → 1.0.527

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.
Files changed (37) hide show
  1. package/dist/EditorIntegration.d.ts +6 -0
  2. package/dist/EditorIntegration.js +5 -0
  3. package/dist/EditorIntegrationClient.d.ts +9 -0
  4. package/dist/EditorIntegrationClient.js +54 -0
  5. package/dist/client-components/MultiComponentEditor.d.ts +12 -0
  6. package/dist/client-components/MultiComponentEditor.js +47 -0
  7. package/dist/client-components/index.d.ts +1 -1
  8. package/dist/client-components/index.js +1 -1
  9. package/dist/handleBasicAuthRoute.d.ts +8 -0
  10. package/dist/handleBasicAuthRoute.js +42 -0
  11. package/dist/index.d.ts +4 -1
  12. package/dist/index.js +11 -3
  13. package/dist/middleware/handleRequest.d.ts +3 -2
  14. package/dist/middleware/handleRequest.js +15 -9
  15. package/dist/middleware/index.js +0 -2
  16. package/dist/proxy/index.d.ts +8 -0
  17. package/dist/proxy/index.js +77 -0
  18. package/dist/useExposeRefreshFunction.d.ts +7 -0
  19. package/dist/useExposeRefreshFunction.js +32 -0
  20. package/package.json +16 -9
  21. package/src/EditorIntegration.tsx +11 -0
  22. package/src/EditorIntegrationClient.tsx +74 -0
  23. package/src/client-components/MultiComponentEditor.tsx +133 -0
  24. package/src/client-components/index.ts +2 -1
  25. package/src/handleBasicAuthRoute.ts +62 -0
  26. package/src/index.ts +13 -3
  27. package/src/middleware/handleRequest.ts +21 -8
  28. package/src/middleware/index.ts +0 -4
  29. package/src/proxy/index.ts +108 -0
  30. package/src/useExposeRefreshFunction.ts +45 -0
  31. package/tsconfig.json +1 -2
  32. package/dist/client-components/ClientLink.d.ts +0 -6
  33. package/dist/client-components/ClientLink.js +0 -39
  34. package/dist/configure.d.ts +0 -1
  35. package/dist/configure.js +0 -10
  36. package/src/client-components/ClientLink.tsx +0 -46
  37. package/src/configure.ts +0 -12
@@ -0,0 +1,6 @@
1
+ export type EditorIntegrationProps = {
2
+ timings?: {
3
+ [key: string]: number;
4
+ };
5
+ };
6
+ export declare function EditorIntegration(props: EditorIntegrationProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,5 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { EditorIntegrationClient } from "./EditorIntegrationClient";
3
+ export function EditorIntegration(props) {
4
+ return _jsx(EditorIntegrationClient, Object.assign({}, props));
5
+ }
@@ -0,0 +1,9 @@
1
+ export declare function EditorIntegrationClient({ timings, }: {
2
+ timings?: {
3
+ [key: string]: number;
4
+ };
5
+ }): import("react/jsx-runtime").JSX.Element;
6
+ export type ComponentSelectedEvent = {
7
+ type: "componentSelected";
8
+ componentIds: string[];
9
+ };
@@ -0,0 +1,54 @@
1
+ "use client";
2
+ import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useEffect } from "react";
4
+ import useExposeRefreshFunction from "./useExposeRefreshFunction";
5
+ export function EditorIntegrationClient({ timings, }) {
6
+ useExposeRefreshFunction();
7
+ useEffect(() => {
8
+ const handleKeyDown = (event) => {
9
+ if (event.ctrlKey && event.key === "F11") {
10
+ event.preventDefault();
11
+ window.parent.postMessage({ type: "editor-exitFullscreen" }, "*");
12
+ }
13
+ if (event.key === "F2") {
14
+ event.preventDefault();
15
+ window.parent.postMessage({ type: "editor-keyDown", key: "F2" }, "*");
16
+ }
17
+ };
18
+ window.addEventListener("keydown", handleKeyDown);
19
+ window.parent.postMessage({ type: "editor-timings", timings }, "*");
20
+ return () => {
21
+ window.removeEventListener("keydown", handleKeyDown);
22
+ };
23
+ }, []);
24
+ return (_jsx(_Fragment, { children: _jsx("style", { children: `
25
+ .a-editor-mce {
26
+ display:flex;
27
+ gap: 10px;
28
+ padding: 30px;
29
+ background-color: #f5f5f5;
30
+ flex-wrap: wrap;
31
+ align-items: center;
32
+ }
33
+ .a-editor-mce-thumbnail {
34
+ display:grid;
35
+ padding: 10px;
36
+ place-items: center;
37
+ overflow: hidden;
38
+ }
39
+ .a-editor-mce-thumbnail--selected {
40
+ box-shadow: 0 0 3px 3px rgb(75 89 255 / 50%);
41
+ }
42
+ .a-editor-mce-thumbnail:hover {
43
+ box-shadow: 0 0 10px 5px rgba(0, 0, 0, 0.5);
44
+ }
45
+ [contentEditable]:empty:before {
46
+ content: attr(placeholder);
47
+ opacity: 0.6;
48
+ }
49
+
50
+ [contenteditable] {
51
+ outline: 0px solid transparent;
52
+ }
53
+ ` }) }));
54
+ }
@@ -0,0 +1,12 @@
1
+ import { ComponentData } from "@alpaca-headless/alpaca-headless";
2
+ import { ReactNode } from "react";
3
+ interface MultiComponentEditorProps {
4
+ children: ReactNode;
5
+ component: ComponentData;
6
+ placeholderName: string;
7
+ thumbZoom?: number;
8
+ thumbWidth?: string;
9
+ thumbHeight?: string;
10
+ }
11
+ export declare function MultiComponentEditor({ children, component, placeholderName, thumbZoom, thumbWidth, thumbHeight, }: MultiComponentEditorProps): import("react/jsx-runtime").JSX.Element | undefined;
12
+ export {};
@@ -0,0 +1,47 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import React, { useState, useEffect, Fragment, useCallback, } from "react";
4
+ export function MultiComponentEditor({ children, component, placeholderName, thumbZoom, thumbWidth = "200px", thumbHeight = "112px", }) {
5
+ const [selectedId, setSelectedId] = useState(null);
6
+ const placeholder = component.placeholders.find((x) => x.name === placeholderName);
7
+ if (!placeholder)
8
+ return;
9
+ const components = placeholder.components;
10
+ if (!components)
11
+ return;
12
+ const handleMessage = useCallback((event) => {
13
+ if (event.data.type === "componentsSelected") {
14
+ setSelectedId(event.data.componentIds[0]);
15
+ }
16
+ }, [components]);
17
+ useEffect(() => {
18
+ window.addEventListener("message", handleMessage);
19
+ return () => {
20
+ window.removeEventListener("message", handleMessage);
21
+ };
22
+ }, []);
23
+ const selectedIndex = components.findIndex((x) => x.id === selectedId);
24
+ const childrenArray = React.Children.toArray(children);
25
+ const filteredChildren = childrenArray.filter((child) => child.type !== "script");
26
+ return (_jsxs(_Fragment, { children: [filteredChildren[selectedIndex < 0 ? 0 : selectedIndex], _jsxs("div", { className: "a-editor-mce", children: [_jsx("script", { "data-placeholder-start": placeholder.key, "data-orientation": "horizontal" }), filteredChildren.map((x, index) => thumbnail(x, index)), _jsx("script", { "data-placeholder-end": placeholder.key })] })] }));
27
+ function thumbnail(x, index) {
28
+ var _a, _b, _c, _d, _e;
29
+ const style = {};
30
+ if (thumbHeight) {
31
+ style.height = thumbHeight;
32
+ }
33
+ if (thumbWidth) {
34
+ style.width = thumbWidth;
35
+ }
36
+ const componentArray = (_a = x.props) === null || _a === void 0 ? void 0 : _a.children;
37
+ const component = components[index];
38
+ return (_jsxs(Fragment, { children: [_jsxs("div", { className: "a-editor-mce-thumbnail" +
39
+ (index === selectedIndex ? " a-editor-mce-thumbnail--selected" : ""), style: style, onClick: () => {
40
+ selectComponents([components[index].id]);
41
+ }, children: [_jsx("script", { "data-component-start": component.id, "data-itemid": ((_c = (_b = component._editor) === null || _b === void 0 ? void 0 : _b.linkedComponentItem) === null || _c === void 0 ? void 0 : _c.id) || component.id, "data-layoutid": (_e = (_d = component._editor) === null || _d === void 0 ? void 0 : _d.hostingPageItem) === null || _e === void 0 ? void 0 : _e.id }), _jsx("div", { style: { pointerEvents: "none", zoom: thumbZoom || 0.25 }, children: componentArray.slice(1, -1) }), _jsx("script", { "data-component-end": component.id })] }), _jsx("div", { "data-dropzone": components[index].id })] }, index));
42
+ }
43
+ }
44
+ function selectComponents(componentIds) {
45
+ var _a;
46
+ (_a = window.top) === null || _a === void 0 ? void 0 : _a.window.postMessage({ componentIds, type: "componentsSelected" }, "*");
47
+ }
@@ -1 +1 @@
1
- export { ClientLink } from "./ClientLink";
1
+ export { MultiComponentEditor } from "./MultiComponentEditor";
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- export { ClientLink } from "./ClientLink";
2
+ export { MultiComponentEditor } from "./MultiComponentEditor";
@@ -0,0 +1,8 @@
1
+ import { ApiConfig, RenderOptions } from "@alpaca-headless/alpaca-headless";
2
+ import { NextRequest } from "next/server";
3
+ export declare function handleBasicAuthRoute({ request, mapHost, renderOptions, apiConfig, }: {
4
+ request: NextRequest;
5
+ mapHost: (host: string) => string;
6
+ renderOptions: RenderOptions;
7
+ apiConfig?: ApiConfig;
8
+ }): Promise<Response | undefined>;
@@ -0,0 +1,42 @@
1
+ import { resolveRoute, } from "@alpaca-headless/alpaca-headless";
2
+ import { getApiHeaders } from ".";
3
+ export async function handleBasicAuthRoute({ request, mapHost, renderOptions, apiConfig, }) {
4
+ const urlSearchParams = new URLSearchParams(request.nextUrl.search);
5
+ const nextSearchParams = {};
6
+ for (const [key, value] of urlSearchParams.entries()) {
7
+ nextSearchParams[key] = value;
8
+ }
9
+ const config = apiConfig || {};
10
+ if (!config.headers) {
11
+ config.headers = getApiHeaders();
12
+ }
13
+ const routeData = await resolveRoute({
14
+ path: request.nextUrl.pathname,
15
+ searchParams: nextSearchParams,
16
+ host: mapHost(request.headers.get("host") || ""),
17
+ renderOptions,
18
+ renderings: {},
19
+ apiConfig: config,
20
+ });
21
+ if (routeData.result.type === "redirect") {
22
+ return new Response(null, {
23
+ status: routeData.result.redirectType === "permanent" ? 301 : 302,
24
+ headers: {
25
+ Location: routeData.result.location,
26
+ },
27
+ });
28
+ }
29
+ if (routeData.result.type === "unauthorized") {
30
+ if (routeData.result.auth)
31
+ return new Response(null, {
32
+ status: 401,
33
+ headers: {
34
+ "WWW-Authenticate": routeData.result.auth.replace(", Bearer", ""),
35
+ },
36
+ });
37
+ else
38
+ return new Response(null, {
39
+ status: 401,
40
+ });
41
+ }
42
+ }
package/dist/index.d.ts CHANGED
@@ -1 +1,4 @@
1
- export * from "../../alpaca-headless/src/index";
1
+ export { EditorIntegration } from "./EditorIntegration";
2
+ export declare function getApiHeaders(): Headers;
3
+ export { handleRequest } from "./middleware/handleRequest";
4
+ export { proxy } from "./proxy";
package/dist/index.js CHANGED
@@ -1,3 +1,11 @@
1
- import { init } from "./configure";
2
- init();
3
- export * from "../../alpaca-headless/src/index";
1
+ import { headers } from "next/headers";
2
+ export { EditorIntegration } from "./EditorIntegration";
3
+ export function getApiHeaders() {
4
+ const requestHeaders = headers();
5
+ const apiHeaders = new Headers();
6
+ apiHeaders.set("Cookie", requestHeaders.get("Cookie") || "");
7
+ apiHeaders.set("Authorization", requestHeaders.get("Authorization") || "");
8
+ return apiHeaders;
9
+ }
10
+ export { handleRequest } from "./middleware/handleRequest";
11
+ export { proxy } from "./proxy";
@@ -1,7 +1,8 @@
1
- import { RenderOptions } from "../../../alpaca-headless/src";
1
+ import { ApiConfig, RenderOptions } from "@alpaca-headless/alpaca-headless";
2
2
  import { NextRequest } from "next/server";
3
- export declare function handleRequest({ request, mapHost, renderOptions, }: {
3
+ export declare function handleRequest({ request, mapHost, renderOptions, apiConfig, }: {
4
4
  request: NextRequest;
5
5
  mapHost: (host: string) => string;
6
6
  renderOptions: RenderOptions;
7
+ apiConfig?: ApiConfig;
7
8
  }): Promise<Response | undefined>;
@@ -1,31 +1,37 @@
1
- import { resolveRoute } from "../../../alpaca-headless/src";
2
- export async function handleRequest({ request, mapHost, renderOptions, }) {
1
+ import { resolveRoute, } from "@alpaca-headless/alpaca-headless";
2
+ import { getApiHeaders } from "..";
3
+ export async function handleRequest({ request, mapHost, renderOptions, apiConfig, }) {
3
4
  const urlSearchParams = new URLSearchParams(request.nextUrl.search);
4
5
  const nextSearchParams = {};
5
6
  for (const [key, value] of urlSearchParams.entries()) {
6
7
  nextSearchParams[key] = value;
7
8
  }
8
- const result = await resolveRoute({
9
+ const config = apiConfig || {};
10
+ if (!config.headers) {
11
+ config.headers = getApiHeaders();
12
+ }
13
+ const routeData = await resolveRoute({
9
14
  path: request.nextUrl.pathname,
10
15
  searchParams: nextSearchParams,
11
16
  host: mapHost(request.headers.get("host") || ""),
12
17
  renderOptions,
13
18
  renderings: {},
19
+ apiConfig: config,
14
20
  });
15
- if (result.type === "redirect") {
21
+ if (routeData.result.type === "redirect") {
16
22
  return new Response(null, {
17
- status: result.redirectType === "permanent" ? 301 : 302,
23
+ status: routeData.result.redirectType === "permanent" ? 301 : 302,
18
24
  headers: {
19
- Location: result.location,
25
+ Location: routeData.result.location,
20
26
  },
21
27
  });
22
28
  }
23
- if (result.type === "unauthorized") {
24
- if (result.auth)
29
+ if (routeData.result.type === "unauthorized") {
30
+ if (routeData.result.auth)
25
31
  return new Response(null, {
26
32
  status: 401,
27
33
  headers: {
28
- "WWW-Authenticate": result.auth.replace(", Bearer", ""),
34
+ "WWW-Authenticate": routeData.result.auth.replace(", Bearer", ""),
29
35
  },
30
36
  });
31
37
  else
@@ -1,3 +1 @@
1
- import { init } from "../configure";
2
- init();
3
1
  export * from "./handleRequest";
@@ -0,0 +1,8 @@
1
+ import { NextResponse } from "next/server";
2
+ declare function GET(req: Request, target: string): Promise<NextResponse<unknown>>;
3
+ declare function POST(req: Request): Promise<NextResponse<unknown>>;
4
+ export declare const proxy: {
5
+ POST: typeof POST;
6
+ GET: typeof GET;
7
+ };
8
+ export {};
@@ -0,0 +1,77 @@
1
+ import axios from "axios";
2
+ // import { HttpsProxyAgent } from "https-proxy-agent";
3
+ import { NextResponse } from "next/server";
4
+ async function GET(req, target
5
+ //{ proxy }: { proxy?: string }
6
+ ) {
7
+ const reqUrl = new URL(req.url);
8
+ const url = target + reqUrl.pathname + "?" + reqUrl.searchParams.toString();
9
+ const headers = {
10
+ Authorization: req.headers.get("Authorization") || "",
11
+ Cookie: req.headers.get("Cookie") || "",
12
+ };
13
+ // const agent = proxy ? new HttpsProxyAgent(proxy) : undefined;
14
+ const externalResponse = await axios.get(url, {
15
+ headers: headers,
16
+ // httpAgent: agent,
17
+ // httpsAgent: agent,
18
+ responseType: "stream",
19
+ });
20
+ return new NextResponse(nodeReadableToReadableStream(externalResponse.data), {
21
+ status: externalResponse.status,
22
+ });
23
+ }
24
+ async function POST(req
25
+ //{ proxy }: { proxy?: string }
26
+ ) {
27
+ const reqUrl = new URL(req.url);
28
+ const body = await req.text();
29
+ const url = process.env.EDITOR_SERVICE_URL +
30
+ reqUrl.pathname +
31
+ "?" +
32
+ reqUrl.searchParams.toString();
33
+ const headers = {
34
+ "Content-Type": req.headers.get("Content-Type") || "",
35
+ Authorization: req.headers.get("Authorization") || "",
36
+ Cookie: req.headers.get("Cookie") || "",
37
+ };
38
+ // const agent = proxy ? new HttpsProxyAgent(proxy) : undefined;
39
+ const externalResponse = await axios.post(url, body, {
40
+ headers: headers,
41
+ // httpAgent: agent,
42
+ // httpsAgent: agent,
43
+ responseType: "stream",
44
+ });
45
+ const responseHeaders = getResponseHeaders(externalResponse);
46
+ return new NextResponse(nodeReadableToReadableStream(externalResponse.data), {
47
+ status: externalResponse.status,
48
+ headers: responseHeaders,
49
+ });
50
+ }
51
+ const getResponseHeaders = (externalResponse) => {
52
+ const responseHeaders = new Headers();
53
+ responseHeaders.set("Content-Type", externalResponse.headers["content-type"] || "");
54
+ responseHeaders.set("Set-Cookie", externalResponse.headers["set-cookie"] || "");
55
+ return responseHeaders;
56
+ };
57
+ function nodeReadableToReadableStream(nodeStream) {
58
+ return new ReadableStream({
59
+ start(controller) {
60
+ nodeStream.on("data", (chunk) => {
61
+ controller.enqueue(new Uint8Array(chunk));
62
+ });
63
+ nodeStream.on("end", () => {
64
+ controller.close();
65
+ });
66
+ nodeStream.on("error", (err) => {
67
+ controller.error(err);
68
+ });
69
+ },
70
+ pull() { },
71
+ cancel() { },
72
+ });
73
+ }
74
+ export const proxy = {
75
+ POST,
76
+ GET,
77
+ };
@@ -0,0 +1,7 @@
1
+ declare global {
2
+ interface Window {
3
+ requestRefresh?: (newUri?: string) => boolean;
4
+ }
5
+ }
6
+ declare const useExposeRefreshFunction: () => null;
7
+ export default useExposeRefreshFunction;
@@ -0,0 +1,32 @@
1
+ import { useRouter, useSearchParams } from "next/navigation";
2
+ import { useEffect, useState } from "react";
3
+ import uuid from "react-uuid";
4
+ const useExposeRefreshFunction = () => {
5
+ const router = useRouter();
6
+ const searchParams = useSearchParams();
7
+ const [refreshStart, setRefreshStart] = useState();
8
+ useEffect(() => {
9
+ // Expose the refresh function to the parent window
10
+ window.requestRefresh = (newUri) => {
11
+ console.log("refresh requested", newUri);
12
+ if (!newUri) {
13
+ const uri = new URL(window.location.href);
14
+ uri.searchParams.set("edit_rev", uuid().toString());
15
+ newUri = uri.toString();
16
+ }
17
+ router.replace(newUri, { scroll: false });
18
+ setRefreshStart(performance.now());
19
+ return true; // Indicate the function executed successfully
20
+ };
21
+ // Optionally clean up when the component unmounts
22
+ return () => {
23
+ delete window.requestRefresh;
24
+ };
25
+ }, [router]);
26
+ useEffect(() => {
27
+ if (refreshStart)
28
+ console.log("Refresh complete", performance.now() - refreshStart);
29
+ }, [searchParams]);
30
+ return null; // This hook doesn't render anything
31
+ };
32
+ export default useExposeRefreshFunction;
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@alpaca-headless/alpaca-headless-nextjs",
3
- "version": "1.0.281",
3
+ "version": "1.0.527",
4
4
  "type": "module",
5
5
  "description": "Alpaca Headless",
6
6
  "main": "dist/index.js",
7
7
  "exports": {
8
8
  ".": "./dist/index.js",
9
9
  "./client-components": "./dist/client-components",
10
- "./middleware": "./dist/middleware"
10
+ "./middleware": "./dist/middleware",
11
+ "./internals": "./dist/internals"
11
12
  },
12
13
  "typesVersions": {
13
14
  "*": {
@@ -16,6 +17,9 @@
16
17
  ],
17
18
  "middleware": [
18
19
  "./dist/middleware/index.d.ts"
20
+ ],
21
+ "internals": [
22
+ "./dist/internals/index.d.ts"
19
23
  ]
20
24
  }
21
25
  },
@@ -38,17 +42,20 @@
38
42
  },
39
43
  "homepage": "https://github.com/yourusername/your-module-name#readme",
40
44
  "devDependencies": {
41
- "@types/node": "^20.11.25",
42
- "@types/react": "18.2.67",
43
- "@types/react-dom": "18.2.22",
45
+ "@types/node": "^20.14.2",
46
+ "@types/react": "18.3.3",
47
+ "@types/react-dom": "18.3.0",
44
48
  "eslint": "^8",
45
- "eslint-config-next": "14.1.3",
49
+ "eslint-config-next": "14.2.10",
46
50
  "typescript": "^5"
47
51
  },
48
52
  "dependencies": {
49
- "next": "^14.1.4",
50
- "react": "^18",
51
- "react-dom": "^18",
53
+ "@alpaca-headless/alpaca-headless": "npm:@alpaca-headless/alpaca-headless-editor-preview@^1.0.522",
54
+ "axios": "^1.7.2",
55
+ "https-proxy-agent": "^7.0.4",
56
+ "next": "^14.2.4",
57
+ "react": "^18.3.1",
58
+ "react-dom": "^18.3.1",
52
59
  "react-uuid": "^2.0.0"
53
60
  }
54
61
  }
@@ -0,0 +1,11 @@
1
+ import { EditorIntegrationClient } from "./EditorIntegrationClient";
2
+
3
+ export type EditorIntegrationProps = {
4
+ timings?: {
5
+ [key: string]: number;
6
+ };
7
+ };
8
+
9
+ export function EditorIntegration(props: EditorIntegrationProps) {
10
+ return <EditorIntegrationClient {...props} />;
11
+ }
@@ -0,0 +1,74 @@
1
+ "use client";
2
+
3
+ import { useEffect } from "react";
4
+ import useExposeRefreshFunction from "./useExposeRefreshFunction";
5
+
6
+ export function EditorIntegrationClient({
7
+ timings,
8
+ }: {
9
+ timings?: {
10
+ [key: string]: number;
11
+ };
12
+ }) {
13
+ useExposeRefreshFunction();
14
+
15
+ useEffect(() => {
16
+ const handleKeyDown = (event: KeyboardEvent) => {
17
+ if (event.ctrlKey && event.key === "F11") {
18
+ event.preventDefault();
19
+ window.parent.postMessage({ type: "editor-exitFullscreen" }, "*");
20
+ }
21
+ if (event.key === "F2") {
22
+ event.preventDefault();
23
+ window.parent.postMessage({ type: "editor-keyDown", key: "F2" }, "*");
24
+ }
25
+ };
26
+
27
+ window.addEventListener("keydown", handleKeyDown);
28
+ window.parent.postMessage({ type: "editor-timings", timings }, "*");
29
+
30
+ return () => {
31
+ window.removeEventListener("keydown", handleKeyDown);
32
+ };
33
+ }, []);
34
+
35
+ return (
36
+ <>
37
+ <style>{`
38
+ .a-editor-mce {
39
+ display:flex;
40
+ gap: 10px;
41
+ padding: 30px;
42
+ background-color: #f5f5f5;
43
+ flex-wrap: wrap;
44
+ align-items: center;
45
+ }
46
+ .a-editor-mce-thumbnail {
47
+ display:grid;
48
+ padding: 10px;
49
+ place-items: center;
50
+ overflow: hidden;
51
+ }
52
+ .a-editor-mce-thumbnail--selected {
53
+ box-shadow: 0 0 3px 3px rgb(75 89 255 / 50%);
54
+ }
55
+ .a-editor-mce-thumbnail:hover {
56
+ box-shadow: 0 0 10px 5px rgba(0, 0, 0, 0.5);
57
+ }
58
+ [contentEditable]:empty:before {
59
+ content: attr(placeholder);
60
+ opacity: 0.6;
61
+ }
62
+
63
+ [contenteditable] {
64
+ outline: 0px solid transparent;
65
+ }
66
+ `}</style>
67
+ </>
68
+ );
69
+ }
70
+
71
+ export type ComponentSelectedEvent = {
72
+ type: "componentSelected";
73
+ componentIds: string[];
74
+ };
@@ -0,0 +1,133 @@
1
+ "use client";
2
+ import { ComponentData } from "@alpaca-headless/alpaca-headless";
3
+
4
+ import React, {
5
+ useState,
6
+ ReactElement,
7
+ ReactNode,
8
+ useEffect,
9
+ Fragment,
10
+ useCallback,
11
+ } from "react";
12
+
13
+ interface MultiComponentEditorProps {
14
+ children: ReactNode;
15
+ component: ComponentData;
16
+ placeholderName: string;
17
+ thumbZoom?: number;
18
+ thumbWidth?: string;
19
+ thumbHeight?: string;
20
+ }
21
+
22
+ export function MultiComponentEditor({
23
+ children,
24
+ component,
25
+ placeholderName,
26
+ thumbZoom,
27
+ thumbWidth = "200px",
28
+ thumbHeight = "112px",
29
+ }: MultiComponentEditorProps) {
30
+ const [selectedId, setSelectedId] = useState<string | null>(null);
31
+ const placeholder = component.placeholders.find(
32
+ (x) => x.name === placeholderName
33
+ );
34
+ if (!placeholder) return;
35
+ const components = placeholder.components;
36
+ if (!components) return;
37
+
38
+ const handleMessage = useCallback(
39
+ (event: MessageEvent) => {
40
+ if (event.data.type === "componentsSelected") {
41
+ setSelectedId(event.data.componentIds[0]);
42
+ }
43
+ },
44
+ [components]
45
+ );
46
+
47
+ useEffect(() => {
48
+ window.addEventListener("message", handleMessage);
49
+
50
+ return () => {
51
+ window.removeEventListener("message", handleMessage);
52
+ };
53
+ }, []);
54
+
55
+ const selectedIndex = components.findIndex(
56
+ (x: ComponentData) => x.id === selectedId
57
+ );
58
+
59
+ const childrenArray = React.Children.toArray(children) as ReactElement[];
60
+
61
+ const filteredChildren = childrenArray.filter(
62
+ (child) => child.type !== "script"
63
+ );
64
+
65
+ return (
66
+ <>
67
+ {filteredChildren[selectedIndex < 0 ? 0 : selectedIndex]}
68
+ <div className="a-editor-mce">
69
+ <script
70
+ data-placeholder-start={placeholder.key}
71
+ data-orientation="horizontal"
72
+ />
73
+ {filteredChildren.map((x, index) => thumbnail(x, index))}
74
+ <script data-placeholder-end={placeholder.key} />
75
+ </div>
76
+ </>
77
+ );
78
+
79
+ function thumbnail(x: React.ReactNode, index: number) {
80
+ const style: {
81
+ height?: string;
82
+ width?: string;
83
+ zoom?: number;
84
+ transform?: string;
85
+ } = {};
86
+
87
+ if (thumbHeight) {
88
+ style.height = thumbHeight;
89
+ }
90
+ if (thumbWidth) {
91
+ style.width = thumbWidth;
92
+ }
93
+
94
+ const componentArray = (x as any).props?.children;
95
+
96
+ const component = components![index];
97
+
98
+ return (
99
+ <Fragment key={index}>
100
+ <div
101
+ className={
102
+ "a-editor-mce-thumbnail" +
103
+ (index === selectedIndex ? " a-editor-mce-thumbnail--selected" : "")
104
+ }
105
+ style={style}
106
+ onClick={() => {
107
+ selectComponents([components![index].id]);
108
+ }}
109
+ >
110
+ <script
111
+ data-component-start={component.id}
112
+ data-itemid={
113
+ component._editor?.linkedComponentItem?.id || component.id
114
+ }
115
+ data-layoutid={component._editor?.hostingPageItem?.id}
116
+ />
117
+ <div style={{ pointerEvents: "none", zoom: thumbZoom || 0.25 }}>
118
+ {componentArray.slice(1, -1)}
119
+ </div>
120
+ <script data-component-end={component.id} />
121
+ </div>
122
+ <div data-dropzone={components[index].id}></div>
123
+ </Fragment>
124
+ );
125
+ }
126
+ }
127
+
128
+ function selectComponents(componentIds: string[]) {
129
+ window.top?.window.postMessage(
130
+ { componentIds, type: "componentsSelected" },
131
+ "*"
132
+ );
133
+ }
@@ -1,2 +1,3 @@
1
1
  "use client";
2
- export { ClientLink } from "./ClientLink";
2
+
3
+ export { MultiComponentEditor } from "./MultiComponentEditor";
@@ -0,0 +1,62 @@
1
+ import {
2
+ ApiConfig,
3
+ RenderOptions,
4
+ resolveRoute,
5
+ } from "@alpaca-headless/alpaca-headless";
6
+ import { NextRequest } from "next/server";
7
+ import { getApiHeaders } from ".";
8
+
9
+ export async function handleBasicAuthRoute({
10
+ request,
11
+ mapHost,
12
+ renderOptions,
13
+ apiConfig,
14
+ }: {
15
+ request: NextRequest;
16
+ mapHost: (host: string) => string;
17
+ renderOptions: RenderOptions;
18
+ apiConfig?: ApiConfig;
19
+ }) {
20
+ const urlSearchParams = new URLSearchParams(request.nextUrl.search);
21
+ const nextSearchParams: any = {};
22
+ for (const [key, value] of urlSearchParams.entries()) {
23
+ nextSearchParams[key] = value;
24
+ }
25
+
26
+ const config = apiConfig || {};
27
+ if (!config.headers) {
28
+ config.headers = getApiHeaders();
29
+ }
30
+
31
+ const routeData = await resolveRoute({
32
+ path: request.nextUrl.pathname,
33
+ searchParams: nextSearchParams,
34
+ host: mapHost(request.headers.get("host") || ""),
35
+ renderOptions,
36
+ renderings: {},
37
+ apiConfig: config,
38
+ });
39
+
40
+ if (routeData.result.type === "redirect") {
41
+ return new Response(null, {
42
+ status: routeData.result.redirectType === "permanent" ? 301 : 302,
43
+ headers: {
44
+ Location: routeData.result.location,
45
+ },
46
+ });
47
+ }
48
+
49
+ if (routeData.result.type === "unauthorized") {
50
+ if (routeData.result.auth)
51
+ return new Response(null, {
52
+ status: 401,
53
+ headers: {
54
+ "WWW-Authenticate": routeData.result.auth.replace(", Bearer", ""),
55
+ },
56
+ });
57
+ else
58
+ return new Response(null, {
59
+ status: 401,
60
+ });
61
+ }
62
+ }
package/src/index.ts CHANGED
@@ -1,5 +1,15 @@
1
- import { init } from "./configure";
1
+ import { headers } from "next/headers";
2
2
 
3
- init();
3
+ export { EditorIntegration } from "./EditorIntegration";
4
4
 
5
- export * from "../../alpaca-headless/src/index";
5
+ export function getApiHeaders() {
6
+ const requestHeaders = headers();
7
+ const apiHeaders = new Headers();
8
+ apiHeaders.set("Cookie", requestHeaders.get("Cookie") || "");
9
+ apiHeaders.set("Authorization", requestHeaders.get("Authorization") || "");
10
+ return apiHeaders;
11
+ }
12
+
13
+ export { handleRequest } from "./middleware/handleRequest";
14
+
15
+ export { proxy } from "./proxy";
@@ -1,14 +1,21 @@
1
- import { RenderOptions, resolveRoute } from "../../../alpaca-headless/src";
1
+ import {
2
+ ApiConfig,
3
+ RenderOptions,
4
+ resolveRoute,
5
+ } from "@alpaca-headless/alpaca-headless";
2
6
  import { NextRequest } from "next/server";
7
+ import { getApiHeaders } from "..";
3
8
 
4
9
  export async function handleRequest({
5
10
  request,
6
11
  mapHost,
7
12
  renderOptions,
13
+ apiConfig,
8
14
  }: {
9
15
  request: NextRequest;
10
16
  mapHost: (host: string) => string;
11
17
  renderOptions: RenderOptions;
18
+ apiConfig?: ApiConfig;
12
19
  }) {
13
20
  const urlSearchParams = new URLSearchParams(request.nextUrl.search);
14
21
  const nextSearchParams: any = {};
@@ -16,29 +23,35 @@ export async function handleRequest({
16
23
  nextSearchParams[key] = value;
17
24
  }
18
25
 
19
- const result = await resolveRoute({
26
+ const config = apiConfig || {};
27
+ if (!config.headers) {
28
+ config.headers = getApiHeaders();
29
+ }
30
+
31
+ const routeData = await resolveRoute({
20
32
  path: request.nextUrl.pathname,
21
33
  searchParams: nextSearchParams,
22
34
  host: mapHost(request.headers.get("host") || ""),
23
35
  renderOptions,
24
36
  renderings: {},
37
+ apiConfig: config,
25
38
  });
26
39
 
27
- if (result.type === "redirect") {
40
+ if (routeData.result.type === "redirect") {
28
41
  return new Response(null, {
29
- status: result.redirectType === "permanent" ? 301 : 302,
42
+ status: routeData.result.redirectType === "permanent" ? 301 : 302,
30
43
  headers: {
31
- Location: result.location,
44
+ Location: routeData.result.location,
32
45
  },
33
46
  });
34
47
  }
35
48
 
36
- if (result.type === "unauthorized") {
37
- if (result.auth)
49
+ if (routeData.result.type === "unauthorized") {
50
+ if (routeData.result.auth)
38
51
  return new Response(null, {
39
52
  status: 401,
40
53
  headers: {
41
- "WWW-Authenticate": result.auth.replace(", Bearer", ""),
54
+ "WWW-Authenticate": routeData.result.auth.replace(", Bearer", ""),
42
55
  },
43
56
  });
44
57
  else
@@ -1,5 +1 @@
1
- import { init } from "../configure";
2
-
3
- init();
4
-
5
1
  export * from "./handleRequest";
@@ -0,0 +1,108 @@
1
+ import axios from "axios";
2
+ // import { HttpsProxyAgent } from "https-proxy-agent";
3
+ import { NextResponse } from "next/server";
4
+
5
+ async function GET(
6
+ req: Request,
7
+ target: string
8
+ //{ proxy }: { proxy?: string }
9
+ ) {
10
+ const reqUrl = new URL(req.url);
11
+
12
+ const url: string =
13
+ target + reqUrl.pathname + "?" + reqUrl.searchParams.toString();
14
+
15
+ const headers: { [key: string]: string } = {
16
+ Authorization: req.headers.get("Authorization") || "",
17
+ Cookie: req.headers.get("Cookie") || "",
18
+ };
19
+
20
+ // const agent = proxy ? new HttpsProxyAgent(proxy) : undefined;
21
+
22
+ const externalResponse = await axios.get(url, {
23
+ headers: headers,
24
+ // httpAgent: agent,
25
+ // httpsAgent: agent,
26
+ responseType: "stream",
27
+ });
28
+
29
+ return new NextResponse(nodeReadableToReadableStream(externalResponse.data), {
30
+ status: externalResponse.status,
31
+ });
32
+ }
33
+
34
+ async function POST(
35
+ req: Request
36
+ //{ proxy }: { proxy?: string }
37
+ ) {
38
+ const reqUrl = new URL(req.url);
39
+ const body = await req.text();
40
+
41
+ const url: string =
42
+ process.env.EDITOR_SERVICE_URL +
43
+ reqUrl.pathname +
44
+ "?" +
45
+ reqUrl.searchParams.toString();
46
+
47
+ const headers: { [key: string]: string } = {
48
+ "Content-Type": req.headers.get("Content-Type") || "",
49
+ Authorization: req.headers.get("Authorization") || "",
50
+ Cookie: req.headers.get("Cookie") || "",
51
+ };
52
+
53
+ // const agent = proxy ? new HttpsProxyAgent(proxy) : undefined;
54
+
55
+ const externalResponse = await axios.post(url, body, {
56
+ headers: headers,
57
+ // httpAgent: agent,
58
+ // httpsAgent: agent,
59
+ responseType: "stream",
60
+ });
61
+
62
+ const responseHeaders = getResponseHeaders(externalResponse);
63
+
64
+ return new NextResponse(nodeReadableToReadableStream(externalResponse.data), {
65
+ status: externalResponse.status,
66
+ headers: responseHeaders,
67
+ });
68
+ }
69
+
70
+ const getResponseHeaders = (externalResponse: any) => {
71
+ const responseHeaders = new Headers();
72
+ responseHeaders.set(
73
+ "Content-Type",
74
+ externalResponse.headers["content-type"] || ""
75
+ );
76
+ responseHeaders.set(
77
+ "Set-Cookie",
78
+ externalResponse.headers["set-cookie"] || ""
79
+ );
80
+ return responseHeaders;
81
+ };
82
+
83
+ function nodeReadableToReadableStream(
84
+ nodeStream: NodeJS.ReadableStream
85
+ ): ReadableStream<Uint8Array> {
86
+ return new ReadableStream<Uint8Array>({
87
+ start(controller) {
88
+ nodeStream.on("data", (chunk: Buffer) => {
89
+ controller.enqueue(new Uint8Array(chunk));
90
+ });
91
+
92
+ nodeStream.on("end", () => {
93
+ controller.close();
94
+ });
95
+
96
+ nodeStream.on("error", (err: Error) => {
97
+ controller.error(err);
98
+ });
99
+ },
100
+ pull() {},
101
+ cancel() {},
102
+ });
103
+ }
104
+
105
+ export const proxy = {
106
+ POST,
107
+ GET,
108
+ };
@@ -0,0 +1,45 @@
1
+ import { useRouter, useSearchParams } from "next/navigation";
2
+ import { useEffect, useState } from "react";
3
+ import uuid from "react-uuid";
4
+
5
+ declare global {
6
+ interface Window {
7
+ requestRefresh?: (newUri?: string) => boolean;
8
+ }
9
+ }
10
+
11
+ const useExposeRefreshFunction = () => {
12
+ const router = useRouter();
13
+ const searchParams = useSearchParams();
14
+ const [refreshStart, setRefreshStart] = useState<number>();
15
+
16
+ useEffect(() => {
17
+ // Expose the refresh function to the parent window
18
+ window.requestRefresh = (newUri?: string) => {
19
+ console.log("refresh requested", newUri);
20
+ if (!newUri) {
21
+ const uri = new URL(window.location.href);
22
+ uri.searchParams.set("edit_rev", uuid().toString());
23
+ newUri = uri.toString();
24
+ }
25
+
26
+ router.replace(newUri, { scroll: false });
27
+ setRefreshStart(performance.now());
28
+ return true; // Indicate the function executed successfully
29
+ };
30
+
31
+ // Optionally clean up when the component unmounts
32
+ return () => {
33
+ delete window.requestRefresh;
34
+ };
35
+ }, [router]);
36
+
37
+ useEffect(() => {
38
+ if (refreshStart)
39
+ console.log("Refresh complete", performance.now() - refreshStart!);
40
+ }, [searchParams]);
41
+
42
+ return null; // This hook doesn't render anything
43
+ };
44
+
45
+ export default useExposeRefreshFunction;
package/tsconfig.json CHANGED
@@ -22,6 +22,5 @@
22
22
  "noUnusedParameters": true
23
23
  },
24
24
  "include": ["src/**/*"],
25
- "exclude": ["node_modules", "**/*.spec.ts"],
26
- "references": [{ "path": "../alpaca-headless" }]
25
+ "exclude": ["node_modules", "**/*.spec.ts"]
27
26
  }
@@ -1,6 +0,0 @@
1
- import React from "react";
2
- import { LinkField } from "../../../alpaca-headless/src/types/fieldTypes";
3
- export declare function ClientLink({ field, children, ...props }: {
4
- field: LinkField;
5
- children: React.ReactNode;
6
- } & React.AnchorHTMLAttributes<HTMLAnchorElement>): import("react/jsx-runtime").JSX.Element | undefined;
@@ -1,39 +0,0 @@
1
- "use client";
2
- var __rest = (this && this.__rest) || function (s, e) {
3
- var t = {};
4
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
- t[p] = s[p];
6
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
- t[p[i]] = s[p[i]];
10
- }
11
- return t;
12
- };
13
- import { jsx as _jsx } from "react/jsx-runtime";
14
- export function ClientLink(_a) {
15
- var { field, children } = _a, props = __rest(_a, ["field", "children"]);
16
- if (!field)
17
- return;
18
- if (field.jsonValue) {
19
- field = field.jsonValue;
20
- }
21
- if (!field.value)
22
- return;
23
- //const previewContext = usePreviewContext();
24
- // if (previewContext) {
25
- // return (
26
- // <LinkPreview field={field} {...props}>
27
- // {children}
28
- // </LinkPreview>
29
- // );
30
- // }
31
- // const editing = useEditContext();
32
- // if (editing)
33
- // return (
34
- // <LinkEditorWrapper field={field} {...props}>
35
- // {children}
36
- // </LinkEditorWrapper>
37
- // );
38
- return (_jsx("a", Object.assign({ href: field.value.url }, props, { children: children })));
39
- }
@@ -1 +0,0 @@
1
- export declare function init(): void;
package/dist/configure.js DELETED
@@ -1,10 +0,0 @@
1
- import { cookies, headers } from "next/headers";
2
- import { alpacaHeadless } from "../../alpaca-headless/src/index";
3
- export function init() {
4
- if (!alpacaHeadless.isInitialized) {
5
- alpacaHeadless.configuration.dependencies.fetch = fetch;
6
- alpacaHeadless.configuration.dependencies.cookies = () => cookies().toString();
7
- alpacaHeadless.configuration.dependencies.headers = headers;
8
- alpacaHeadless.isInitialized = true;
9
- }
10
- }
@@ -1,46 +0,0 @@
1
- "use client";
2
-
3
- import React from "react";
4
- import { LinkField } from "../../../alpaca-headless/src/types/fieldTypes";
5
-
6
- export function ClientLink({
7
- field,
8
- children,
9
- ...props
10
- }: {
11
- field: LinkField;
12
- children: React.ReactNode;
13
- } & React.AnchorHTMLAttributes<HTMLAnchorElement>) {
14
- if (!field) return;
15
-
16
- if (field.jsonValue) {
17
- field = field.jsonValue as LinkField;
18
- }
19
-
20
- if (!field.value) return;
21
-
22
- //const previewContext = usePreviewContext();
23
-
24
- // if (previewContext) {
25
- // return (
26
- // <LinkPreview field={field} {...props}>
27
- // {children}
28
- // </LinkPreview>
29
- // );
30
- // }
31
-
32
- // const editing = useEditContext();
33
-
34
- // if (editing)
35
- // return (
36
- // <LinkEditorWrapper field={field} {...props}>
37
- // {children}
38
- // </LinkEditorWrapper>
39
- // );
40
-
41
- return (
42
- <a href={field.value.url} {...props}>
43
- {children}
44
- </a>
45
- );
46
- }
package/src/configure.ts DELETED
@@ -1,12 +0,0 @@
1
- import { cookies, headers } from "next/headers";
2
- import { alpacaHeadless } from "../../alpaca-headless/src/index";
3
-
4
- export function init() {
5
- if (!alpacaHeadless.isInitialized) {
6
- alpacaHeadless.configuration.dependencies.fetch = fetch;
7
- alpacaHeadless.configuration.dependencies.cookies = () =>
8
- cookies().toString();
9
- alpacaHeadless.configuration.dependencies.headers = headers;
10
- alpacaHeadless.isInitialized = true;
11
- }
12
- }