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