@knapsack/renderer-react 4.90.0--canary.6959.a15e90e.0 → 4.90.0--canary.7255.526ffd7.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.
@@ -1,16 +1,4 @@
1
1
  "use strict";
2
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
- if (kind === "m") throw new TypeError("Private method is not writable");
4
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
- };
8
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
- };
13
- var _KnapsackReactRenderer_demoWrapperPath, _KnapsackReactRenderer_disableReactStrictMode;
14
2
  Object.defineProperty(exports, "__esModule", { value: true });
15
3
  exports.KnapsackReactRenderer = void 0;
16
4
  const renderer_webpack_base_1 = require("@knapsack/renderer-webpack-base");
@@ -50,6 +38,13 @@ See https://reactjs.org/docs/strict-mode.html for more info
50
38
  codeSrcs: zod_1.z.array(types_1.CodeSrcUserConfigSchema).optional(),
51
39
  });
52
40
  class KnapsackReactRenderer extends renderer_webpack_base_1.RendererWebpackBase {
41
+ /**
42
+ * `react.js` & `react-dom.js` root relative paths
43
+ */
44
+ assets;
45
+ babelConfig;
46
+ #demoWrapperPath;
47
+ #disableReactStrictMode;
53
48
  constructor(options = {}) {
54
49
  const { error } = OptionsSchema.safeParse(options);
55
50
  const { webpackConfig, demoWrapperPath, disableReactStrictMode, codeSrcs } = options;
@@ -63,469 +58,6 @@ class KnapsackReactRenderer extends renderer_webpack_base_1.RendererWebpackBase
63
58
  (0, path_1.join)(__dirname, '../dist/client/init.mjs'),
64
59
  ],
65
60
  });
