@uniformdev/canvas-next 19.10.0 → 19.12.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.
@@ -30,185 +30,381 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/route/index.ts
31
31
  var route_exports = {};
32
32
  __export(route_exports, {
33
+ getStaticPaths: () => getStaticPaths2,
33
34
  unstable_getServerSideProps: () => unstable_getServerSideProps,
34
- unstable_logIssues: () => unstable_logIssues,
35
- unstable_withUniformGetServerSideProps: () => unstable_withUniformGetServerSideProps
35
+ unstable_getStaticProps: () => unstable_getStaticProps,
36
+ unstable_withUniformGetServerSideProps: () => unstable_withUniformGetServerSideProps,
37
+ unstable_withUniformGetStaticProps: () => unstable_withUniformGetStaticProps,
38
+ withUniformGetStaticPaths: () => withUniformGetStaticPaths
36
39
  });
37
40
  module.exports = __toCommonJS(route_exports);
38
41
 
39
- // src/route/withUniformGetServerSideProps.ts
42
+ // src/project-map/withUniformGetServerSideProps.ts
40
43
  var import_canvas = require("@uniformdev/canvas");
41
- var import_chalk3 = __toESM(require("chalk"));
42
-
43
- // src/route/defaultHandleComposition.ts
44
- var import_chalk2 = __toESM(require("chalk"));
45
-
46
- // src/route/logIssues.ts
47
- var import_chalk = __toESM(require("chalk"));
48
- function unstable_logIssues(prefix, issues, colour) {
49
- colour = colour != null ? colour : "red";
50
- const reversedIssues = [...issues].reverse();
51
- console.error(
52
- `${import_chalk.default[colour](prefix)}
53
- ${reversedIssues.map(
54
- (issue) => `${import_chalk.default[colour](">")} ${import_chalk.default.italic.gray(indent(issue.type.toUpperCase(), 7))} ${renderIssue(
55
- issue
56
- )}`
57
- ).join("\n")}`
58
- );
59
- }
60
- function renderIssue(issue) {
61
- var _a;
62
- let path;
63
- let type;
64
- let message = issue.message;
65
- let detail;
66
- if (issue.type !== "config") {
67
- path = issue.componentPath;
68
- type = issue.componentType;
69
- message = issue.message;
70
- }
71
- if (issue.type === "binding") {
72
- detail = `Binding expression: ${(_a = issue.expression) == null ? void 0 : _a.pointer}`;
73
- } else if (issue.type === "data") {
74
- detail = `Data resource name: ${issue.dataName}, data type: ${issue.dataType}`;
75
- }
76
- if (issue.type === "input") {
77
- detail = issue.inputName;
78
- }
79
- let result = `${import_chalk.default.white(blockify(message))}`;
80
- if (detail) {
81
- result += `
82
- ${indent(" ", 10)}${import_chalk.default.gray(`${detail}`)}`;
83
- }
84
- if (path && type) {
85
- result += `
86
- ${indent(" ", 10)}${import_chalk.default.gray(`Occurred on component ${type} at slot path ${path}`)}`;
87
- }
88
- return result;
89
- }
90
- function indent(str, len) {
91
- const indent2 = len != null ? len : 10;
92
- return str.padStart(indent2);
93
- }
94
- function blockify(str, len) {
95
- const indentSize = len != null ? len : 10;
96
- return str.split("\n").map((line, index) => index === 0 ? line : `${indent(" ", indentSize)}${line}`).join("\n");
97
- }
98
-
99
- // src/route/defaultHandleComposition.ts
100
- function defaultHandleComposition(matched) {
101
- var _a, _b;
102
- const resErrors = (_a = matched.compositionApiResponse.errors) != null ? _a : [];
103
- const resWarnings = (_b = matched.compositionApiResponse.warnings) != null ? _b : [];
104
- const colour = resErrors.length > 0 ? "red" : resWarnings.length > 0 ? "yellow" : "green";
105
- console.log(`[canvas-next] ${import_chalk2.default[colour]("matched")} ${matched.matchedRoute}`, matched.type);
106
- if (matched.dynamicInputs) {
107
- const entries = Object.entries(matched.dynamicInputs);
108
- if (entries.length > 0) {
109
- console.log(
110
- ` ${import_chalk2.default.gray("Matched dynamic inputs:\n ")}`,
111
- entries.map(([k, v]) => `${k}: ${v}`).join("\n ")
112
- );
44
+ var withUniformGetServerSideProps = (options) => {
45
+ const canvasClient = (options == null ? void 0 : options.client) || new import_canvas.CanvasClient({
46
+ apiKey: process.env.UNIFORM_API_KEY,
47
+ projectId: process.env.UNIFORM_PROJECT_ID,
48
+ apiHost: process.env.UNIFORM_CLI_BASE_URL,
49
+ edgeApiHost: process.env.UNIFORM_CLI_BASE_EDGE_URL
50
+ });
51
+ return async function wrappedGetServerSideProps(context) {
52
+ var _a, _b;
53
+ const projectMapId = (_a = options == null ? void 0 : options.projectMapId) != null ? _a : process.env.UNIFORM_PROJECT_MAP_ID;
54
+ const { preview, previewData } = context;
55
+ let composition = void 0;
56
+ let nodePath = (options == null ? void 0 : options.prefix) ? context.resolvedUrl.replace(new RegExp(`^${options.prefix}`), "") : context.resolvedUrl;
57
+ if (options == null ? void 0 : options.modifyPath) {
58
+ nodePath = options.modifyPath(nodePath, context);
113
59
  }
114
- }
115
- if (resErrors.length > 0) {
116
- unstable_logIssues(
117
- `[canvas-next] ${matched.matchedRoute} composition data error${resErrors.length === 1 ? "" : "s"}; some content may be missing`,
118
- resErrors,
119
- "red"
120
- );
121
- }
122
- if (resWarnings.length > 0) {
123
- unstable_logIssues(
124
- `[canvas-next] ${matched.matchedRoute} composition data warning${resWarnings.length === 1 ? "" : "s"}; some content may be missing`,
125
- resWarnings,
126
- "yellow"
127
- );
128
- }
129
- if (matched.compositionApiResponse.diagnostics) {
130
- console.log(`[canvas-next] ${import_chalk2.default.green("Route diagnostics are enabled. Diagnostic data:")}`);
131
- console.log(JSON.stringify(matched.compositionApiResponse.diagnostics, null, 2));
132
- }
133
- return matched.compositionApiResponse.composition;
134
- }
135
-
136
- // src/route/defaultHandleRedirect.ts
137
- var import_redirect = require("@uniformdev/redirect");
138
- function defaultHandleRedirect(matched, requestUrl) {
139
- return {
140
- redirect: {
141
- destination: import_redirect.RedirectClient.getTargetVariableExpandedUrl(requestUrl, matched.redirect),
142
- statusCode: matched.redirect.targetStatusCode
60
+ if (previewData == null ? void 0 : previewData.isUniformContextualEditing) {
61
+ composition = { ...import_canvas.EMPTY_COMPOSITION, _id: (_b = previewData.compositionId) != null ? _b : import_canvas.EMPTY_COMPOSITION._id };
62
+ } else {
63
+ try {
64
+ const time = Date.now();
65
+ const response = await canvasClient.getCompositionByNodePath({
66
+ ...options == null ? void 0 : options.requestOptions,
67
+ projectMapId,
68
+ projectMapNodePath: nodePath,
69
+ state: preview || (options == null ? void 0 : options.preview) ? import_canvas.CANVAS_DRAFT_STATE : import_canvas.CANVAS_PUBLISHED_STATE
70
+ });
71
+ const duration = Date.now() - time;
72
+ composition = response.composition;
73
+ if (!(options == null ? void 0 : options.silent)) {
74
+ (0, import_canvas.logCompositionResponse)(response, duration);
75
+ }
76
+ } catch (e) {
77
+ console.error("[canvas-next] Failed to fetch composition", e);
78
+ return {
79
+ notFound: true
80
+ };
81
+ }
143
82
  }
83
+ const ret = (options == null ? void 0 : options.callback) ? await options.callback(context, composition) : { props: {} };
84
+ if (Object.hasOwn(ret, "props")) {
85
+ const casted = ret;
86
+ casted.props["data"] = composition;
87
+ }
88
+ return ret;
144
89
  };
145
- }
90
+ };
146
91
 
147
- // src/route/withUniformGetServerSideProps.ts
148
- var unstable_withUniformGetServerSideProps = (options) => {
149
- var _a, _b, _c, _d;
150
- const handleNotFound = (_a = options == null ? void 0 : options.handleNotFound) != null ? _a : () => ({ notFound: true });
151
- const handleComposition = (_b = options == null ? void 0 : options.handleComposition) != null ? _b : defaultHandleComposition;
152
- const handleRedirect = (_c = options == null ? void 0 : options.handleRedirect) != null ? _c : defaultHandleRedirect;
153
- const handleModifyPath = (_d = options == null ? void 0 : options.modifyPath) != null ? _d : (path) => decodeURI(path);
154
- return async function wrappedGetServerSideProps(context) {
155
- var _a2, _b2;
156
- const projectMapId = (_a2 = options == null ? void 0 : options.projectMapId) != null ? _a2 : process.env.UNIFORM_PROJECT_MAP_ID;
157
- const routeClient = (options == null ? void 0 : options.client) || new import_canvas.unstable_RouteClient({
92
+ // src/project-map/withUniformGetStaticPaths.ts
93
+ var import_canvas2 = require("@uniformdev/canvas");
94
+ var import_project_map = require("@uniformdev/project-map");
95
+ var withUniformGetStaticPaths = (options) => {
96
+ return async function wrappedGetStaticPaths() {
97
+ var _a, _b;
98
+ const projectMapId = (_a = options == null ? void 0 : options.projectMapId) != null ? _a : process.env.UNIFORM_PROJECT_MAP_ID;
99
+ const projectMapClient = (_b = options == null ? void 0 : options.client) != null ? _b : new import_project_map.ProjectMapClient({
158
100
  apiKey: process.env.UNIFORM_API_KEY,
159
101
  projectId: process.env.UNIFORM_PROJECT_ID,
160
- edgeApiHost: process.env.UNIFORM_CLI_BASE_EDGE_URL
102
+ apiHost: process.env.UNIFORM_CLI_BASE_URL
103
+ });
104
+ const response = await projectMapClient.getNodes({
105
+ ...options == null ? void 0 : options.requestOptions,
106
+ path: options == null ? void 0 : options.rootPath,
107
+ projectMapId,
108
+ state: (options == null ? void 0 : options.preview) ? import_canvas2.CANVAS_DRAFT_STATE : import_canvas2.CANVAS_PUBLISHED_STATE
161
109
  });
162
- const { previewData } = context;
110
+ const nodes = (options == null ? void 0 : options.callback) ? await options.callback(response.nodes) : response.nodes;
111
+ const paths = nodes == null ? void 0 : nodes.filter((node) => Boolean(node.compositionId)).map((node) => {
112
+ var _a2;
113
+ return `${(_a2 = options == null ? void 0 : options.prefix) != null ? _a2 : ""}${node.path}`;
114
+ });
115
+ return {
116
+ paths,
117
+ fallback: true
118
+ };
119
+ };
120
+ };
121
+
122
+ // src/project-map/withUniformGetStaticProps.ts
123
+ var import_canvas3 = require("@uniformdev/canvas");
124
+
125
+ // src/helpers/resolveSlugFromParams.ts
126
+ var resolveSlugFromParams = ({
127
+ param = "slug",
128
+ params
129
+ }) => {
130
+ const slug = (params == null ? void 0 : params[param]) || "";
131
+ const slugString = Array.isArray(slug) ? slug.join("/") : slug;
132
+ return `/${slugString}`;
133
+ };
134
+
135
+ // src/project-map/withUniformGetStaticProps.ts
136
+ var withUniformGetStaticProps = (options) => {
137
+ var _a;
138
+ const canvasClient = (_a = options == null ? void 0 : options.client) != null ? _a : new import_canvas3.CanvasClient({
139
+ apiKey: process.env.UNIFORM_API_KEY,
140
+ projectId: process.env.UNIFORM_PROJECT_ID,
141
+ apiHost: process.env.UNIFORM_CLI_BASE_URL,
142
+ edgeApiHost: process.env.UNIFORM_CLI_BASE_EDGE_URL
143
+ });
144
+ return async function wrappedGetStaticProps(context) {
145
+ var _a2, _b;
146
+ const projectMapId = (_a2 = options == null ? void 0 : options.projectMapId) != null ? _a2 : process.env.UNIFORM_PROJECT_MAP_ID;
147
+ let pathString = resolveSlugFromParams({
148
+ param: options == null ? void 0 : options.param,
149
+ params: context == null ? void 0 : context.params
150
+ });
151
+ if (options == null ? void 0 : options.modifyPath) {
152
+ pathString = options.modifyPath(pathString, context);
153
+ }
154
+ const { preview, previewData } = context;
163
155
  let composition = void 0;
164
- let nodePath = (options == null ? void 0 : options.prefix) ? context.resolvedUrl.replace(new RegExp(`^${options.prefix}`), "") : context.resolvedUrl;
165
- nodePath = handleModifyPath(nodePath, context);
166
156
  if (previewData == null ? void 0 : previewData.isUniformContextualEditing) {
167
- composition = { ...import_canvas.EMPTY_COMPOSITION, _id: (_b2 = previewData.compositionId) != null ? _b2 : import_canvas.EMPTY_COMPOSITION._id };
157
+ composition = { ...import_canvas3.EMPTY_COMPOSITION, _id: (_b = previewData.compositionId) != null ? _b : import_canvas3.EMPTY_COMPOSITION._id };
168
158
  } else {
169
159
  try {
170
- console.log("[canvas-next] get route", nodePath);
171
- const response = await routeClient.getRoute({
160
+ const time = Date.now();
161
+ const response = await canvasClient.getCompositionByNodePath({
172
162
  ...options == null ? void 0 : options.requestOptions,
173
163
  projectMapId,
164
+ projectMapNodePath: pathString,
165
+ state: preview || (options == null ? void 0 : options.preview) ? import_canvas3.CANVAS_DRAFT_STATE : import_canvas3.CANVAS_PUBLISHED_STATE
166
+ });
167
+ const duration = Date.now() - time;
168
+ composition = response.composition;
169
+ if (!(options == null ? void 0 : options.silent)) {
170
+ (0, import_canvas3.logCompositionResponse)(response, duration);
171
+ }
172
+ } catch (e) {
173
+ console.error("[canvas-next] Failed to fetch composition", e);
174
+ return {
175
+ notFound: true
176
+ };
177
+ }
178
+ }
179
+ const ret = options.callback ? await options.callback(context, composition) : { props: {} };
180
+ if (composition && Object.hasOwn(ret, "props")) {
181
+ const casted = ret;
182
+ casted.props["data"] = composition;
183
+ }
184
+ return ret;
185
+ };
186
+ };
187
+
188
+ // src/project-map/index.ts
189
+ var getServerSideProps = withUniformGetServerSideProps();
190
+ var getStaticProps = withUniformGetStaticProps({ param: "path" });
191
+ var getStaticPaths = withUniformGetStaticPaths();
192
+
193
+ // src/route/withUniformGetServerSideProps.ts
194
+ var import_redirect = require("@uniformdev/redirect");
195
+
196
+ // src/route/createRouteFetcher.ts
197
+ var import_canvas4 = require("@uniformdev/canvas");
198
+ var import_ansi_colors = __toESM(require("ansi-colors"));
199
+ var { red } = import_ansi_colors.default;
200
+ function createRouteFetcher(options) {
201
+ const {
202
+ handleNotFound,
203
+ handleComposition,
204
+ handleRedirect,
205
+ defaultHandleComposition,
206
+ defaultHandleNotFound,
207
+ defaultHandleRedirect,
208
+ modifyPath,
209
+ projectMapId = process.env.UNIFORM_PROJECT_MAP_ID,
210
+ client,
211
+ prefix,
212
+ requestOptions,
213
+ silent,
214
+ parseContext
215
+ } = options;
216
+ const routeClient = client || new import_canvas4.unstable_RouteClient({
217
+ apiKey: process.env.UNIFORM_API_KEY,
218
+ projectId: process.env.UNIFORM_PROJECT_ID,
219
+ edgeApiHost: process.env.UNIFORM_CLI_BASE_EDGE_URL
220
+ });
221
+ const handleModifyPath = modifyPath != null ? modifyPath : (path) => decodeURI(path);
222
+ return async function fetcher(context) {
223
+ const { contextualEditingCompositionId, resolvedUrl } = parseContext(context);
224
+ let nodePath = prefix ? resolvedUrl.replace(new RegExp(`^${prefix}`), "") : resolvedUrl;
225
+ nodePath = handleModifyPath(nodePath, context);
226
+ const invokeRedirectResult = (redirect, duration) => (handleRedirect != null ? handleRedirect : defaultHandleRedirect)(
227
+ nodePath,
228
+ redirect,
229
+ context,
230
+ (response) => defaultHandleRedirect(
231
+ nodePath,
232
+ response,
233
+ context,
234
+ () => {
235
+ throw new Error();
236
+ },
237
+ duration
238
+ ),
239
+ duration
240
+ );
241
+ const invokeNotFoundResult = (response, duration) => (handleNotFound != null ? handleNotFound : defaultHandleNotFound)(
242
+ response,
243
+ context,
244
+ (response2) => defaultHandleNotFound(
245
+ response2,
246
+ context,
247
+ () => {
248
+ throw new Error();
249
+ },
250
+ duration
251
+ ),
252
+ duration
253
+ );
254
+ const invokeCompositionResult = (response, duration) => (handleComposition != null ? handleComposition : defaultHandleComposition)(
255
+ response,
256
+ context,
257
+ (response2) => defaultHandleComposition(
258
+ response2,
259
+ context,
260
+ () => {
261
+ throw new Error();
262
+ },
263
+ duration
264
+ ),
265
+ duration
266
+ );
267
+ if (contextualEditingCompositionId) {
268
+ const previewEmptyComposition = await invokeCompositionResult(
269
+ {
270
+ type: "composition",
271
+ matchedRoute: "contextual-editing",
272
+ compositionApiResponse: {
273
+ composition: {
274
+ ...import_canvas4.EMPTY_COMPOSITION,
275
+ _id: contextualEditingCompositionId != null ? contextualEditingCompositionId : import_canvas4.EMPTY_COMPOSITION._id
276
+ }
277
+ }
278
+ },
279
+ 0
280
+ );
281
+ return previewEmptyComposition;
282
+ } else {
283
+ try {
284
+ if (!silent) {
285
+ console.log("Fetch route", nodePath);
286
+ }
287
+ const time = Date.now();
288
+ const response = await routeClient.getRoute({
289
+ ...requestOptions,
290
+ projectMapId,
174
291
  path: nodePath
175
292
  });
293
+ const duration = Date.now() - time;
294
+ if (!silent) {
295
+ (0, import_canvas4.logRouteResponse)(response, duration);
296
+ }
176
297
  if (response.type === "redirect") {
177
- return handleRedirect(response, nodePath, context, defaultHandleRedirect);
298
+ return invokeRedirectResult(response, duration);
178
299
  }
179
300
  if (response.type === "notFound") {
180
- return handleNotFound(response, context);
301
+ return invokeNotFoundResult(response, duration);
181
302
  }
182
- const handleResult = handleComposition(response, context, defaultHandleComposition);
303
+ const handleResult = await invokeCompositionResult(response, duration);
183
304
  if (!handleResult) {
184
- return { notFound: true };
305
+ return invokeNotFoundResult({ type: "notFound" }, duration);
185
306
  }
186
- composition = handleResult;
307
+ return handleResult;
187
308
  } catch (e) {
188
- console.error(import_chalk3.default.red("[canvas-next] Failed to fetch composition"), e);
189
- if (e instanceof import_canvas.ApiClientError) {
309
+ console.error(red("Failed to fetch route"), e);
310
+ if (e instanceof import_canvas4.ApiClientError) {
190
311
  if (e.statusCode === 404) {
191
- return { notFound: true };
312
+ return invokeNotFoundResult({ type: "notFound" }, 0);
192
313
  }
193
- throw new Error(`Failed to fetch composition. See server logs for details.`);
314
+ throw new Error(`Failed to fetch route. See preceding server logs for details.`);
194
315
  }
195
316
  throw e;
196
317
  }
197
318
  }
198
- const ret = (options == null ? void 0 : options.callback) ? await options.callback(context, composition) : { props: {} };
199
- if (Object.hasOwn(ret, "props")) {
200
- const casted = ret;
201
- casted.props["data"] = composition;
319
+ };
320
+ }
321
+
322
+ // src/route/withUniformGetServerSideProps.ts
323
+ var unstable_withUniformGetServerSideProps = (options) => {
324
+ const defaultHandleRedirect = (requestUrl, matched) => {
325
+ return {
326
+ redirect: {
327
+ destination: import_redirect.RedirectClient.getTargetVariableExpandedUrl(requestUrl, matched.redirect),
328
+ statusCode: matched.redirect.targetStatusCode
329
+ }
330
+ };
331
+ };
332
+ const defaultHandleNotFound = () => ({
333
+ notFound: true
334
+ });
335
+ const defaultHandleComposition = async (matched) => {
336
+ return {
337
+ props: {
338
+ data: matched.compositionApiResponse.composition
339
+ }
340
+ };
341
+ };
342
+ const routeFetcher = createRouteFetcher({
343
+ ...options,
344
+ defaultHandleComposition,
345
+ defaultHandleNotFound,
346
+ defaultHandleRedirect,
347
+ parseContext(context) {
348
+ var _a;
349
+ return {
350
+ contextualEditingCompositionId: (_a = context.previewData) == null ? void 0 : _a.compositionId,
351
+ resolvedUrl: context.resolvedUrl
352
+ };
202
353
  }
203
- return ret;
354
+ });
355
+ return routeFetcher;
356
+ };
357
+
358
+ // src/route/withUniformGetStaticProps.ts
359
+ var import_redirect2 = require("@uniformdev/redirect");
360
+ var unstable_withUniformGetStaticProps = (options) => {
361
+ const defaultHandleRedirect = (requestUrl, matched) => {
362
+ return {
363
+ redirect: {
364
+ destination: import_redirect2.RedirectClient.getTargetVariableExpandedUrl(requestUrl, matched.redirect),
365
+ statusCode: matched.redirect.targetStatusCode
366
+ }
367
+ };
204
368
  };
369
+ const defaultHandleNotFound = () => ({
370
+ notFound: true
371
+ });
372
+ const defaultHandleComposition = async (matched) => {
373
+ return {
374
+ props: {
375
+ data: matched.compositionApiResponse.composition
376
+ }
377
+ };
378
+ };
379
+ const routeFetcher = createRouteFetcher({
380
+ ...options,
381
+ defaultHandleComposition,
382
+ defaultHandleNotFound,
383
+ defaultHandleRedirect,
384
+ parseContext(context) {
385
+ var _a, _b;
386
+ return {
387
+ contextualEditingCompositionId: (_a = context.previewData) == null ? void 0 : _a.compositionId,
388
+ resolvedUrl: resolveSlugFromParams({
389
+ params: context.params,
390
+ param: (_b = options == null ? void 0 : options.param) != null ? _b : "route"
391
+ })
392
+ };
393
+ }
394
+ });
395
+ return routeFetcher;
205
396
  };
206
397
 
207
398
  // src/route/index.ts
208
399
  var unstable_getServerSideProps = unstable_withUniformGetServerSideProps();
400
+ var unstable_getStaticProps = unstable_withUniformGetStaticProps();
401
+ var getStaticPaths2 = withUniformGetStaticPaths();
209
402
  // Annotate the CommonJS export names for ESM import in node:
210
403
  0 && (module.exports = {
404
+ getStaticPaths,
211
405
  unstable_getServerSideProps,
212
- unstable_logIssues,
213
- unstable_withUniformGetServerSideProps
406
+ unstable_getStaticProps,
407
+ unstable_withUniformGetServerSideProps,
408
+ unstable_withUniformGetStaticProps,
409
+ withUniformGetStaticPaths
214
410
  });