@canonical/summon-application 0.29.0 → 0.30.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.
Files changed (126) hide show
  1. package/README.md +75 -13
  2. package/dist/esm/application/react/index.js +347 -0
  3. package/dist/esm/application/react/index.js.map +1 -0
  4. package/dist/esm/application/react/templates/.browserslistrc +2 -0
  5. package/dist/esm/application/react/templates/.storybook/main.ts.ejs +10 -0
  6. package/{src → dist/esm}/application/react/templates/README.md.ejs +54 -0
  7. package/dist/esm/application/react/templates/biome.json.ejs +6 -0
  8. package/dist/esm/application/react/templates/gitignore +25 -0
  9. package/{src → dist/esm}/application/react/templates/package.json.ejs +36 -2
  10. package/dist/esm/application/react/templates/patches/react-relay@18.2.0.patch +52 -0
  11. package/dist/esm/application/react/templates/patches/relay-runtime-network@0.1.0.patch +46 -0
  12. package/dist/esm/application/react/templates/relay.config.json +8 -0
  13. package/{src/application/react/templates/src/client/entry.tsx → dist/esm/application/react/templates/src/client/entry.tsx.ejs} +23 -0
  14. package/dist/esm/application/react/templates/src/domains/catalog/CatalogPage.tsx +50 -0
  15. package/dist/esm/application/react/templates/src/domains/catalog/ErrorBoundary.tests.tsx +56 -0
  16. package/dist/esm/application/react/templates/src/domains/catalog/ErrorBoundary.tsx +37 -0
  17. package/dist/esm/application/react/templates/src/domains/catalog/ProductCard.tsx +49 -0
  18. package/dist/esm/application/react/templates/src/domains/catalog/ProductList.stories.tsx +103 -0
  19. package/dist/esm/application/react/templates/src/domains/catalog/ProductList.tests.tsx +80 -0
  20. package/dist/esm/application/react/templates/src/domains/catalog/ProductList.tsx +59 -0
  21. package/dist/esm/application/react/templates/src/domains/catalog/routes.ts +11 -0
  22. package/dist/esm/application/react/templates/src/lib/ClientOnly/ClientOnly.tests.tsx +35 -0
  23. package/dist/esm/application/react/templates/src/lib/ClientOnly/ClientOnly.tsx +31 -0
  24. package/dist/esm/application/react/templates/src/lib/ClientOnly/index.ts +1 -0
  25. package/{src → dist/esm}/application/react/templates/src/lib/Navigation/Navigation.tsx.ejs +3 -0
  26. package/{src/application/react/templates/src/lib/index.ts → dist/esm/application/react/templates/src/lib/index.ts.ejs} +3 -0
  27. package/dist/esm/application/react/templates/src/relay/__generated__/ProductCard_product.graphql.ts +82 -0
  28. package/dist/esm/application/react/templates/src/relay/__generated__/ProductListQuery.graphql.ts +272 -0
  29. package/dist/esm/application/react/templates/src/relay/environment.tests.ts +87 -0
  30. package/dist/esm/application/react/templates/src/relay/environment.ts +119 -0
  31. package/dist/esm/application/react/templates/src/relay/schema.graphql +111 -0
  32. package/dist/esm/application/react/templates/src/relay/schema.tests.ts +137 -0
  33. package/dist/esm/application/react/templates/src/relay/schema.ts +205 -0
  34. package/{src → dist/esm}/application/react/templates/src/routes.tsx.ejs +10 -0
  35. package/{src/application/react/templates/src/server/entry.tsx → dist/esm/application/react/templates/src/server/entry.tsx.ejs} +36 -0
  36. package/{src → dist/esm}/application/react/templates/src/sitemap/getSitemapItems.ts.ejs +3 -0
  37. package/{src/application/react/templates/tsconfig.json → dist/esm/application/react/templates/tsconfig.json.ejs} +3 -0
  38. package/dist/esm/application/react/templates/vite.config.ts.ejs +92 -0
  39. package/dist/esm/application/react/templates/vitest.setup.ts.ejs +22 -0
  40. package/dist/esm/domain/index.js +89 -0
  41. package/dist/esm/domain/index.js.map +1 -0
  42. package/{src/index.ts → dist/esm/index.js} +6 -8
  43. package/dist/esm/index.js.map +1 -0
  44. package/dist/esm/route/index.js +115 -0
  45. package/dist/esm/route/index.js.map +1 -0
  46. package/dist/esm/route/insertRoute.js +178 -0
  47. package/dist/esm/route/insertRoute.js.map +1 -0
  48. package/dist/esm/shared/casing.js +15 -0
  49. package/dist/esm/shared/casing.js.map +1 -0
  50. package/dist/esm/shared/packageManager.js +38 -0
  51. package/dist/esm/shared/packageManager.js.map +1 -0
  52. package/dist/esm/shared/versions.js +88 -0
  53. package/dist/esm/shared/versions.js.map +1 -0
  54. package/dist/esm/wrapper/index.js +72 -0
  55. package/dist/esm/wrapper/index.js.map +1 -0
  56. package/dist/types/application/react/index.d.ts +12 -0
  57. package/dist/types/application/react/index.d.ts.map +1 -0
  58. package/dist/types/domain/index.d.ts +7 -0
  59. package/dist/types/domain/index.d.ts.map +1 -0
  60. package/dist/types/index.d.ts +8 -0
  61. package/dist/types/index.d.ts.map +1 -0
  62. package/dist/types/route/index.d.ts +7 -0
  63. package/dist/types/route/index.d.ts.map +1 -0
  64. package/dist/types/route/insertRoute.d.ts +34 -0
  65. package/dist/types/route/insertRoute.d.ts.map +1 -0
  66. package/{src/shared/casing.ts → dist/types/shared/casing.d.ts} +2 -7
  67. package/dist/types/shared/casing.d.ts.map +1 -0
  68. package/dist/types/shared/packageManager.d.ts +19 -0
  69. package/dist/types/shared/packageManager.d.ts.map +1 -0
  70. package/dist/types/shared/versions.d.ts +15 -0
  71. package/dist/types/shared/versions.d.ts.map +1 -0
  72. package/dist/types/wrapper/index.d.ts +7 -0
  73. package/dist/types/wrapper/index.d.ts.map +1 -0
  74. package/package.json +16 -15
  75. package/src/application/react/index.ts +0 -294
  76. package/src/application/react/templates/.storybook/main.ts +0 -5
  77. package/src/application/react/templates/biome.json.ejs +0 -6
  78. package/src/application/react/templates/vite.config.ts +0 -45
  79. package/src/application/react/templates/vitest.setup.ts +0 -9
  80. package/src/domain/index.ts +0 -119
  81. package/src/index.test.ts +0 -398
  82. package/src/route/index.ts +0 -154
  83. package/src/route/insertRoute.test.ts +0 -98
  84. package/src/route/insertRoute.ts +0 -236
  85. package/src/shared/versions.ts +0 -48
  86. package/src/wrapper/index.ts +0 -100
  87. /package/{src → dist/esm}/application/react/templates/.storybook/decorators/index.ts +0 -0
  88. /package/{src → dist/esm}/application/react/templates/.storybook/decorators/withRouter.tsx +0 -0
  89. /package/{src → dist/esm}/application/react/templates/.storybook/preview.ts +0 -0
  90. /package/{src → dist/esm}/application/react/templates/index.html.ejs +0 -0
  91. /package/{src → dist/esm}/application/react/templates/public/.gitkeep +0 -0
  92. /package/{src → dist/esm}/application/react/templates/public/robots.txt +0 -0
  93. /package/{src → dist/esm}/application/react/templates/src/assets/.gitkeep +0 -0
  94. /package/{src → dist/esm}/application/react/templates/src/domains/account/AccountPage.tsx +0 -0
  95. /package/{src → dist/esm}/application/react/templates/src/domains/account/LoginPage.tsx +0 -0
  96. /package/{src → dist/esm}/application/react/templates/src/domains/account/routes.ts +0 -0
  97. /package/{src → dist/esm}/application/react/templates/src/domains/contact/ContactPage.tsx +0 -0
  98. /package/{src → dist/esm}/application/react/templates/src/domains/contact/routes.ts +0 -0
  99. /package/{src → dist/esm}/application/react/templates/src/domains/marketing/GuidePage.tsx +0 -0
  100. /package/{src → dist/esm}/application/react/templates/src/domains/marketing/HomePage.tsx +0 -0
  101. /package/{src → dist/esm}/application/react/templates/src/domains/marketing/routes.ts +0 -0
  102. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/ExampleComponent.stories.tsx +0 -0
  103. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/ExampleComponent.tests.tsx +0 -0
  104. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/ExampleComponent.tsx +0 -0
  105. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/index.ts +0 -0
  106. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/styles.css +0 -0
  107. /package/{src → dist/esm}/application/react/templates/src/lib/ExampleComponent/types.ts +0 -0
  108. /package/{src → dist/esm}/application/react/templates/src/lib/LazyComponent/LazyComponent.stories.tsx +0 -0
  109. /package/{src → dist/esm}/application/react/templates/src/lib/LazyComponent/LazyComponent.tsx +0 -0
  110. /package/{src → dist/esm}/application/react/templates/src/lib/LazyComponent/index.ts +0 -0
  111. /package/{src → dist/esm}/application/react/templates/src/lib/Navigation/index.ts +0 -0
  112. /package/{src → dist/esm}/application/react/templates/src/lib/ThemeSelector/ThemeSelector.tsx +0 -0
  113. /package/{src → dist/esm}/application/react/templates/src/lib/ThemeSelector/index.ts +0 -0
  114. /package/{src → dist/esm}/application/react/templates/src/server/preview.bun.ts +0 -0
  115. /package/{src → dist/esm}/application/react/templates/src/server/preview.express.ts +0 -0
  116. /package/{src → dist/esm}/application/react/templates/src/server/renderer.tsx +0 -0
  117. /package/{src → dist/esm}/application/react/templates/src/server/server.bun.ts +0 -0
  118. /package/{src → dist/esm}/application/react/templates/src/server/server.express.ts +0 -0
  119. /package/{src → dist/esm}/application/react/templates/src/sitemap/renderer.ts +0 -0
  120. /package/{src → dist/esm}/application/react/templates/src/styles/app.css +0 -0
  121. /package/{src → dist/esm}/application/react/templates/src/styles/index.css.ejs +0 -0
  122. /package/{src → dist/esm}/application/react/templates/src/vite-env.d.ts +0 -0
  123. /package/{src → dist/esm}/application/react/templates/test/e2e/serverHarness.ts +0 -0
  124. /package/{src → dist/esm}/application/react/templates/test/e2e/servers.e2e.ts +0 -0
  125. /package/{src → dist/esm}/application/react/templates/vitest.config.ts +0 -0
  126. /package/{src → dist/esm}/application/react/templates/vitest.e2e.config.ts +0 -0
