@knapsack/renderer-react 4.70.0--canary.4561.78aed7a.0 → 4.70.0--canary.4821.56b0218.0

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js CHANGED
@@ -727,6 +727,7 @@ var rendererMetaScriptTagId = "ks-react-meta";
727
727
  // src/renderer-react.ts
728
728
  var { pkg } = (0, import_file_utils3.findUpPkgJson)(__dirname);
729
729
  import_app2.log.setupUpdateNotifier({ ...pkg, name: pkg.name, version: pkg.version });
730
+ var errorCatcherPath = (0, import_path2.join)(__dirname, "./error-catcher.mjs");
730
731
  var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer_webpack_base.RendererWebpackBase {
731
732
  static {
732
733
  __name(this, "KnapsackReactRenderer");
@@ -746,22 +747,29 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
746
747
  } = {}) {
747
748
  super({
748
749
  id,
749
- extension: ".jsx",
750
750
  language: "jsx",
751
751
  webpackConfig,
752
752
  extraScripts: [
753
753
  // this is the code in `./client/init.mts`
754
754
  "@knapsack/renderer-react/client"
755
- ]
755
+ ],
756
+ codeSrcs: [demoWrapperPath, errorCatcherPath]
756
757
  });
757
758
  this.language = "jsx";
758
759
  this.assets = [];
759
- this.demoWrapperPath = demoWrapperPath;
760
+ this.demoWrapperPath = (0, import_path2.isAbsolute)(demoWrapperPath) ? demoWrapperPath : this.resolvePathSync({
761
+ path: demoWrapperPath,
762
+ resolveFromDir: this.userConfigDir
763
+ }).absolutePath;
764
+ (0, import_file_utils3.assertFileExists)(
765
+ this.demoWrapperPath,
766
+ `Could not find demo wrapper at: "${this.demoWrapperPath}"
767
+ Please adjust setting in "knapsack.config.js" or pass a different path when creating the React Renderer.`
768
+ );
760
769
  this.disableReactStrictMode = disableReactStrictMode;
761
770
  this.creators = [createReactPattern];
762
771
  }