66
- _KnapsackReactRenderer_demoWrapperPath.set(this, void 0);
67
- _KnapsackReactRenderer_disableReactStrictMode.set(this, void 0);
68
- this.setConfig = (opt) => {
69
- super.setConfig(opt);
70
- const { absolutePath, exists: demoWrapperPathExists, type, } = this.resolvePathSync({
71
- path: __classPrivateFieldGet(this, _KnapsackReactRenderer_demoWrapperPath, "f"),
72
- resolveFromDir: this.userConfigDir,
73
- });
74
- if (!demoWrapperPathExists) {
75
- throw new Error(`Could not find demo wrapper at: "${__classPrivateFieldGet(this, _KnapsackReactRenderer_demoWrapperPath, "f")}"\nPlease adjust setting in "knapsack.config.js" or pass a different path when creating the React Renderer.`);
76
- }
77
- this.registerExtraJsImports({
78
- DemoWrapper: {
79
- exportName: 'DemoWrapper',
80
- isDefaultExport: true,
81
- path: type === 'package' ? __classPrivateFieldGet(this, _KnapsackReactRenderer_demoWrapperPath, "f") : absolutePath,
82
- },
83
- });
84
- };
85
- this.init = async (opt) => {
86
- await super.init(opt);
87
- };
88
- this.hydrate = async (opt) => {
89
- await super.hydrate(opt);
90
- await this.init({ missingFileVerbosity: 'silent' });
91
- };
92
- this.getMeta = () => ({
93
- id: this.id,
94
- title: 'React',
95
- aliasUse: 'optional',
96
- aliasTitle: 'Named Export',
97
- aliasIsJsNamedExport: true,
98
- aliasDescription: 'If `export X` was used instead of `export default`, then provide X.',
99
- enableDataDemos: true,
100
- enableTemplateDemos: true,
101
- hasSlotsSupport: true,
102
- hasSlotOptionsSupport: true,
103
- version: pkg.version,
104
- hasInferSpecSupport: true,
105
- syntaxHighlightingLanguage: 'jsx',
106
- hasTemplateSuggestionsSupport: true,
107
- prototypingTemplate: {
108
- path: '@knapsack/renderer-react/prototype-template',
109
- spec: {
110
- isInferred: false,
111
- props: {
112
- type: 'object',
113
- properties: {},
114
- },
115
- slots: {
116
- children: { title: 'Children' },
117
- },
118
- },
119
- },
120
- });
121
- this.changeCase = (str) => (0, utils_1.pascalCase)(str);
122
- this.createWebpackConfig = () => {
123
- const config = super.createWebpackConfig();
124
- // bundle React with webpack (removed config.externals) so init.mts imports work
125
- // and React/ReactDOM are globally available for inline babel-transpiled scripts
126
- return config;
127
- };
128
- this.render = async (opt) => {
129
- var _a;
130
- if (((_a = opt.demo) === null || _a === void 0 ? void 0 : _a.type) === 'template') {
131
- const { absolutePath: templateDemoPath, exists } = await this.resolvePath(opt.demo.templateInfo.path);
132
- if (!exists) {
133
- throw new Error(`Template demo file does not exist: "${opt.demo.templateInfo.path}"`);
134
- }
135
- const [templateFileContents, { usage, importMap }] = await Promise.all([
136
- (0, file_utils_1.readFile)(templateDemoPath),
137
- this.getUsageAndImports({
138
- ...opt,
139
- importMap: new Map(),
140
- }),
141
- ]);
142
- const demoApp = await (0, utils_2.getDemoAppUsage)({
143
- children: usage,
144
- });
145
- const results = await this.prepClientRenderResults({
146
- usage: templateFileContents,
147
- demoApp,
148
- renderOptions: opt,
149
- importMap,
150
- });
151
- return results;
152
- }
153
- if ((0, types_1.isDemoWithData)(opt.demo)) {
154
- const { usage, importMap } = await this.getUsageAndImports({
155
- ...opt,
156
- importMap: new Map(),
157
- });
158
- const importCode = renderer_webpack_base_1.RendererWebpackBase.createJsImportCodeBlock({
159
- importMap,
160
- });
161
- const [demoAppUsage, demoApp] = await Promise.all([
162
- (0, utils_2.getDemoAppUsage)({
163
- children: usage,
164
- imports: importCode,
165
- format: true,
166
- }),
167
- (0, utils_2.getDemoAppUsage)({
168
- children: usage,
169
- }),
170
- ]);
171
- return this.prepClientRenderResults({
172
- demoApp,
173
- usage: demoAppUsage,
174
- renderOptions: opt,
175
- importMap,
176
- });
177
- }
178
- const _exhaustiveCheck = opt.demo;
179
- throw new Error(`Unhandled demo type at reactRenderer.render`);
180
- };
181
- this.getUsageAndImports = async ({ demo, state, importMap, }) => {
182
- if (!demo) {
183
- throw new Error(`No demo provided while rendering `);
184
- }
185
- if ((0, types_1.isDemoWithData)(demo)) {
186
- const { data: { props, slots, slotsOptionsComputed }, } = demo;
187
- const { codeSrcPath, exportName } = this.normalizeDemo({
188
- demo,
189
- state,
190
- });
191
- if (!codeSrcPath) {
192
- throw new Error(`Could not determine code source path for demo: ${JSON.stringify(demo)}`);
193
- }
194
- const { name: templateName } = await this.addUniqueValueToImportMap({
195
- importMap,
196
- path: codeSrcPath,
197
- alias: exportName,
198
- });
199
- const children = [];
200
- const extraProps = [];
201
- if (slots) {
202
- const slotNames = Object.keys(slots);
203
- const slotUsages = await Promise.all(slotNames.map(async (slotName) => {
204
- const slotItems = slots[slotName];
205
- const slotItemsUsages = await Promise.all(slotItems
206
- // remove any incomplete item - happens when users are filling out form
207
- .filter((slotItem) => {
208
- if (!slotItem)
209
- return false;
210
- if (slotItem.type !== 'text') {
211
- if (slotItem.type === 'template-demo' && !slotItem.demoId) {
212
- return false;
213
- }
214
- }
215
- return true;
216
- })
217
- .map(async (slotItem) => {
218
- var _a;
219
- if (slotItem.type === 'text') {
220
- if (slotItems.length === 1 && slotName !== 'children') {
221
- // The ` prevents multi-line strings from causing error (even though they don't show a line break)
222
- return `\`${slotItem.text}\``;
223
- }
224
- return slotItem.text;
225
- }
226
- if (slotItem.type === 'template-reference') {
227
- const slottedTemplate = (_a = state.patterns[slotItem.patternId]) === null || _a === void 0 ? void 0 : _a.templates.find((t) => t.id === slotItem.templateId);
228
- if (!slottedTemplate) {
229
- throw new Error(`Could not find slotted template: ${slotItem.patternId} ${slotItem.templateId}`);
230
- }
231
- const pathInfo = (0, file_utils_1.getPathType)(slottedTemplate.path);
232
- if (pathInfo.type === 'absolute') {
233
- throw new Error(`Absolute paths are not supported for slotted templates: ${slottedTemplate.path}`);
234
- }
235
- const templateRefImport = await this.addUniqueValueToImportMap({
236
- importMap,
237
- path: pathInfo.path,
238
- alias: slottedTemplate.alias || 'default',
239
- });
240
- /**
241
- * i.e. Given a React Component, `Button`, normally this would be `<Button>` with a demo, but since there is none this will just be a reference to it: `Button`
242
- * @see {KsSlotInfo['isTemplateReference']}
243
- * @see {SlottedTemplate}
244
- */
245
- return templateRefImport.name;
246
- }
247
- if (slotItem.type === 'template-demo') {
248
- const thisDemo = slotItem.demo;
249
- if (!thisDemo) {
250
- throw new Error(`Could not find slotted template demo ${JSON.stringify(slotItem)}`);
251
- }
252
- const { usage } = await this.getUsageAndImports({
253
- demo: thisDemo,
254
- state,
255
- importMap,
256
- });
257
- return usage;
258
- }
259
- const _exhaustiveCheck = slotItem;
260
- throw new Error(`Unknown slot item: ${JSON.stringify(slotItem)}`);
261
- }));
262
- return {
263
- slotName,
264
- slotItemsUsages,
265
- };
266
- }));
267
- slotUsages.forEach(({ slotName, slotItemsUsages }) => {
268
- const slotOptionsComputed = slotsOptionsComputed === null || slotsOptionsComputed === void 0 ? void 0 : slotsOptionsComputed[slotName];
269
- const { openTag, closeTag } = (0, renderers_1.createSlotOptionsHtmlTags)({
270
- slotOptionsComputed,
271
- classAttributeName: 'className',
272
- stylesValueType: 'object',
273
- });
274
- if (openTag) {
275
- if (slotName === 'children') {
276
- children.push(openTag);
277
- }
278
- else {
279
- extraProps.push({
280
- key: slotName,
281
- value: openTag,
282
- });
283
- }
284
- }
285
- slotItemsUsages.forEach((usage) => {
286
- if (slotName === 'children') {
287
- children.push(usage);
288
- }
289
- else {
290
- extraProps.push({
291
- key: slotName,
292
- value: usage,
293
- });
294
- }
295
- });
296
- if (closeTag) {
297
- if (slotName === 'children') {
298
- children.push(closeTag);
299
- }
300
- else {
301
- extraProps.push({
302
- key: slotName,
303
- value: closeTag,
304
- });
305
- }
306
- }
307
- });
308
- }
309
- const usage = await (0, utils_2.getUsage)({
310
- templateName,
311
- props,
312
- children: children.join('\n'),
313
- extraProps,
314
- });
315
- return {
316
- usage,
317
- importMap,
318
- };
319
- }
320
- if (demo.type === 'template') {
321
- const { templateInfo } = demo;
322
- const pathInfo = (0, file_utils_1.getPathType)(templateInfo.path);
323
- if (pathInfo.type === 'absolute') {
324
- throw new Error(`Absolute paths are not supported for templates: ${templateInfo.path}`);
325
- }
326
- const { name: templateName } = await this.addUniqueValueToImportMap({
327
- importMap,
328
- path: pathInfo.path,
329
- alias: templateInfo.alias || 'default',
330
- });
331
- const usage = await (0, utils_2.getUsage)({ templateName });
332
- return {
333
- usage,
334
- importMap,
335
- };
336
- }
337
- const _exhaustiveCheck = demo;
338
- throw new Error(`Unhandled demo type at reactRenderer.getUsageAndImports`);
339
- };
340
- this.getDiscovery = async () => {
341
- const codeSrcPaths = this.getCodeSrcs().map(({ path }) => path);
342
- const results = await Promise.all(codeSrcPaths.map(async (path) => {
343
- try {
344
- const { exports, errorMsg } = await (0, file_utils_1.getJsExportNames)({
345
- path,
346
- resolveFromDir: this.dataDir,
347
- pkgPathAliases: this.pkgPathAliases,
348
- });
349
- if (errorMsg) {
350
- throw new Error(errorMsg);
351
- }
352
- return {
353
- path,
354
- exportNames: exports
355
- // only allow names that start with a capital letter (i.e. React Component names)
356
- // will exclude helper functions and custom hooks
357
- .filter((e) => e === 'default' || (0, utils_1.isFirstLetterCapital)(e)),
358
- };
359
- }
360
- catch (e) {
361
- this.log.warn(`Could not get import names for "${path}": ${e.message}`, null, this.logPrefix);
362
- return { path, exportNames: [] };
363
- }
364
- }));
365
- return {
366
- rendererId: this.id,
367
- meta: this.getMeta(),
368
- codeSrcsByPath: Object.fromEntries(this.codeSrcs.entries()),
369
- templates: results.flatMap(({ path, exportNames }) => exportNames.map((exportName) => (0, types_1.addIdToTemplateInfo)({
370
- rendererId: this.id,
371
- codeSrcPath: path,
372
- exportName,
373
- }))),
374
- };
375
- };
376
- this.inspect = async (templateInfo) => {
377
- const { codeSrcPath, exportName } = templateInfo;
378
- const { inferSpec } = await import('./analyze/index.mjs');
379
- const { ksTemplateSpec: spec } = await inferSpec({
380
- path: codeSrcPath,
381
- namedExport: exportName,
382
- resolveFrom: this.dataDir,
383
- pkgPathAliases: this.pkgPathAliases,
384
- });
385
- return {
386
- type: 'success',
387
- spec,
388
- };
389
- };
390
- this.watch = async () => {
391
- super.watch();
392
- app_1.knapsackEvents.onPatternTemplateChanged(() => {
393
- (0, utils_2.clearInferSpecCache)();
394
- });
395
- };
396
- this.getTemplateMeta = async ({ pattern, template, }) => {
397
- const files = [];
398
- if ((0, types_1.isSpecNotInferred)(template.spec)) {
399
- const schema = JSON.parse(JSON.stringify(template.spec.props || {}));
400
- if (template.spec.slots) {
401
- Object.entries(template.spec.slots).forEach(([id, info]) => {
402
- var _a;
403
- schema.properties[id] = {
404
- typeof: 'function',
405
- tsType: 'React.ReactNode',
406
- description: info.allowedPatternIds
407
- ? `${info.description}. Only use: ${info.allowedPatternIds.join(', ')}`
408
- : info.description,
409
- };
410
- schema.required = (_a = schema.required) !== null && _a !== void 0 ? _a : [];
411
- if (info.isRequired)
412
- schema.required.push(id);
413
- });
414
- }
415
- const typeDefs = await KnapsackReactRenderer.convertSchemaToTypeScriptDefs({
416
- schema,
417
- title: `${this.changeCase(pattern.id)}Props`,
418
- // @todo pull in base url
419
- description: `[Knapsack Docs](http://localhost:3999/pattern/${pattern.id}/${template.id})`,
420
- patternId: pattern.id,
421
- templateId: template.id,
422
- postBanner: `import * as React from 'react';`,
423
- });
424
- files.push({
425
- contents: typeDefs,
426
- encoding: 'utf8',
427
- path: `${pattern.id}.${template.id}.spec.d.ts`,
428
- });
429
- files.push({
430
- contents: JSON.stringify(schema, null, ' '),
431
- encoding: 'utf8',
432
- path: `${pattern.id}.${template.id}.spec.json`,
433
- });
434
- }
435
- return files;
436
- };
437
- this.alterTemplateMetaFiles = async ({ files, metaDir, }) => {
438
- const imports = [];
439
- const ext = '.spec.d.ts';
440
- files.forEach((file) => {
441
- if (file.path.endsWith(ext)) {
442
- const { base } = (0, path_1.parse)(file.path);
443
- const [patternId, templateId] = base.split('.');
444
- const isFirst = templateId === this.id;
445
- const exportName = this.changeCase(`${patternId}Props`);
446
- const exportNameWithTemplateId = this.changeCase(`${patternId}-${templateId}Props`);
447
- imports.push(`export { ${isFirst
448
- ? exportName
449
- : `${exportName} as ${exportNameWithTemplateId}`} } from './${(0, path_1.relative)(metaDir, file.path).replace('.d.ts', '')}';`);
450
- }
451
- });
452
- // extra line at end of file
453
- imports.push('');
454
- return [
455
- ...files,
456
- {
457
- contents: imports.join('\n'),
458
- encoding: 'utf8',
459
- path: (0, path_1.join)(metaDir, 'react.d.ts'),
460
- },
461
- ];
462
- };
463
- this.getTemplateSuggestions = async ({ newPath, state, }) => {
464
- // Deduplicate suggestions using Map with stringified path/alias as keys.
465
- // Map values are suggestion objects, Array.from(map.values()) returns deduplicated array.
466
- const usedSuggestions = Array.from(new Map(Object.values(state.patterns).reduce((acc, { templateDemos, templates }) => {
467
- templates.forEach(({ path, alias, templateLanguageId }) => {
468
- if (templateLanguageId !== this.id)
469
- return;
470
- acc.push([JSON.stringify({ path, alias }), { path, alias }]);
471
- });
472
- templateDemos.forEach(({ templateInfo: { path, alias }, templateLanguageId }) => {
473
- if (templateLanguageId !== this.id)
474
- return;
475
- acc.push([JSON.stringify({ path, alias }), { path, alias }]);
476
- });
477
- return acc;
478
- }, [])).values());
479
- const codeSrcs = new Set(this.getCodeSrcs().map(({ path }) => path));
480
- const allPaths = [
481
- ...new Set([
482
- newPath,
483
- ...Object.keys(this.pkgPathAliases || {}),
484
- ...codeSrcs,
485
- ]),
486
- ];
487
- // @todo use getDiscovery
488
- const allSuggestions = await Promise.all(allPaths.map(async (path) => {
489
- if (!path)
490
- return [];
491
- try {
492
- const { exports, errorMsg } = await (0, file_utils_1.getJsExportNames)({
493
- path,
494
- resolveFromDir: this.dataDir,
495
- pkgPathAliases: this.pkgPathAliases,
496
- });
497
- if (errorMsg) {
498
- throw new Error(errorMsg);
499
- }
500
- return (exports
501
- // only allow names that start with a capital letter (i.e. React Component names)
502
- // will exclude helper functions and custom hooks
503
- .filter((e) => e === 'default' || (0, utils_1.isFirstLetterCapital)(e))
504
- .map((name) => ({
505
- alias: name,
506
- path,
507
- })));
508
- }
509
- catch (e) {
510
- // only want this showing with verbose since template suggestions are not critical
511
- this.log.verbose(`Error getting import names for ${path}: ${e.message}`, null, this.logPrefix);
512
- return [];
513
- }
514
- })).then((results) => {
515
- // sadly `Promise.all` & `.flatMap` just don't work, so this:
516
- return results.flat();
517
- });
518
- const suggestions = allSuggestions.filter((s) => {
519
- return !usedSuggestions.find((us) => us.alias === s.alias && us.path === s.path);
520
- });
521
- const connectedSuggestions = usedSuggestions.map((s) => ({
522
- ...s,
523
- connected: true,
524
- }));
525
- return {
526
- suggestions: [...suggestions, ...connectedSuggestions],
527
- };
528
- };
529
61
  if (error) {
530
62
  this.log.error(`"KnapsackReactRenderer" constructor has invalid options, please fix in "knapsack.config.cjs":`, zod_1.z.prettifyError(error));
531
63
  process.exit(1);
@@ -533,10 +65,10 @@ class KnapsackReactRenderer extends renderer_webpack_base_1.RendererWebpackBase
533
65
  }