@@ -0,0 +1,111 @@
1
+ # Mock GraphQL schema for the Relay data-layer example.
2
+ #
3
+ # A compact catalog domain, shaped the Relay way: an object identification
4
+ # `Node` interface with globally unique IDs, a `viewer` root field as the
5
+ # entry point, and one paginated connection (`Viewer.products`) following the
6
+ # Relay Cursor Connections specification. `relay-compiler` validates queries
7
+ # against this file (see relay.config.json); `schema.ts` makes it executable
8
+ # against an in-memory dataset so the app runs without a GraphQL backend.
9
+
10
+ """
11
+ An object with a globally unique ID, per the Relay object identification spec.
12
+ """
13
+ interface Node {
14
+ """
15
+ The globally unique ID of the object.
16
+ """
17
+ id: ID!
18
+ }
19
+
20
+ """
21
+ The authenticated entry point into the graph.
22
+ """
23
+ type Viewer {
24
+ """
25
+ Display name of the current user.
26
+ """
27
+ name: String!
28
+
29
+ """
30
+ Products in the catalog, paginated forwards through a connection.
31
+ """
32
+ products(first: Int, after: String): ProductConnection!
33
+ }
34
+
35
+ """
36
+ A product in the catalog.
37
+ """
38
+ type Product implements Node {
39
+ id: ID!
40
+
41
+ """
42
+ Human-readable product name.
43
+ """
44
+ name: String!
45
+
46
+ """
47
+ One-line marketing description.
48
+ """
49
+ tagline: String!
50
+
51
+ """
52
+ Price in the minor unit of `currency` (e.g. cents).
53
+ """
54
+ priceCents: Int!
55
+
56
+ """
57
+ ISO 4217 currency code for `priceCents`.
58
+ """
59
+ currency: String!
60
+
61
+ """
62
+ Average review rating, from 0.0 to 5.0.
63
+ """
64
+ rating: Float!
65
+
66
+ """
67
+ Whether the product can currently be ordered.
68
+ """
69
+ inStock: Boolean!
70
+ }
71
+
72
+ """
73
+ A page of products and the cursors to continue paginating.
74
+ """
75
+ type ProductConnection {
76
+ edges: [ProductEdge!]!
77
+ pageInfo: PageInfo!
78
+
79
+ """
80
+ Total number of products in the catalog, across all pages.
81
+ """
82
+ totalCount: Int!
83
+ }
84
+
85
+ """
86
+ A product plus the opaque cursor identifying its position.
87
+ """
88
+ type ProductEdge {
89
+ cursor: String!
90
+ node: Product!
91
+ }
92
+
93
+ """
94
+ Forward-pagination info per the Relay connection specification.
95
+ """
96
+ type PageInfo {
97
+ endCursor: String
98
+ hasNextPage: Boolean!
99
+ }
100
+
101
+ type Query {
102
+ """
103
+ Fetches an object by its globally unique ID.
104
+ """
105
+ node(id: ID!): Node
106
+
107
+ """
108
+ The entry point for the current user's view of the graph.
109
+ """
110
+ viewer: Viewer!
111
+ }
@@ -0,0 +1,137 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { CATALOG_PRODUCTS, executeLocalOperation } from "./schema.js";
3
+
4
+ interface ProductsPage {
5
+ readonly viewer: {
6
+ readonly products: {
7
+ readonly edges: readonly {
8
+ readonly cursor: string;
9
+ readonly node: { readonly id: string; readonly name: string };
10
+ }[];
11
+ readonly pageInfo: {
12
+ readonly endCursor: string | null;
13
+ readonly hasNextPage: boolean;
14
+ };
15
+ readonly totalCount: number;
16
+ };
17
+ };
18
+ }
19
+
20
+ const PRODUCTS_QUERY = `
21
+ query SchemaTestsProductsQuery($first: Int, $after: String) {
22
+ viewer {
23
+ products(first: $first, after: $after) {
24
+ edges {
25
+ cursor
26
+ node {
27
+ id
28
+ name
29
+ }
30
+ }
31
+ pageInfo {
32
+ endCursor
33
+ hasNextPage
34
+ }
35
+ totalCount
36
+ }
37
+ }
38
+ }
39
+ `;
40
+
41
+ const fetchProductsPage = async (variables: {
42
+ first?: number;
43
+ after?: string;
44
+ }): Promise<ProductsPage> => {
45
+ const result = await executeLocalOperation({
46
+ text: PRODUCTS_QUERY,
47
+ variables,
48
+ });
49
+ expect(result.errors).toBeUndefined();
50
+ return result.data as ProductsPage;
51
+ };
52
+
53
+ describe("executeLocalOperation", () => {
54
+ it("resolves the viewer with the first page of products", async () => {
55
+ const data = await fetchProductsPage({ first: 2 });
56
+ const { products } = data.viewer;
57
+
58
+ expect(products.totalCount).toBe(CATALOG_PRODUCTS.length);
59
+ expect(products.edges.map((edge) => edge.node.name)).toEqual([
60
+ CATALOG_PRODUCTS[0]?.name,
61
+ CATALOG_PRODUCTS[1]?.name,
62
+ ]);
63
+ expect(products.pageInfo.hasNextPage).toBe(true);
64
+ });
65
+
66
+ it("paginates forward from an end cursor without gaps or overlap", async () => {
67
+ const firstPage = await fetchProductsPage({ first: 2 });
68
+ const { endCursor } = firstPage.viewer.products.pageInfo;
69
+ expect(endCursor).not.toBeNull();
70
+
71
+ const secondPage = await fetchProductsPage({
72
+ first: 2,
73
+ after: endCursor as string,
74
+ });
75
+ expect(
76
+ secondPage.viewer.products.edges.map((edge) => edge.node.id),
77
+ ).toEqual([CATALOG_PRODUCTS[2]?.id, CATALOG_PRODUCTS[3]?.id]);
78
+ });
79
+
80
+ it("reports the end of the catalog", async () => {
81
+ const page = await fetchProductsPage({ first: CATALOG_PRODUCTS.length });
82
+ expect(page.viewer.products.pageInfo.hasNextPage).toBe(false);
83
+ expect(page.viewer.products.edges).toHaveLength(CATALOG_PRODUCTS.length);
84
+ });
85
+
86
+ it("rejects malformed cursors as a GraphQL error", async () => {
87
+ const result = await executeLocalOperation({
88
+ text: PRODUCTS_QUERY,
89
+ variables: { first: 1, after: "not-a-cursor" },
90
+ });
91
+ expect(result.errors?.[0]?.message).toContain("Invalid cursor");
92
+ });
93
+
94
+ it("rejects negative cursor indices that encodeCursor can never produce", async () => {
95
+ const result = await executeLocalOperation({
96
+ text: PRODUCTS_QUERY,
97
+ variables: { first: 1, after: "cursor:-1" },
98
+ });
99
+ expect(result.errors?.[0]?.message).toContain("Invalid cursor");
100
+ });
101
+
102
+ it("looks up nodes by global ID and misses unknown IDs", async () => {
103
+ const nodeQuery = `
104
+ query SchemaTestsNodeQuery($id: ID!) {
105
+ node(id: $id) {
106
+ id
107
+ ... on Product {
108
+ name
109
+ }
110
+ }
111
+ }
112
+ `;
113
+ const target = CATALOG_PRODUCTS[3];
114
+
115
+ const hit = await executeLocalOperation({
116
+ text: nodeQuery,
117
+ variables: { id: target?.id },
118
+ });
119
+ expect(hit.data).toEqual({
120
+ node: { id: target?.id, name: target?.name },
121
+ });
122
+
123
+ const miss = await executeLocalOperation({
124
+ text: nodeQuery,
125
+ variables: { id: "Product:does-not-exist" },
126
+ });
127
+ expect(miss.data).toEqual({ node: null });
128
+ });
129
+
130
+ it("returns validation problems as GraphQL errors, not exceptions", async () => {
131
+ const result = await executeLocalOperation({
132
+ text: "query SchemaTestsInvalidQuery { nope }",
133
+ });
134
+ expect(result.data).toBeNull();
135
+ expect(result.errors?.[0]?.message).toContain("nope");
136
+ });
137
+ });
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Executable mock schema for the Relay data layer.
3
+ *
4
+ * Builds the SDL in ./schema.graphql into a graphql-js schema backed by a
5
+ * small, deterministic in-memory catalog, so the app (and its tests and
6
+ * Storybook) can execute real GraphQL operations without a backend. The
7
+ * dataset is static — no randomness, no clocks — which keeps unit tests and
8
+ * visual tests reproducible.
9
+ *
10
+ * (The file name above is deliberately not backtick-quoted:
11
+ * vite-plugin-relay-lite's tag scanner matches the word "graphql" followed
12
+ * by a backtick even inside comments, and would try to parse what follows
13
+ * as a GraphQL document.)
14
+ */
15
+
16
+ import { buildSchema, GraphQLError, graphql } from "graphql";
17
+ import schemaSource from "./schema.graphql?raw";
18
+
19
+ /** A product row in the in-memory catalog. */
20
+ export interface ProductRecord {
21
+ /** Discriminant used by graphql-js to resolve the `Node` interface. */
22
+ readonly __typename: "Product";
23
+ readonly id: string;
24
+ readonly name: string;
25
+ readonly tagline: string;
26
+ readonly priceCents: number;
27
+ readonly currency: string;
28
+ readonly rating: number;
29
+ readonly inStock: boolean;
30
+ }
31
+
32
+ /**
33
+ * The full catalog, in stable order. IDs follow the `Product:{n}` global-ID
34
+ * convention consumed by `Query.node`; they are opaque to clients.
35
+ */
36
+ export const CATALOG_PRODUCTS: readonly ProductRecord[] = [
37
+ {
38
+ __typename: "Product",
39
+ id: "Product:1",
40
+ name: "Vanguard Workstation",
41
+ tagline: "A certified Ubuntu desktop for heavy compilation workloads",
42
+ priceCents: 189_900,
43
+ currency: "USD",
44
+ rating: 4.7,
45
+ inStock: true,
46
+ },
47
+ {
48
+ __typename: "Product",
49
+ id: "Product:2",
50
+ name: "Meridian Laptop 14",
51
+ tagline: "Thin, quiet, and pre-loaded with your team's golden image",
52
+ priceCents: 129_900,
53
+ currency: "USD",
54
+ rating: 4.5,
55
+ inStock: true,
56
+ },
57
+ {
58
+ __typename: "Product",
59
+ id: "Product:3",
60
+ name: "Beacon Micro Server",
61
+ tagline: "A fanless edge node that fits in a network cabinet",
62
+ priceCents: 64_900,
63
+ currency: "USD",
64
+ rating: 4.2,
65
+ inStock: false,
66
+ },
67
+ {
68
+ __typename: "Product",
69
+ id: "Product:4",
70
+ name: "Atlas Rack Server",
71
+ tagline: "Dense compute for private-cloud deployments",
72
+ priceCents: 449_900,
73
+ currency: "USD",
74
+ rating: 4.8,
75
+ inStock: true,
76
+ },
77
+ {
78
+ __typename: "Product",
79
+ id: "Product:5",
80
+ name: "Harbor NAS Enclosure",
81
+ tagline: "Four bays of quiet, snapshot-friendly storage",
82
+ priceCents: 89_900,
83
+ currency: "USD",
84
+ rating: 4.1,
85
+ inStock: true,
86
+ },
87
+ {
88
+ __typename: "Product",
89
+ id: "Product:6",
90
+ name: "Relay IoT Gateway",
91
+ tagline: "Bridges field sensors onto your message bus securely",
92
+ priceCents: 29_900,
93
+ currency: "USD",
94
+ rating: 3.9,
95
+ inStock: false,
96
+ },
97
+ ];
98
+
99
+ const productsById = new Map(
100
+ CATALOG_PRODUCTS.map((product) => [product.id, product]),
101
+ );
102
+
103
+ const CURSOR_PREFIX = "cursor:";
104
+
105
+ /** Encodes a catalog index as an opaque connection cursor. */
106
+ const encodeCursor = (index: number): string => `${CURSOR_PREFIX}${index}`;
107
+
108
+ /** Decodes a connection cursor back to a catalog index; rejects foreign cursors. */
109
+ const decodeCursor = (cursor: string): number => {
110
+ const index = Number(cursor.slice(CURSOR_PREFIX.length));
111
+ if (
112
+ !cursor.startsWith(CURSOR_PREFIX) ||
113
+ !Number.isInteger(index) ||
114
+ index < 0
115
+ ) {
116
+ throw new GraphQLError(`Invalid cursor: ${cursor}`);
117
+ }
118
+ return index;
119
+ };
120
+
121
+ interface ProductsArguments {
122
+ readonly first?: number | null;
123
+ readonly after?: string | null;
124
+ }
125
+
126
+ /**
127
+ * Resolves `Viewer.products` with honest forward cursor pagination: `after`
128
+ * positions the window just past the given cursor, `first` bounds its size,
129
+ * and `pageInfo` reflects whether more of the catalog remains.
130
+ */
131
+ const resolveProducts = ({ first, after }: ProductsArguments) => {
132
+ if (typeof first === "number" && first < 0) {
133
+ throw new GraphQLError(
134
+ `Argument "first" must be non-negative, got ${first}`,
135
+ );
136
+ }
137
+ const startIndex = after == null ? 0 : decodeCursor(after) + 1;
138
+ const endIndex = first == null ? CATALOG_PRODUCTS.length : startIndex + first;
139
+ const edges = CATALOG_PRODUCTS.slice(startIndex, endIndex).map(
140
+ (node, offset) => ({
141
+ cursor: encodeCursor(startIndex + offset),
142
+ node,
143
+ }),
144
+ );
145
+
146
+ return {
147
+ edges,
148
+ pageInfo: {
149
+ endCursor: edges.at(-1)?.cursor ?? null,
150
+ hasNextPage: startIndex + edges.length < CATALOG_PRODUCTS.length,
151
+ },
152
+ totalCount: CATALOG_PRODUCTS.length,
153
+ };
154
+ };
155
+
156
+ const schema = buildSchema(schemaSource);
157
+
158
+ // Root value for graphql-js's default field resolver: root fields are
159
+ // functions receiving the field arguments, and `Viewer.products` is a method
160
+ // on the viewer object for the same reason. `Node` resolution relies on the
161
+ // `__typename` discriminant each record carries.
162
+ const rootValue = {
163
+ node: ({ id }: { id: string }) => productsById.get(id) ?? null,
164
+ viewer: () => ({
165
+ name: "Ada Lovelace",
166
+ products: (args: ProductsArguments) => resolveProducts(args),
167
+ }),
168
+ };
169
+
170
+ /** Input for {@link executeLocalOperation}. */
171
+ export interface ExecuteLocalOperationOptions {
172
+ /** Full GraphQL source text of the operation. */
173
+ readonly text: string;
174
+ /** Variable values for the operation. */
175
+ readonly variables?: Record<string, unknown>;
176
+ }
177
+
178
+ /** Result shape of {@link executeLocalOperation} — a standard GraphQL response. */
179
+ export interface LocalOperationResult {
180
+ readonly data?: unknown;
181
+ readonly errors?: readonly { readonly message: string }[];
182
+ }
183
+
184
+ /**
185
+ * Executes a GraphQL operation against the in-memory catalog schema.
186
+ *
187
+ * This is the execution half of the mock backend: `relay.config.json` points
188
+ * the compiler at ./schema.graphql for validation and codegen, and the Relay
189
+ * environment's local executor calls this function at runtime.
190
+ */
191
+ export const executeLocalOperation = async (
192
+ options: ExecuteLocalOperationOptions,
193
+ ): Promise<LocalOperationResult> => {
194
+ const result = await graphql({
195
+ schema,
196
+ source: options.text,
197
+ variableValues: options.variables,
198
+ rootValue,
199
+ });
200
+
201
+ return {
202
+ data: result.data ?? null,
203
+ errors: result.errors?.map((error) => error.toJSON()),
204
+ };
205
+ };
@@ -10,6 +10,9 @@ import {
10
10
  } from "@canonical/router-core";
