astro-tractstack 2.0.5 → 2.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { fileURLToPath as d } from "node:url";
2
2
  import { dirname as i, resolve as l } from "node:path";
3
- import { existsSync as r, mkdirSync as x, copyFileSync as k, writeFileSync as u } from "node:fs";
3
+ import { existsSync as n, mkdirSync as x, copyFileSync as k, writeFileSync as u } from "node:fs";
4
4
  import { resolve as a } from "path";
5
5
  function b(t) {
6
6
  const e = i(d(t));
@@ -10,7 +10,7 @@ function b(t) {
10
10
  }
11
11
  function g(t, e) {
12
12
  e.info("TractStack configuration applied"), t.enableMultiTenant && e.info("Multi-tenant mode enabled"), t.includeExamples && e.info("Example components will be included");
13
- const c = process.env.PUBLIC_GO_BACKEND, o = process.env.PUBLIC_TENANTID;
13
+ const c = process.env.PUBLIC_GO_BACKEND, r = process.env.PUBLIC_TENANTID;
14
14
  if (!c)
15
15
  e.warn("PUBLIC_GO_BACKEND not set - this will be required at runtime");
16
16
  else
@@ -19,11 +19,11 @@ function g(t, e) {
19
19
  } catch {
20
20
  e.error(`PUBLIC_GO_BACKEND is not a valid URL: ${c}`);
21
21
  }
22
- return o ? /^[a-zA-Z0-9_-]+$/.test(o) ? e.info(`Tenant ID validated: ${o}`) : e.error(`PUBLIC_TENANTID contains invalid characters: ${o}`) : e.warn("PUBLIC_TENANTID not set - this will be required at runtime"), t;
22
+ return r ? /^[a-zA-Z0-9_-]+$/.test(r) ? e.info(`Tenant ID validated: ${r}`) : e.error(`PUBLIC_TENANTID contains invalid characters: ${r}`) : e.warn("PUBLIC_TENANTID not set - this will be required at runtime"), t;
23
23
  }
24
24
  async function w(t, e, c) {
25
25
  e.info("TractStack: Injecting template files");
26
- const o = [
26
+ const r = [
27
27
  // Core Configuration
28
28
  {
29
29
  src: t("../templates/env.example"),
@@ -564,6 +564,10 @@ async function w(t, e, c) {
564
564
  src: t("../templates/src/stores/backend.ts"),
565
565
  dest: "src/stores/backend.ts"
566
566
  },
567
+ {
568
+ src: t("../templates/src/stores/resources.ts"),
569
+ dest: "src/stores/resources.ts"
570
+ },
567
571
  // Compositor stores
568
572
  {
569
573
  src: t("../templates/src/stores/nodes.ts"),
@@ -1298,6 +1302,10 @@ async function w(t, e, c) {
1298
1302
  src: t("../templates/src/lib/session.ts"),
1299
1303
  dest: "src/lib/session.ts"
1300
1304
  },
1305
+ {
1306
+ src: t("../templates/src/lib/resources.ts"),
1307
+ dest: "src/lib/resources.ts"
1308
+ },
1301
1309
  // Client Scripts
1302
1310
  {
1303
1311
  src: t("../templates/src/client/htmx.min.js"),
@@ -2056,6 +2064,13 @@ async function w(t, e, c) {
2056
2064
  dest: "src/custom/CustomRoutes.astro",
2057
2065
  protected: !0
2058
2066
  },
2067
+ {
2068
+ src: t(
2069
+ c?.includeExamples ? "../templates/custom/with-examples/HeaderWidget.astro" : "../templates/custom/minimal/HeaderWidget.astro"
2070
+ ),
2071
+ dest: "src/custom/HeaderWidget.astro",
2072
+ protected: !0
2073
+ },
2059
2074
  {
2060
2075
  src: t("../templates/src/utils/customHelpers.ts"),
2061
2076
  dest: "src/utils/customHelpers.ts",
@@ -2099,13 +2114,13 @@ async function w(t, e, c) {
2099
2114
  }
2100
2115
  ] : []
2101
2116
  ];
2102
- for (const s of o)
2117
+ for (const s of r)
2103
2118
  try {
2104
2119
  const p = i(s.dest);
2105
- r(p) || x(p, { recursive: !0 });
2106
- const n = !s.protected && (s.dest === "tailwind.config.cjs" || s.dest.startsWith("src/components/codehooks/") || s.dest.startsWith("src/components/widgets/") || s.dest.startsWith("src/") || s.dest.startsWith("public/client/") || s.dest === ".gitignore");
2107
- if (!r(s.dest) || n)
2108
- if (r(s.src))
2120
+ n(p) || x(p, { recursive: !0 });
2121
+ const o = !s.protected && (s.dest === "tailwind.config.cjs" || s.dest.startsWith("src/components/codehooks/") || s.dest.startsWith("src/components/widgets/") || s.dest.startsWith("src/") || s.dest.startsWith("public/client/") || s.dest === ".gitignore");
2122
+ if (!n(s.dest) || o)
2123
+ if (n(s.src))
2109
2124
  k(s.src, s.dest), e.info(`Updated ${s.dest}`);
2110
2125
  else {
2111
2126
  const m = _(s.dest);
@@ -2113,8 +2128,8 @@ async function w(t, e, c) {
2113
2128
  }
2114
2129
  else s.protected ? e.info(`Protected: ${s.dest} (skipped overwrite)`) : e.info(`Skipped existing ${s.dest}`);
2115
2130
  } catch (p) {
2116
- const n = p instanceof Error ? p.message : String(p);
2117
- e.error(`Failed to create ${s.dest}: ${n}`);
2131
+ const o = p instanceof Error ? p.message : String(p);
2132
+ e.error(`Failed to create ${s.dest}: ${o}`);
2118
2133
  }
2119
2134
  }
2120
2135
  function _(t) {
@@ -2133,7 +2148,7 @@ function C(t = {}) {
2133
2148
  return {
2134
2149
  name: "astro-tractstack",
2135
2150
  hooks: {
2136
- "astro:config:setup": async ({ config: c, updateConfig: o, logger: s }) => {
2151
+ "astro:config:setup": async ({ config: c, updateConfig: r, logger: s }) => {
2137
2152
  g(t, s);
2138
2153
  const p = t.enableMultiTenant || !1;
2139
2154
  if (s.info(
@@ -2153,7 +2168,7 @@ function C(t = {}) {
2153
2168
  ), new Error(
2154
2169
  "TractStack requires an SSR adapter. Please add @astrojs/node adapter to your astro.config.mjs"
2155
2170
  );
2156
- o({
2171
+ r({
2157
2172
  vite: {
2158
2173
  define: {
2159
2174
  __TRACTSTACK_VERSION__: JSON.stringify("2.0.0-alpha.1"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astro-tractstack",
3
- "version": "2.0.5",
3
+ "version": "2.0.7",
4
4
  "description": "Astro integration for TractStack - redeeming the web from boring experiences",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -0,0 +1,35 @@
1
+ ---
2
+ /*
3
+ // ========================================================================================
4
+ // CUSTOM HEADER WIDGET
5
+ // ========================================================================================
6
+ // This widget is rendered on every page above the main header. It is designed to
7
+ // fetch and display site-wide content, such as promotional banners or alerts.
8
+ //
9
+ // To activate this component:
10
+ // 1. Uncomment all the code within these '---' fences.
11
+ // 2. Define your desired resource categories in the `resourceCategories` array.
12
+ // 3. Add your Astro/HTML markup in the empty space after the closing '---' below.
13
+ // ========================================================================================
14
+
15
+ // --- UNCOMMENT BELOW TO ACTIVATE ---
16
+
17
+ // import { getHeaderResources } from '@/lib/resources';
18
+ // import type { ResourceNode } from '@/types/compositorTypes';
19
+
20
+ // export interface Props {
21
+ // tenantId: string;
22
+ // }
23
+ // const { tenantId } = Astro.props;
24
+
25
+ // // Add the slugs of the resource categories you want to fetch here.
26
+ // const resourceCategories = []; // e.g., ['promotions', 'site-alerts']
27
+
28
+ // // This function automatically fetches and caches the resources.
29
+ // const resources: ResourceNode[] =
30
+ // resourceCategories.length > 0
31
+ // ? await getHeaderResources(tenantId, resourceCategories)
32
+ // : [];
33
+
34
+ */
35
+ ---
@@ -0,0 +1,35 @@
1
+ ---
2
+ /*
3
+ // ========================================================================================
4
+ // CUSTOM HEADER WIDGET
5
+ // ========================================================================================
6
+ // This widget is rendered on every page above the main header. It is designed to
7
+ // fetch and display site-wide content, such as promotional banners or alerts.
8
+ //
9
+ // To activate this component:
10
+ // 1. Uncomment all the code within these '---' fences.
11
+ // 2. Define your desired resource categories in the `resourceCategories` array.
12
+ // 3. Add your Astro/HTML markup in the empty space after the closing '---' below.
13
+ // ========================================================================================
14
+
15
+ // --- UNCOMMENT BELOW TO ACTIVATE ---
16
+
17
+ // import { getHeaderResources } from '@/lib/resources';
18
+ // import type { ResourceNode } from '@/types/compositorTypes';
19
+
20
+ // export interface Props {
21
+ // tenantId: string;
22
+ // }
23
+ // const { tenantId } = Astro.props;
24
+
25
+ // // Add the slugs of the resource categories you want to fetch here.
26
+ // const resourceCategories = []; // e.g., ['promotions', 'site-alerts']
27
+
28
+ // // This function automatically fetches and caches the resources.
29
+ // const resources: ResourceNode[] =
30
+ // resourceCategories.length > 0
31
+ // ? await getHeaderResources(tenantId, resourceCategories)
32
+ // : [];
33
+
34
+ */
35
+ ---
@@ -67,8 +67,20 @@ const StyleLinkConfigPanel = ({ node, config }: StyleLinkConfigPanelProps) => {
67
67
  linkNode.tagName = 'button';
68
68
  } else if (callbackPayload.startsWith('(bunnyMoment')) {
69
69
  linkNode.tagName = 'button';
70
- newButtonPayload.bunnyPayload =
71
- (tokens && preParseBunny([tokens])) ?? undefined;
70
+ if (
71
+ tokens &&
72
+ Array.isArray(tokens) &&
73
+ tokens[0] === 'bunnyMoment' &&
74
+ Array.isArray(tokens[1])
75
+ ) {
76
+ const params = tokens[1];
77
+ if (params.length === 2) {
78
+ newButtonPayload.bunnyPayload = {
79
+ videoId: String(params[0]),
80
+ t: String(params[1]),
81
+ };
82
+ }
83
+ }
72
84
  } else if (callbackPayload.startsWith('(goto')) {
73
85
  const targetUrl =
74
86
  tokens && preParseAction([tokens], slug, isContext, config);
@@ -87,10 +87,11 @@ export default function ActionBuilderField({
87
87
  return;
88
88
  }
89
89
 
90
- if (command === 'identifyAs') {
90
+ if (command === 'bunnyMoment') {
91
+ onChange(trimmedParams);
92
+ } else if (command === 'identifyAs') {
91
93
  const firstSpaceIndex = trimmedParams.indexOf(' ');
92
94
  if (firstSpaceIndex === -1) {
93
- // Handle case with only beliefId and no value
94
95
  onChange(`(${command} ${trimmedParams})`);
95
96
  } else {
96
97
  const beliefId = trimmedParams.substring(0, firstSpaceIndex);
@@ -99,7 +100,6 @@ export default function ActionBuilderField({
99
100
  onChange(`(${command} ${beliefId} ${finalValue})`);
100
101
  }
101
102
  } else {
102
- // Original behavior for all other commands
103
103
  onChange(`(${command} ${trimmedParams})`);
104
104
  }
105
105
  };
@@ -1,5 +1,6 @@
1
1
  ---
2
2
  import { ClientRouter } from 'astro:transitions';
3
+ import HeaderWidget from '@/custom/HeaderWidget.astro';
3
4
  import Header from '@/components/Header.astro';
4
5
  import Footer from '@/components/Footer.astro';
5
6
  import { getBrandConfig } from '@/utils/api/brandConfig';
@@ -238,6 +239,7 @@ const enableBunny = import.meta.env.PUBLIC_ENABLE_BUNNY === 'true';
238
239
  </head>
239
240
  <body class="font-main w-full">
240
241
  <div class="overflow-hidden">
242
+ {!isStoryKeep && !isEditor && <HeaderWidget tenantId={tenantId} />}
241
243
  {
242
244
  !isEditor && (
243
245
  <Header
@@ -0,0 +1,69 @@
1
+ import { headerResourcesStore, HEADER_RESOURCES_TTL } from '@/stores/resources';
2
+ import type { ResourceNode } from '@/types/compositorTypes';
3
+
4
+ /**
5
+ * Fetches resource nodes based on categories, with server-side in-memory caching
6
+ * to prevent redundant API calls for high-traffic, site-wide components.
7
+ *
8
+ * @param tenantId The ID of the current tenant.
9
+ * @param categories An array of resource category slugs to fetch.
10
+ * @param ttl Optional. The Time-To-Live for the cache in milliseconds. Defaults to 5 minutes.
11
+ * @returns A promise that resolves to an array of ResourceNode objects.
12
+ */
13
+ export async function getHeaderResources(
14
+ tenantId: string,
15
+ categories: string[],
16
+ ttl: number = HEADER_RESOURCES_TTL
17
+ ): Promise<ResourceNode[]> {
18
+ const cache = headerResourcesStore.get();
19
+ const now = Date.now();
20
+
21
+ // If we have fresh data in the cache, return it immediately.
22
+ if (cache.data.length > 0 && now - cache.lastFetched < ttl) {
23
+ return cache.data;
24
+ }
25
+
26
+ // If no categories are requested, there's nothing to fetch.
27
+ if (!categories || categories.length === 0) {
28
+ return [];
29
+ }
30
+
31
+ const goBackend =
32
+ import.meta.env.PUBLIC_GO_BACKEND || 'http://localhost:8080';
33
+
34
+ try {
35
+ // THIS IS THE CORRECTED ENDPOINT
36
+ const response = await fetch(`${goBackend}/api/v1/nodes/resources`, {
37
+ method: 'POST',
38
+ headers: {
39
+ 'Content-Type': 'application/json',
40
+ 'X-Tenant-ID': tenantId,
41
+ },
42
+ body: JSON.stringify({ categories }),
43
+ });
44
+
45
+ if (!response.ok) {
46
+ console.error(
47
+ `Failed to fetch header resources. Status: ${response.status}`
48
+ );
49
+ // Gracefully degrade: return old data if we have it, otherwise an empty array.
50
+ return cache.data;
51
+ }
52
+
53
+ // The backend returns a payload like { resources: [...] }
54
+ const responsePayload = await response.json();
55
+ const resources: ResourceNode[] = responsePayload.resources || [];
56
+
57
+ // Update the store with the new data and timestamp.
58
+ headerResourcesStore.set({
59
+ data: resources,
60
+ lastFetched: now,
61
+ });
62
+
63
+ return resources;
64
+ } catch (error) {
65
+ console.error('Error fetching header resources:', error);
66
+ // On network error, also return stale data if available.
67
+ return cache.data;
68
+ }
69
+ }
@@ -0,0 +1,17 @@
1
+ import { atom } from 'nanostores';
2
+ import type { ResourceNode } from '@/types/compositorTypes';
3
+
4
+ export interface ResourcesCache {
5
+ data: ResourceNode[];
6
+ lastFetched: number;
7
+ }
8
+
9
+ // Initialize with an empty state. This atom will live on the server and persist
10
+ // across page requests for the lifetime of the server instance.
11
+ export const headerResourcesStore = atom<ResourcesCache>({
12
+ data: [],
13
+ lastFetched: 0,
14
+ });
15
+
16
+ // Default Time-To-Live for the cache: 5 minutes in milliseconds.
17
+ export const HEADER_RESOURCES_TTL = 5 * 60 * 1000;
@@ -566,6 +566,10 @@ export async function injectTemplateFiles(
566
566
  src: resolve('../templates/src/stores/backend.ts'),
567
567
  dest: 'src/stores/backend.ts',
568
568
  },
569
+ {
570
+ src: resolve('../templates/src/stores/resources.ts'),
571
+ dest: 'src/stores/resources.ts',
572
+ },
569
573
 
570
574
  // Compositor stores
571
575
  {
@@ -1322,6 +1326,10 @@ export async function injectTemplateFiles(
1322
1326
  src: resolve('../templates/src/lib/session.ts'),
1323
1327
  dest: 'src/lib/session.ts',
1324
1328
  },
1329
+ {
1330
+ src: resolve('../templates/src/lib/resources.ts'),
1331
+ dest: 'src/lib/resources.ts',
1332
+ },
1325
1333
 
1326
1334
  // Client Scripts
1327
1335
  {
@@ -2098,6 +2106,15 @@ export async function injectTemplateFiles(
2098
2106
  dest: 'src/custom/CustomRoutes.astro',
2099
2107
  protected: true,
2100
2108
  },
2109
+ {
2110
+ src: resolve(
2111
+ config?.includeExamples
2112
+ ? '../templates/custom/with-examples/HeaderWidget.astro'
2113
+ : '../templates/custom/minimal/HeaderWidget.astro'
2114
+ ),
2115
+ dest: 'src/custom/HeaderWidget.astro',
2116
+ protected: true,
2117
+ },
2101
2118
  {
2102
2119
  src: resolve('../templates/src/utils/customHelpers.ts'),
2103
2120
  dest: 'src/utils/customHelpers.ts',