534
66
  this.language = 'jsx';
535
67
  this.assets = [];
536
- __classPrivateFieldSet(this, _KnapsackReactRenderer_disableReactStrictMode, disableReactStrictMode, "f");
68
+ this.#disableReactStrictMode = disableReactStrictMode;
537
69
  this.creators = [react_creators_1.createReactPattern];
538
70
  if (demoWrapperPath) {
539
- __classPrivateFieldSet(this, _KnapsackReactRenderer_demoWrapperPath, demoWrapperPath, "f");
71
+ this.#demoWrapperPath = demoWrapperPath;
540
72
  }
541
73
  else {
542
74
  const defaultDemoWrapperPath = '@knapsack/renderer-react-components/demo-wrapper';
@@ -549,13 +81,67 @@ class KnapsackReactRenderer extends renderer_webpack_base_1.RendererWebpackBase
549
81
  if (!exists) {
550
82
  throw new Error(`Could not locate the default Demo Wrapper component at "${defaultDemoWrapperPath}". This is an internal error and may be caused by a NPM install issue.`);
551
83
  }
552
- __classPrivateFieldSet(this, _KnapsackReactRenderer_demoWrapperPath, absolutePath, "f");
84
+ this.#demoWrapperPath = absolutePath;
553
85
  }
554
86
  }