11
11
  import type { ReactElement, ReactNode } from "react";
12
12
  import accountRoutes from "#domains/account/routes.js";
13
+ <% if (relay) { -%>
14
+ import catalogRoutes from "#domains/catalog/routes.js";
15
+ <% } -%>
13
16
  <% if (forms) { -%>
14
17
  import contactRoutes from "#domains/contact/routes.js";
15
18
  <% } -%>
@@ -105,6 +108,10 @@ const [account, login] = group(publicLayout, [
105
108
  <% if (forms) { -%>
106
109
  const [contact] = group(publicLayout, [contactRoutes.contact] as const);
107
110
 
111
+ <% } -%>
112
+ <% if (relay) { -%>
113
+ const [catalog] = group(publicLayout, [catalogRoutes.catalog] as const);
114
+
108
115
  <% } -%>
109
116
  const appRoutes = {
110
117
  guide,
@@ -114,6 +121,9 @@ const appRoutes = {
114
121
  <% if (forms) { -%>
115
122
  contact,
116
123
  <% } -%>
124
+ <% if (relay) { -%>
125
+ catalog,
126
+ <% } -%>
117
127
  } as const;
118
128
 
119
129
  export type AppRoutes = typeof appRoutes;
@@ -2,6 +2,10 @@ import { HeadProvider } from "@canonical/react-head";
2
2
  import type { ServerEntrypointProps } from "@canonical/react-ssr/renderer";
3
3
  import { createStaticRouter } from "@canonical/router-core";
4
4
  import { Outlet, RouterProvider } from "@canonical/router-react";
5
+ <% if (relay) { -%>
6
+ import { RelayEnvironmentProvider } from "react-relay";
7
+ import { createEnvironment } from "#relay/environment.js";
8
+ <% } -%>
5
9
  import { appRoutes, middleware, notFoundRoute } from "../routes.js";
6
10
  import "#styles/app.css";
7
11
 
@@ -18,10 +22,41 @@ export default function EntryServer(props: ServerEntrypointProps<InitialData>) {
18
22
  middleware: [...middleware],
19
23
  notFound: notFoundRoute,
20
24
  });
25
+ <% if (relay) { -%>
26
+
27
+ // A fresh Relay environment per server render, so no store state leaks
28
+ // between requests. Nothing fetches through it yet: components that issue
29
+ // queries are wrapped in `ClientOnly` (see CatalogPage) until data
30
+ // serialization/hydration is supported; the provider is here so any
31
+ // component touching Relay context renders without branching on runtime.
32
+ const relayEnvironment = createEnvironment();
33
+ <% } -%>
21
34
 
22
35
  // Paint the cookie-resolved theme on <html> for a flash-free first render —
23
36
  // the same element `usePreferredTheme` toggles on the client, and one React
24
37
  // does not hydrate (only `#root` is), so there is no mismatch to reconcile.
38
+ <% if (relay) { -%>
39
+ return (
40
+ <html lang={props.lang} className={initialData.theme}>
41
+ <head>
42
+ {props.otherHeadElements}
43
+ {props.scriptElements}
44
+ {props.linkElements}
45
+ </head>
46
+ <body>
47
+ <div id="root">
48
+ <HeadProvider>
49
+ <RelayEnvironmentProvider environment={relayEnvironment}>
50
+ <RouterProvider router={router}>
51
+ <Outlet fallback={<p>Loading…</p>} />
52
+ </RouterProvider>
53
+ </RelayEnvironmentProvider>
54
+ </HeadProvider>
55
+ </div>
56
+ </body>
57
+ </html>
58
+ );
59
+ <% } else { -%>
25
60
  return (
26
61
  <html lang={props.lang} className={initialData.theme}>
27
62
  <head>
@@ -40,6 +75,7 @@ export default function EntryServer(props: ServerEntrypointProps<InitialData>) {
40
75
  </body>
41
76
  </html>
42
77
  );
78
+ <% } -%>
43
79
  }
44
80
 
45
81
  export type { InitialData };
@@ -22,6 +22,9 @@ export default async function getSitemapItems(): Promise<SitemapItem[]> {
22
22
  return [
23
23
  { loc: "/", changefreq: "weekly", priority: 1.0 },
24
24
  { loc: "/guides/router-core", changefreq: "monthly", priority: 0.8 },
25
+ <% if (relay) { -%>
26
+ { loc: "/catalog", changefreq: "weekly", priority: 0.7 },
27
+ <% } -%>
25
28
  <% if (forms) { -%>
26
29
  { loc: "/contact", changefreq: "monthly", priority: 0.7 },
27
30
  <% } -%>
@@ -15,6 +15,9 @@
15
15
  "paths": {
16
16
  "#lib/*": ["./lib/*"],
17
17
  "#domains/*": ["./domains/*"],
18
+ <% if (relay) { -%>
19
+ "#relay/*": ["./relay/*"],
20
+ <% } -%>
18
21
  "#styles/*": ["./styles/*"]
19
22
  }
20
23
  },
@@ -0,0 +1,92 @@
1
+ import react from "@vitejs/plugin-react";
2
+ import browserslist from "browserslist";
3
+ import { browserslistToTargets } from "lightningcss";
4
+ import { defineConfig } from "vite";
5
+ <% if (relay) { -%>
6
+ import relay from "vite-plugin-relay-lite";
7
+ <% } -%>
8
+
9
+ // Path aliases (#lib, #domains, #styles) are declared as Node subpath imports
10
+ // in package.json "imports" and resolved natively by Vite — no resolver plugin.
11
+ const PORT = Number(process.env.PORT) || undefined;
12
+
13
+ // `build:server` runs `vite build --mode server` to compile the two server
14
+ // renderers in a single pass. Each is a separate, individually-instantiated
15
+ // Lego brick, so they are named Rollup inputs — the build emits
16
+ // `dist/server/renderer.js` (the JSX app) + `dist/server/sitemap.js` (the XML
17
+ // sitemap), which the preview servers import directly. Every other command
18
+ // (`dev`, `build:client`, `preview`) uses the default mode and the SPA client
19
+ // build (`--ssrManifest --outDir dist/client`).
20
+ export default defineConfig(({ mode }) => ({
21
+ <% if (relay) { -%>
22
+ // Relay's `graphql\`...\`` tags must be rewritten into imports of the
23
+ // compiler-generated artifacts. `@vitejs/plugin-react` v6 is OXC-based (no
24
+ // Babel), so the classic `babel-plugin-relay` route would need the
25
+ // `@rolldown/plugin-babel` escape hatch; `vite-plugin-relay-lite` does the
26
+ // same rewrite with its own parser and no Babel, and works on Vite 8 /
27
+ // rolldown despite its peer range stopping at Vite 7 (bun installs it with
28
+ // only a peer-version warning). Footgun: its tag scanner matches the word
29
+ // "graphql" followed by a backtick even inside comments, so never
30
+ // backtick-quote a graphql file name in a comment. `codegen: false` because
31
+ // artifacts are committed and regenerated explicitly via the `relay` /
32
+ // `relay:watch` scripts.
33
+ plugins: [relay({ codegen: false }), react()],
34
+ <% } else { -%>
35
+ plugins: [react()],
36
+ <% } -%>
37
+ // Honour the PORT env var for `dev` (SPA) and `preview` so all server scripts
38
+ // — including the SSR ones, which already read PORT — respond to it uniformly.
39
+ server: { port: PORT },
40
+ preview: { port: PORT },
41
+ // CSS delivery is the app's job, not the libraries': @canonical/* packages
42
+ // deliberately ship modern, uncompiled per-component CSS and take no stance
43
+ // on browser support. Lightning CSS (already bundled with Vite 8) compiles
44
+ // that CSS down to this app's declared browser floor — the browserslist
45
+ // query in .browserslistrc, which is the one knob to turn when support
46
+ // requirements change. Not everything can be downleveled: math functions
47
+ // like `mod()` (used by the typography baseline grid) have no polyfillable
48
+ // form, so that feature's effective Chromium ≥ 125 floor is unchanged.
49
+ css: {
50
+ transformer: "lightningcss",
51
+ lightningcss: { targets: browserslistToTargets(browserslist()) },
52
+ },
53
+ build: {
54
+ // Minify CSS with Lightning CSS too (instead of the esbuild default), so
55
+ // a single tool owns both downleveling and minification — in the client
56
+ // build and the server build alike.
57
+ cssMinify: "lightningcss",
58
+ ...(mode === "server"
59
+ ? {
60
+ ssr: true,
61
+ outDir: "dist/server",
62
+ rollupOptions: {
63
+ input: {
64
+ renderer: "src/server/renderer.tsx",
65
+ sitemap: "src/sitemap/renderer.ts",
66
+ },
67
+ },
68
+ }
69
+ : undefined),
70
+ },
71
+ ssr: {
72
+ // Bundle @canonical/* for SSR rather than externalising them, for two
73
+ // reasons: (1) some packages declare only a "module" entry (no
74
+ // "main"/"exports"), which Vite's SSR (Node-style) resolver ignores —
75
+ // externalising them fails with ERR_RESOLVE_PACKAGE_ENTRY_FAIL; (2) their
76
+ // built output imports CSS as a side effect (e.g. `import "./x.css"`),
77
+ // which Node cannot load (ERR_UNKNOWN_FILE_EXTENSION) but Vite's SSR
78
+ // transform no-ops. The regex covers the whole scope so any current or
79
+ // future @canonical dependency is handled.
80
+ <% if (relay) { -%>
81
+ //
82
+ // The Relay packages (react-relay, relay-runtime, relay-runtime-network,
83
+ // graphql) stay externalised like react itself. Two packaging defects
84
+ // made that possible and are fixed via `patchedDependencies` (see
85
+ // patches/): react-relay's CJS exports are member expressions
86
+ // cjs-module-lexer cannot detect (breaking named imports under Node SSR
87
+ // and Vite's dev module runner), and relay-runtime-network@0.1.0 ships an
88
+ // `imports` map pointing at its unpublished src/ directory.
89
+ <% } -%>
90
+ noExternal: [/^@canonical\//],
91
+ },
92
+ }));
@@ -0,0 +1,22 @@
1
+ import * as matchers from "@testing-library/jest-dom/matchers";
2
+ import { cleanup } from "@testing-library/react";
3
+ <% if (relay) { -%>
4
+ import { afterEach, expect, vi } from "vitest";
5
+ <% } else { -%>
6
+ import { afterEach, expect } from "vitest";
7
+ <% } -%>
8
+
9
+ expect.extend(matchers as unknown as Parameters<typeof expect.extend>[0]);
10
+ <% if (relay) { -%>
11
+
12
+ // relay-test-utils' `createMockEnvironment` wraps environment methods in
13
+ // `jest.fn` mocks whenever NODE_ENV === "test", reaching for a global `jest`
14
+ // object. Vitest sets NODE_ENV=test but exposes `vi` instead, so alias it —
15
+ // `vi.fn` is API-compatible with the `jest.fn` surface relay-test-utils uses
16
+ // (`.mock`, `.mockClear`).
17
+ (globalThis as { jest?: typeof vi }).jest = vi;
18
+ <% } -%>
19
+
20
+ afterEach(() => {
21
+ cleanup();
22
+ });