763
- init = /* @__PURE__ */ __name(async (opt) => {
764
- await super.init(opt);
772
+ init = /* @__PURE__ */ __name(async () => {
765
773
  this.assets = await copyReactAssets(this.outputDir, this.publicPath);
766
774
  if (!await (0, import_file_utils3.exists)(this.demoWrapperPath)) {
767
775
  throw new Error(
@@ -807,76 +815,37 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
807
815
  };
808
816
  return config;
809
817
  }, "createWebpackConfig");
810
- getJsImports = /* @__PURE__ */ __name(() => {
811
- const imports = super.getJsImports();
812
- imports.push(
813
- {
814
- type: "extra",
815
- importInfo: {
816
- type: "default",
817
- path: this.demoWrapperPath,
818
- name: "DemoWrapper"
819
- }
820
- },
821
- {
822
- type: "extra",
823
- importInfo: {
824
- type: "default",
825
- path: (0, import_path2.join)(__dirname, "./error-catcher.mjs"),
826
- name: "ErrorCatcher"
827
- }
828
- }
829
- );
830
- return imports;
831
- }, "getJsImports");
832
818
  async prepClientRenderResults({
833
819
  usage,
834
820
  demoApp,
835
- imports: xImports,
836
- renderOptions: { pattern, template, demo }
821
+ importMap,
822
+ renderOptions: { demo, state, patternId, templateId }
837
823
  }) {
838
- const extraImports = this.getJsImports().filter(
839
- (imp) => imp.type === "extra"
840
- );
841
- const { imports, isDeclaredVarsUnique, nameCollisions } = this.makeKsJsImportsUnique({ imports: [...xImports, ...extraImports] });
842
- if (!isDeclaredVarsUnique) {
843
- import_app2.log.error(`${nameCollisions.join(", ")} are declared multiple times`, {
844
- imports
845
- });
846
- }
847
824
  const meta = {
848
825
  demo,
849
826
  disableReactStrictMode: this.disableReactStrictMode,
850
- neededImports: imports,
827
+ neededImportsByPath: (0, import_renderer_webpack_base.convertImportMapToNeededImportsByPath)(importMap),
828
+ extraImports: {
829
+ DemoWrapper: {
830
+ type: "default",
831
+ path: this.demoWrapperPath,
832
+ name: "DemoWrapper"
833
+ },
834
+ ErrorCatcher: {
835
+ type: "default",
836
+ path: errorCatcherPath,
837
+ name: "ErrorCatcher"
838
+ }
839
+ },
851
840
  demoWrapperProps: {
852
- pattern,
853
- template,
854
- demo,
855
- patternsUsed: imports.flatMap((imp) => {
856
- if (imp.type === "pattern-template") {
857
- return [
858
- {
859
- patternId: imp.patternId,
860
- templateId: imp.templateId
861
- }
862
- ];
863
- }
864
- if (imp.type === "pattern-template-demo") {
865
- return [
866
- {
867
- patternId: imp.patternId,
868
- templateId: imp.templateId,
869
- demoId: imp.demoId
870
- }
871
- ];
872
- }
873
- return [];
874
- })
841
+ patternId,
842
+ templateId,
843
+ demo
875
844
  }
876
845
  };
877
846
  let code = `
878
847
  window.knapsack = window.knapsack || {};
879
- window.knapsack.getDemoApp = ({ ${imports.map((i) => i.importInfo.name).join(", ")} }) => {
848
+ window.knapsack.getDemoApp = ({ ${[...importMap.keys()].join(", ")} }) => {
880
849
  ${demoApp}
881
850
  return ${demoAppName}
882
851
  }
@@ -898,7 +867,7 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
898
867
  <script type="application/javascript">${code}</script>
899
868
  <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
900
869
  ${this.assets.map((asset) => `<script src="${asset}"></script>`).join("\n")}
901
- ${this.createHtmlTagsForAssetPaths({
870
+ ${import_renderer_webpack_base.RendererWebpackBase.createHtmlTagsForAssetPaths({
902
871
  assets: this.getWebpackAssetPaths(),
903
872
  // 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
904
873
  scriptTagsAreAsync: false
@@ -942,9 +911,12 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
942
911
  await (0, import_sleep_promise.default)(waitTime);
943
912
  }
944
913
  }
945
- const [templateFileContents, { usage, imports }] = await Promise.all([
914
+ const [templateFileContents, { usage, importMap }] = await Promise.all([
946
915
  (0, import_file_utils3.readFile)(templateDemoPath),
947
- this.getUsageAndImports(opt)
916
+ this.getUsageAndImports({
917
+ ...opt,
918
+ importMap: /* @__PURE__ */ new Map()
919
+ })
948
920
  ]);
949
921
  const demoApp = await getDemoAppUsage({
950
922
  children: usage
@@ -952,15 +924,18 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
952
924
  const results = await this.prepClientRenderResults({
953
925
  usage: templateFileContents,
954
926
  demoApp,
955
- imports,
956
- renderOptions: opt
927
+ renderOptions: opt,
928
+ importMap
957
929
  });
958
930
  return results;
959
931
  }
960
932
  if (opt.demo?.type === "data") {
961
- const { usage, imports } = await this.getUsageAndImports(opt);
962
- const { code: importCode } = this.createJsImportCodeBlock({
963
- imports
933
+ const { usage, importMap } = await this.getUsageAndImports({
934
+ ...opt,
935
+ importMap: /* @__PURE__ */ new Map()
936
+ });
937
+ const importCode = import_renderer_webpack_base.RendererWebpackBase.createJsImportCodeBlock({
938
+ importMap
964
939
  });
965
940
  const [demoAppUsage, demoApp] = await Promise.all([
966
941
  getDemoAppUsage({
@@ -975,32 +950,40 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
975
950
  return this.prepClientRenderResults({
976
951
  demoApp,
977
952
  usage: demoAppUsage,
978
- imports,
979
- renderOptions: opt
953
+ renderOptions: opt,
954
+ importMap
980
955
  });
981
956
  }
982
957
  }, "render");
983
958
  getUsageAndImports = /* @__PURE__ */ __name(async ({
984
- pattern,
985
- template,
986
- patternManifest,
987
- demo
959
+ patternId,
960
+ templateId,
961
+ demo,
962
+ state,
963
+ importMap
988
964
  }) => {
989
- if (demo?.type && demo.type === "data") {
965
+ if (!demo) {
966
+ throw new Error(
967
+ `No demo provided while rendering ${patternId} ${templateId}`
968
+ );
969
+ }
970
+ const pattern = state.patterns[patternId];
971
+ if (!pattern) {
972
+ throw new Error(`Could not find pattern: ${patternId}`);
973
+ }
974
+ if (demo.type === "data") {
975
+ const template = pattern.templates.find((t) => t.id === templateId);
976
+ if (!template) {
977
+ throw new Error(`Could not find template: ${templateId}`);
978
+ }
990
979
  const {
991
980
  data: { props, slots, slotsOptionsComputed }
992
981
  } = demo;
993
- const importInfo = this.getJsImport({
994
- patternId: pattern.id,
995
- templateId: template.id
982
+ const { name: templateName } = await this.addUniqueValueToImportMap({
983
+ importMap,
984
+ path: template.path,
985
+ alias: template.alias || "default"
996
986
  });
997
- if (!importInfo) {
998
- throw new Error(
999
- `Could not find import for pattern-template: ${pattern.id}-${template.id}`
1000
- );
1001
- }
1002
- const { type, name: templateName } = importInfo.importInfo;
1003
- const importInfos = [importInfo];
1004
987
  const children = [];
1005
988
  const extraProps = [];
1006
989
  if (slots) {
@@ -1010,6 +993,7 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1010
993
  const slotItems = slots[slotName];
1011
994
  const slotItemsUsages = await Promise.all(
1012
995
  slotItems.filter((slotItem) => {
996
+ if (!slotItem) return false;
1013
997
  if (slotItem.type !== "text") {
1014
998
  if (!slotItem.patternId) return false;
1015
999
  if (!slotItem.templateId) return false;
@@ -1025,31 +1009,39 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1025
1009
  }
1026
1010
  return slotItem.text;
1027
1011
  }
1028
- const slotPattern = patternManifest.getPattern(
1029
- slotItem.patternId
1030
- );
1031
- const slotTemplate = slotPattern.templates.find(
1032
- (t) => t.id === slotItem.templateId
1033
- );
1034
1012
  if (slotItem.type === "template-reference") {
1035
- const { usage: usage2, imports } = await this.getUsageAndImports({
1036
- pattern: slotPattern,
1037
- template: slotTemplate,
1038
- patternManifest
1013
+ const slottedTemplate = state.patterns[slotItem.patternId]?.templates.find((t) => t.id === slotItem.templateId);
1014
+ if (!slottedTemplate) {
1015
+ throw new Error(
1016
+ `Could not find slotted template: ${slotItem.patternId} ${slotItem.templateId}`
1017
+ );
1018
+ }
1019
+ const templateRefImport = await this.addUniqueValueToImportMap({
1020
+ importMap,
1021
+ path: slottedTemplate.path,
1022
+ alias: slottedTemplate.alias || "default"
1039
1023
  });
1040
- importInfos.push(...imports);
1041
- return usage2;
1024
+ return templateRefImport.name;
1042
1025
  }
1043
1026
  if (slotItem.type === "template-demo") {
1044
- const { usage: usage2, imports } = await this.getUsageAndImports({
1045
- pattern: slotPattern,
1046
- template: slotTemplate,
1047
- demo: slotItem.demo || this.patterns.demosById[slotItem.demoId],
1048
- patternManifest
1027
+ const thisDemo = slotItem.demo;
1028
+ if (!thisDemo) {
1029
+ throw new Error(
1030
+ `Could not find slotted template demo ${JSON.stringify(
1031
+ slotItem
1032
+ )}`
1033
+ );
1034
+ }
1035
+ const { usage: usage2 } = await this.getUsageAndImports({
1036
+ patternId: thisDemo.patternId,
1037
+ templateId: thisDemo.templateId,
1038
+ demo: thisDemo,
1039
+ state,
1040
+ importMap
1049
1041
  });
1050
- importInfos.push(...imports);
1051
1042
  return usage2;
1052
1043
  }
1044
+ const _exhaustiveCheck2 = slotItem;
1053
1045
  throw new Error(
1054
1046
  `Unknown slot item: ${JSON.stringify(slotItem)}`
1055
1047
  );
@@ -1108,50 +1100,25 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1108
1100
  });
1109
1101
  return {
1110
1102
  usage,
1111
- imports: importInfos
1103
+ importMap
1112
1104
  };
1113
1105
  }
1114
- if (demo?.type && demo.type === "template") {
1115
- const importInfo = this.getJsImport({
1116
- patternId: pattern.id,
1117
- templateId: template.id,
1118
- demoId: demo.id
1106
+ if (demo.type === "template") {
1107
+ const { templateInfo } = demo;
1108
+ const { name: templateName } = await this.addUniqueValueToImportMap({
1109
+ importMap,
1110
+ path: templateInfo.path,
1111
+ alias: templateInfo.alias || "default"
1119
1112
  });
1120
- if (!importInfo) {
1121
- throw new Error(
1122
- `Could not find import for pattern-template-demo: ${pattern.id}-${template.id}-${demo.id}`
1123
- );
1124
- }
1125
- const { type, name: templateName } = importInfo.importInfo;
1126
1113
  const usage = await getUsage({ templateName });
1127
1114
  return {
1128
1115
  usage,
1129
- imports: [importInfo]
1130
- };
1131
- }
1132
- if (!demo) {
1133
- const importInfo = this.getJsImport({
1134
- patternId: pattern.id,
1135
- templateId: template.id
1136
- });
1137
- if (!importInfo) {
1138
- throw new Error(
1139
- `Could not find import for pattern-template: ${pattern.id}-${template.id}`
1140
- );
1141
- }
1142
- const { type, name: templateName } = importInfo.importInfo;
1143
- return {
1144
- /**
1145
- * 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`
1146
- * @see {KsSlotInfo['isTemplateReference']}
1147
- * @see {SlottedTemplate}
1148
- */
1149
- usage: templateName,
1150
- imports: [importInfo]
1116
+ importMap
1151
1117
  };
1152
1118
  }
1119
+ const _exhaustiveCheck = demo;
1153
1120
  throw new Error(
1154
- `Unhandled demo type for ${pattern.id}-${template.id}: ${JSON.stringify(
1121
+ `Unhandled demo type for ${patternId}-${templateId}: ${JSON.stringify(
1155
1122
  demo
1156
1123
  )}`
1157
1124
  );
@@ -1174,8 +1141,8 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1174
1141
  }
1175
1142
  return spec;
1176
1143
  }, "inferSpec");
1177
- watch = /* @__PURE__ */ __name(async (opt) => {
1178
- super.watch(opt);
1144
+ watch = /* @__PURE__ */ __name(async () => {
1145
+ super.watch();
1179
1146
  import_app2.knapsackEvents.onPatternTemplateChanged(() => {
1180
1147
  clearInferSpecCache();
1181
1148
  });
@@ -1253,21 +1220,34 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1253
1220
  ];
1254
1221
  }, "alterTemplateMetaFiles");
1255
1222
  getTemplateSuggestions = /* @__PURE__ */ __name(async ({
1256
- newPath
1223
+ newPath,
1224
+ state
1257
1225
  }) => {
1258
- const { data: dataDir } = this.patterns.userConfig;
1259
- const { allTemplateDemos, allTemplates } = this.getMyTemplates();
1260
- const usedSuggestions = [
1261
- ...allTemplateDemos,
1262
- ...allTemplates
1263
- ].map(({ path: path2, alias }) => {
1264
- return {
1265
- path: path2,
1266
- alias: alias || "default"
1267
- };
1268
- });
1226
+ const usedSuggestions = Object.values(state.patterns).reduce(
1227
+ (acc, { templateDemos, templates }) => {
1228
+ templates.forEach(({ path: path2, alias, templateLanguageId }) => {
1229
+ if (templateLanguageId !== this.id) return;
1230
+ acc.push({ path: path2, alias });
1231
+ });
1232
+ templateDemos.forEach(
1233
+ ({ templateInfo: { path: path2, alias }, templateLanguageId }) => {
1234
+ if (templateLanguageId !== this.id) return;
1235
+ acc.push({ path: path2, alias });
1236
+ }
1237
+ );
1238
+ return acc;
1239
+ },
1240
+ []
1241
+ );
1242
+ const codeSrcs = new Set(this.getCodeSrcs());
1243
+ codeSrcs.delete(this.demoWrapperPath);
1244
+ codeSrcs.delete(errorCatcherPath);
1269
1245
  const allPaths = [
1270
- .../* @__PURE__ */ new Set([newPath, ...usedSuggestions.map(({ path: path2 }) => path2)])
1246
+ .../* @__PURE__ */ new Set([
1247
+ newPath,
1248
+ ...Object.keys(this.pkgPathAliases || {}),
1249
+ ...codeSrcs
1250
+ ])
1271
1251
  ];
1272
1252
  const allSuggestions = await Promise.all(
1273
1253
  allPaths.map(async (path2) => {
@@ -1275,7 +1255,7 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1275
1255
  try {
1276
1256
  const { exports: exports2, errorMsg } = await (0, import_file_utils3.getJsExportNames)({
1277
1257
  path: path2,
1278
- resolveFromDir: dataDir,
1258
+ resolveFromDir: this.dataDir,
1279
1259
  pkgPathAliases: this.pkgPathAliases
1280
1260
  });
1281
1261
  if (errorMsg) {