87
+ setConfig = (opt) => {
88
+ super.setConfig(opt);
89
+ const { absolutePath, exists: demoWrapperPathExists, type, } = this.resolvePathSync({
90
+ path: this.#demoWrapperPath,
91
+ resolveFromDir: this.userConfigDir,
92
+ });
93
+ if (!demoWrapperPathExists) {
94
+ throw new Error(`Could not find demo wrapper at: "${this.#demoWrapperPath}"\nPlease adjust setting in "knapsack.config.js" or pass a different path when creating the React Renderer.`);
95
+ }
96
+ this.registerExtraJsImports({
97
+ DemoWrapper: {
98
+ exportName: 'DemoWrapper',
99
+ isDefaultExport: true,
100
+ path: type === 'package' ? this.#demoWrapperPath : absolutePath,
101
+ },
102
+ });
103
+ };
104
+ init = async (opt) => {
105
+ await super.init(opt);
106
+ };
107
+ hydrate = async (opt) => {
108
+ await super.hydrate(opt);
109
+ await this.init({ missingFileVerbosity: 'silent' });
110
+ };
111
+ getMeta = () => ({
112
+ id: this.id,
113
+ title: 'React',
114
+ aliasUse: 'optional',
115
+ aliasTitle: 'Named Export',
116
+ aliasIsJsNamedExport: true,
117
+ aliasDescription: 'If `export X` was used instead of `export default`, then provide X.',
118
+ enableDataDemos: true,
119
+ enableTemplateDemos: true,
120
+ hasSlotsSupport: true,
121
+ hasSlotOptionsSupport: true,
122
+ version: pkg.version,
123
+ hasInferSpecSupport: true,
124
+ syntaxHighlightingLanguage: 'jsx',
125
+ hasTemplateSuggestionsSupport: true,
126
+ prototypingTemplate: {
127
+ path: '@knapsack/renderer-react/prototype-template',
128
+ spec: {
129
+ isInferred: false,
130
+ props: {
131
+ type: 'object',
132
+ properties: {},
133
+ },
134
+ slots: {
135
+ children: { title: 'Children' },
136
+ },
137
+ },
138
+ },
139
+ });
140
+ changeCase = (str) => (0, utils_1.pascalCase)(str);
555
141
  async prepClientRenderResults({ usage, demoApp, importMap, renderOptions: { demo }, }) {
556
142
  const meta = {
557
143
  demo,
558
- disableReactStrictMode: __classPrivateFieldGet(this, _KnapsackReactRenderer_disableReactStrictMode, "f"),
144
+ disableReactStrictMode: this.#disableReactStrictMode,
559
145
  neededImportsByCodeSrcId: (0, renderer_webpack_base_1.convertImportMapToNeededImportsByCodeSrcId)(importMap),
560
146
  demoWrapperProps: {
561
147
  demo,
@@ -599,7 +185,404 @@ class KnapsackReactRenderer extends renderer_webpack_base_1.RendererWebpackBase
599
185
  templateLanguage: this.language,
600
186
  };
601
187
  }
188
+ render = async (opt) => {
189
+ if (opt.demo?.type === 'template') {
190
+ const { absolutePath: templateDemoPath, exists } = await this.resolvePath(opt.demo.templateInfo.path);
191
+ if (!exists) {
192
+ throw new Error(`Template demo file does not exist: "${opt.demo.templateInfo.path}"`);
193
+ }
194
+ const [templateFileContents, { usage, importMap }] = await Promise.all([
195
+ (0, file_utils_1.readFile)(templateDemoPath),
196
+ this.getUsageAndImports({
197
+ ...opt,
198
+ importMap: new Map(),
199
+ }),
200
+ ]);
201
+ const demoApp = await (0, utils_2.getDemoAppUsage)({
202
+ children: usage,
203
+ });
204
+ const results = await this.prepClientRenderResults({
205
+ usage: templateFileContents,
206
+ demoApp,
207
+ renderOptions: opt,
208
+ importMap,
209
+ });
210
+ return results;
211
+ }
212
+ if ((0, types_1.isDemoWithData)(opt.demo)) {
213
+ const { usage, importMap } = await this.getUsageAndImports({
214
+ ...opt,
215
+ importMap: new Map(),
216
+ });
217
+ const importCode = renderer_webpack_base_1.RendererWebpackBase.createJsImportCodeBlock({
218
+ importMap,
219
+ });
220
+ const [demoAppUsage, demoApp] = await Promise.all([
221
+ (0, utils_2.getDemoAppUsage)({
222
+ children: usage,
223
+ imports: importCode,
224
+ format: true,
225
+ }),
226
+ (0, utils_2.getDemoAppUsage)({
227
+ children: usage,
228
+ }),
229
+ ]);
230
+ return this.prepClientRenderResults({
231
+ demoApp,
232
+ usage: demoAppUsage,
233
+ renderOptions: opt,
234
+ importMap,
235
+ });
236
+ }
237
+ const _exhaustiveCheck = opt.demo;
238
+ throw new Error(`Unhandled demo type at reactRenderer.render`);
239
+ };
240
+ getUsageAndImports = async ({ demo, state, importMap, }) => {
241
+ if (!demo) {
242
+ throw new Error(`No demo provided while rendering `);
243
+ }
244
+ if ((0, types_1.isDemoWithData)(demo)) {
245
+ const { data: { props, slots, slotsOptionsComputed }, } = demo;
246
+ const { codeSrcPath, exportName } = this.normalizeDemo({
247
+ demo,
248
+ state,
249
+ });
250
+ if (!codeSrcPath) {
251
+ throw new Error(`Could not determine code source path for demo: ${JSON.stringify(demo)}`);
252
+ }
253
+ const { name: templateName } = await this.addUniqueValueToImportMap({
254
+ importMap,
255
+ path: codeSrcPath,
256
+ alias: exportName,
257
+ });
258
+ const children = [];
259
+ const extraProps = [];
260
+ if (slots) {
261
+ const slotNames = Object.keys(slots);
262
+ const slotUsages = await Promise.all(slotNames.map(async (slotName) => {
263
+ const slotItems = slots[slotName];
264
+ const slotItemsUsages = await Promise.all(slotItems
265
+ // remove any incomplete item - happens when users are filling out form
266
+ .filter((slotItem) => {
267
+ if (!slotItem)
268
+ return false;
269
+ if (slotItem.type !== 'text') {
270
+ if (slotItem.type === 'template-demo' && !slotItem.demoId) {
271
+ return false;
272
+ }
273
+ }
274
+ return true;
275
+ })
276
+ .map(async (slotItem) => {
277
+ if (slotItem.type === 'text') {
278
+ if (slotItems.length === 1 && slotName !== 'children') {
279
+ // The ` prevents multi-line strings from causing error (even though they don't show a line break)
280
+ return `\`${slotItem.text}\``;
281
+ }
282
+ return slotItem.text;
283
+ }
284
+ if (slotItem.type === 'template-reference') {
285
+ const slottedTemplate = state.patterns[slotItem.patternId]?.templates.find((t) => t.id === slotItem.templateId);
286
+ if (!slottedTemplate) {
287
+ throw new Error(`Could not find slotted template: ${slotItem.patternId} ${slotItem.templateId}`);
288
+ }
289
+ const pathInfo = (0, file_utils_1.getPathType)(slottedTemplate.path);
290
+ if (pathInfo.type === 'absolute') {
291
+ throw new Error(`Absolute paths are not supported for slotted templates: ${slottedTemplate.path}`);
292
+ }
293
+ const templateRefImport = await this.addUniqueValueToImportMap({
294
+ importMap,
295
+ path: pathInfo.path,
296
+ alias: slottedTemplate.alias || 'default',
297
+ });
298
+ /**
299
+ * i.e. Given a React Component, `Button`, normally this would be `<Button>` with a demo, but since there is none this will just be a reference to it: `Button`
300
+ * @see {KsSlotInfo['isTemplateReference']}
301
+ * @see {SlottedTemplate}
302
+ */
303
+ return templateRefImport.name;
304
+ }
305
+ if (slotItem.type === 'template-demo') {
306
+ const thisDemo = slotItem.demo;
307
+ if (!thisDemo) {
308
+ throw new Error(`Could not find slotted template demo ${JSON.stringify(slotItem)}`);
309
+ }
310
+ const { usage } = await this.getUsageAndImports({
311
+ demo: thisDemo,
312
+ state,
313
+ importMap,
314
+ });
315
+ return usage;
316
+ }
317
+ const _exhaustiveCheck = slotItem;
318
+ throw new Error(`Unknown slot item: ${JSON.stringify(slotItem)}`);
319
+ }));
320
+ return {
321
+ slotName,
322
+ slotItemsUsages,
323
+ };
324
+ }));
325
+ slotUsages.forEach(({ slotName, slotItemsUsages }) => {
326
+ const slotOptionsComputed = slotsOptionsComputed?.[slotName];
327
+ const { openTag, closeTag } = (0, renderers_1.createSlotOptionsHtmlTags)({
328
+ slotOptionsComputed,
329
+ classAttributeName: 'className',
330
+ stylesValueType: 'object',
331
+ });
332
+ if (openTag) {
333
+ if (slotName === 'children') {
334
+ children.push(openTag);
335
+ }
336
+ else {
337
+ extraProps.push({
338
+ key: slotName,
339
+ value: openTag,
340
+ });
341
+ }
342
+ }
343
+ slotItemsUsages.forEach((usage) => {
344
+ if (slotName === 'children') {
345
+ children.push(usage);
346
+ }
347
+ else {
348
+ extraProps.push({
349
+ key: slotName,
350
+ value: usage,
351
+ });
352
+ }
353
+ });
354
+ if (closeTag) {
355
+ if (slotName === 'children') {
356
+ children.push(closeTag);
357
+ }
358
+ else {
359
+ extraProps.push({
360
+ key: slotName,
361
+ value: closeTag,
362
+ });
363
+ }
364
+ }
365
+ });
366
+ }
367
+ const usage = await (0, utils_2.getUsage)({
368
+ templateName,
369
+ props,
370
+ children: children.join('\n'),
371
+ extraProps,
372
+ });
373
+ return {
374
+ usage,
375
+ importMap,
376
+ };
377
+ }
378
+ if (demo.type === 'template') {
379
+ const { templateInfo } = demo;
380
+ const pathInfo = (0, file_utils_1.getPathType)(templateInfo.path);
381
+ if (pathInfo.type === 'absolute') {
382
+ throw new Error(`Absolute paths are not supported for templates: ${templateInfo.path}`);
383
+ }
384
+ const { name: templateName } = await this.addUniqueValueToImportMap({
385
+ importMap,
386
+ path: pathInfo.path,
387
+ alias: templateInfo.alias || 'default',
388
+ });
389
+ const usage = await (0, utils_2.getUsage)({ templateName });
390
+ return {
391
+ usage,
392
+ importMap,
393
+ };
394
+ }
395
+ const _exhaustiveCheck = demo;
396
+ throw new Error(`Unhandled demo type at reactRenderer.getUsageAndImports`);
397
+ };
398
+ getDiscovery = async () => {
399
+ const codeSrcPaths = this.getCodeSrcs().map(({ path }) => path);
400
+ const results = await Promise.all(codeSrcPaths.map(async (path) => {
401
+ try {
402
+ const { exports, errorMsg } = await (0, file_utils_1.getJsExportNames)({
403
+ path,
404
+ resolveFromDir: this.dataDir,
405
+ pkgPathAliases: this.pkgPathAliases,
406
+ });
407
+ if (errorMsg) {
408
+ throw new Error(errorMsg);
409
+ }
410
+ return {
411
+ path,
412
+ exportNames: exports
413
+ // only allow names that start with a capital letter (i.e. React Component names)
414
+ // will exclude helper functions and custom hooks
415
+ .filter((e) => e === 'default' || (0, utils_1.isFirstLetterCapital)(e)),
416
+ };
417
+ }
418
+ catch (e) {
419
+ this.log.warn(`Could not get import names for "${path}": ${e.message}`, null, this.logPrefix);
420
+ return { path, exportNames: [] };
421
+ }
422
+ }));
423
+ return {
424
+ rendererId: this.id,
425
+ meta: this.getMeta(),
426
+ codeSrcsByPath: Object.fromEntries(this.codeSrcs.entries()),
427
+ templates: results.flatMap(({ path, exportNames }) => exportNames.map((exportName) => (0, types_1.addIdToTemplateInfo)({
428
+ rendererId: this.id,
429
+ codeSrcPath: path,
430
+ exportName,
431
+ }))),
432
+ };
433
+ };
434
+ inspect = async (templateInfo) => {
435
+ const { codeSrcPath, exportName } = templateInfo;
436
+ const { inferSpec } = await import('./analyze/index.mjs');
437
+ const { ksTemplateSpec: spec } = await inferSpec({
438
+ path: codeSrcPath,
439
+ namedExport: exportName,
440
+ resolveFrom: this.dataDir,
441
+ pkgPathAliases: this.pkgPathAliases,
442
+ });
443
+ return {
444
+ type: 'success',
445
+ spec,
446
+ };
447
+ };
448
+ watch = async () => {
449
+ super.watch();
450
+ app_1.knapsackEvents.onPatternTemplateChanged(() => {
451
+ (0, utils_2.clearInferSpecCache)();
452
+ });
453
+ };
454
+ getTemplateMeta = async ({ pattern, template, }) => {
455
+ const files = [];
456
+ if ((0, types_1.isSpecNotInferred)(template.spec)) {
457
+ const schema = JSON.parse(JSON.stringify(template.spec.props || {}));
458
+ if (template.spec.slots) {
459
+ Object.entries(template.spec.slots).forEach(([id, info]) => {
460
+ schema.properties[id] = {
461
+ typeof: 'function',
462
+ tsType: 'React.ReactNode',
463
+ description: info.allowedPatternIds
464
+ ? `${info.description}. Only use: ${info.allowedPatternIds.join(', ')}`
465
+ : info.description,
466
+ };
467
+ schema.required = schema.required ?? [];
468
+ if (info.isRequired)
469
+ schema.required.push(id);
470
+ });
471
+ }
472
+ const typeDefs = await KnapsackReactRenderer.convertSchemaToTypeScriptDefs({
473
+ schema,
474
+ title: `${this.changeCase(pattern.id)}Props`,
475
+ // @todo pull in base url
476
+ description: `[Knapsack Docs](http://localhost:3999/pattern/${pattern.id}/${template.id})`,
477
+ patternId: pattern.id,
478
+ templateId: template.id,
479
+ postBanner: `import * as React from 'react';`,
480
+ });
481
+ files.push({
482
+ contents: typeDefs,
483
+ encoding: 'utf8',
484
+ path: `${pattern.id}.${template.id}.spec.d.ts`,
485
+ });
486
+ files.push({
487
+ contents: JSON.stringify(schema, null, ' '),
488
+ encoding: 'utf8',
489
+ path: `${pattern.id}.${template.id}.spec.json`,
490
+ });
491
+ }
492
+ return files;
493
+ };
494
+ alterTemplateMetaFiles = async ({ files, metaDir, }) => {
495
+ const imports = [];
496
+ const ext = '.spec.d.ts';
497
+ files.forEach((file) => {
498
+ if (file.path.endsWith(ext)) {
499
+ const { base } = (0, path_1.parse)(file.path);
500
+ const [patternId, templateId] = base.split('.');
501
+ const isFirst = templateId === this.id;
502
+ const exportName = this.changeCase(`${patternId}Props`);
503
+ const exportNameWithTemplateId = this.changeCase(`${patternId}-${templateId}Props`);
504
+ imports.push(`export { ${isFirst
505
+ ? exportName
506
+ : `${exportName} as ${exportNameWithTemplateId}`} } from './${(0, path_1.relative)(metaDir, file.path).replace('.d.ts', '')}';`);
507
+ }
508
+ });
509
+ // extra line at end of file
510
+ imports.push('');
511
+ return [
512
+ ...files,
513
+ {
514
+ contents: imports.join('\n'),
515
+ encoding: 'utf8',
516
+ path: (0, path_1.join)(metaDir, 'react.d.ts'),
517
+ },
518
+ ];
519
+ };
520
+ getTemplateSuggestions = async ({ newPath, state, }) => {
521
+ // Deduplicate suggestions using Map with stringified path/alias as keys.
522
+ // Map values are suggestion objects, Array.from(map.values()) returns deduplicated array.
523
+ const usedSuggestions = Array.from(new Map(Object.values(state.patterns).reduce((acc, { templateDemos, templates }) => {
524
+ templates.forEach(({ path, alias, templateLanguageId }) => {
525
+ if (templateLanguageId !== this.id)
526
+ return;
527
+ acc.push([JSON.stringify({ path, alias }), { path, alias }]);
528
+ });
529
+ templateDemos.forEach(({ templateInfo: { path, alias }, templateLanguageId }) => {
530
+ if (templateLanguageId !== this.id)
531
+ return;
532
+ acc.push([JSON.stringify({ path, alias }), { path, alias }]);
533
+ });
534
+ return acc;
535
+ }, [])).values());
536
+ const codeSrcs = new Set(this.getCodeSrcs().map(({ path }) => path));
537
+ const allPaths = [
538
+ ...new Set([
539
+ newPath,
540
+ ...Object.keys(this.pkgPathAliases || {}),
541
+ ...codeSrcs,
542
+ ]),
543
+ ];
544
+ // @todo use getDiscovery
545
+ const allSuggestions = await Promise.all(allPaths.map(async (path) => {
546
+ if (!path)
547
+ return [];
548
+ try {
549
+ const { exports, errorMsg } = await (0, file_utils_1.getJsExportNames)({
550
+ path,
551
+ resolveFromDir: this.dataDir,
552
+ pkgPathAliases: this.pkgPathAliases,
553
+ });
554
+ if (errorMsg) {
555
+ throw new Error(errorMsg);
556
+ }
557
+ return (exports
558
+ // only allow names that start with a capital letter (i.e. React Component names)
559
+ // will exclude helper functions and custom hooks
560
+ .filter((e) => e === 'default' || (0, utils_1.isFirstLetterCapital)(e))
561
+ .map((name) => ({
562
+ alias: name,
563
+ path,
564
+ })));
565
+ }
566
+ catch (e) {
567
+ // only want this showing with verbose since template suggestions are not critical
568
+ this.log.verbose(`Error getting import names for ${path}: ${e.message}`, null, this.logPrefix);
569
+ return [];
570
+ }
571
+ })).then((results) => {
572
+ // sadly `Promise.all` & `.flatMap` just don't work, so this:
573
+ return results.flat();
574
+ });
575
+ const suggestions = allSuggestions.filter((s) => {
576
+ return !usedSuggestions.find((us) => us.alias === s.alias && us.path === s.path);
577
+ });
578
+ const connectedSuggestions = usedSuggestions.map((s) => ({
579
+ ...s,
580
+ connected: true,
581
+ }));
582
+ return {
583
+ suggestions: [...suggestions, ...connectedSuggestions],
584
+ };
585
+ };
602
586
  }
603
587
  exports.KnapsackReactRenderer = KnapsackReactRenderer;
604
- _KnapsackReactRenderer_demoWrapperPath = new WeakMap(), _KnapsackReactRenderer_disableReactStrictMode = new WeakMap();
605
588
  //# sourceMappingURL=renderer-react.js.map