@knapsack/renderer-react 4.70.0--canary.4433.133de0f.0 → 4.70.0--canary.4854.b1d79a8.0

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js CHANGED
@@ -39,6 +39,7 @@ var import_sleep_promise = __toESM(require("sleep-promise"));
39
39
  var import_renderer_webpack_base = require("@knapsack/renderer-webpack-base");
40
40
  var import_utils3 = require("@knapsack/utils");
41
41
  var import_app2 = require("@knapsack/app");
42
+ var import_renderers = require("@knapsack/app/renderers");
42
43
  var import_types2 = require("@knapsack/types");
43
44
  var import_file_utils3 = require("@knapsack/file-utils");
44
45
  var import_path2 = require("path");
@@ -63,13 +64,14 @@ function renderUsageTemplate({
63
64
  `;
64
65
  }
65
66
  __name(renderUsageTemplate, "renderUsageTemplate");
67
+ var demoAppName = "DemoApp";
66
68
  function renderDemoAppTemplate({
67
- imports,
69
+ imports = "",
68
70
  children
69
71
  }) {
70
72
  return `${imports}
71
73
 
72
- function DemoApp() {
74
+ function ${demoAppName}() {
73
75
  return (
74
76
  ${children}
75
77
  )
@@ -128,12 +130,14 @@ async function getUsage(data) {
128
130
  __name(getUsage, "getUsage");
129
131
  async function getDemoAppUsage({
130
132
  children,
131
- imports
133
+ imports,
134
+ format
132
135
  }) {
133
136
  const code = renderDemoAppTemplate({
134
137
  children,
135
138
  imports
136
139
  });
140
+ if (!format) return code;
137
141
  return (0, import_file_utils.formatCode)({
138
142
  contents: code,
139
143
  path: "x.tsx"
@@ -717,11 +721,13 @@ var createReactPattern = (0, import_creator_utils.createCreator)({
717
721
  }, "getTasks")
718
722
  });
719
723
 
724
+ // src/types.ts
725
+ var rendererMetaScriptTagId = "ks-react-meta";
726
+
720
727
  // src/renderer-react.ts
721
728
  var { pkg } = (0, import_file_utils3.findUpPkgJson)(__dirname);
722
729
  import_app2.log.setupUpdateNotifier({ ...pkg, name: pkg.name, version: pkg.version });
723
- var { createSlotOptionsHtmlTags } = import_app2.KnapsackRendererBase;
724
- var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer_webpack_base.KnapsackRendererWebpackBase {
730
+ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer_webpack_base.RendererWebpackBase {
725
731
  static {
726
732
  __name(this, "KnapsackReactRenderer");
727
733
  }
@@ -730,7 +736,6 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
730
736
  */
731
737
  assets;
732
738
  babelConfig;
733
- creators;
734
739
  demoWrapperPath;
735
740
  disableReactStrictMode;
736
741
  constructor({
@@ -743,7 +748,11 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
743
748
  id,
744
749
  extension: ".jsx",
745
750
  language: "jsx",
746
- webpackConfig
751
+ webpackConfig,
752
+ extraScripts: [
753
+ // this is the code in `./client/init.mts`
754
+ "@knapsack/renderer-react/client"
755
+ ]
747
756
  });
748
757
  this.language = "jsx";
749
758
  this.assets = [];
@@ -751,7 +760,7 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
751
760
  this.disableReactStrictMode = disableReactStrictMode;
752
761
  this.creators = [createReactPattern];
753
762
  }
754
- async init(opt) {
763
+ init = /* @__PURE__ */ __name(async (opt) => {
755
764
  await super.init(opt);
756
765
  this.assets = await copyReactAssets(this.outputDir, this.publicPath);
757
766
  if (!await (0, import_file_utils3.exists)(this.demoWrapperPath)) {
@@ -759,7 +768,7 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
759
768
  `Could not find demo wrapper at: "${this.demoWrapperPath}"`
760
769
  );
761
770
  }
762
- }
771
+ }, "init");
763
772
  getMeta = /* @__PURE__ */ __name(() => ({
764
773
  id: this.id,
765
774
  title: "React",
@@ -789,18 +798,16 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
789
798
  }
790
799
  }
791
800
  }), "getMeta");
792
- changeCase(str) {
793
- return (0, import_utils3.pascalCase)(str);
794
- }
795
- createWebpackConfig() {
801
+ changeCase = /* @__PURE__ */ __name((str) => (0, import_utils3.pascalCase)(str), "changeCase");
802
+ createWebpackConfig = /* @__PURE__ */ __name(() => {
796
803
  const config = super.createWebpackConfig();
797
804
  config.externals = {
798
805
  react: "React",
799
806
  "react-dom": "ReactDOM"
800
807
  };
801
808
  return config;
802
- }
803
- getJsImports() {
809
+ }, "createWebpackConfig");
810
+ getJsImports = /* @__PURE__ */ __name(() => {
804
811
  const imports = super.getJsImports();
805
812
  imports.push(
806
813
  {
@@ -821,174 +828,89 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
821
828
  }
822
829
  );
823
830
  return imports;
824
- }
831
+ }, "getJsImports");
825
832
  async prepClientRenderResults({
826
833
  usage,
827
834
  demoApp,
828
835
  imports: xImports,
829
836
  renderOptions: { pattern, template, demo }
830
837
  }) {
831
- const extraImportNames = this.getJsImports().flatMap(
832
- (imp) => imp.type === "extra" ? [imp.importInfo.name] : []
838
+ const extraImports = this.getJsImports().filter(
839
+ (imp) => imp.type === "extra"
833
840
  );
834
- const { imports, isDeclaredVarsUnique, nameCollisions } = this.makeKsJsImportsUnique({ imports: xImports });
841
+ const { imports, isDeclaredVarsUnique, nameCollisions } = this.makeKsJsImportsUnique({ imports: [...xImports, ...extraImports] });
835
842
  if (!isDeclaredVarsUnique) {
836
843
  import_app2.log.error(`${nameCollisions.join(", ")} are declared multiple times`, {
837
844
  imports
838
845
  });
839
846
  }
840
- const importNames = [
841
- ...imports.map(({ importInfo: { name } }) => name),
842
- ...extraImportNames
843
- ];
844
- const patternsUsed = imports.flatMap((imp) => {
845
- if (imp.type === "pattern-template") {
846
- return [
847
- {
848
- patternId: imp.patternId,
849
- templateId: imp.templateId
847
+ const importInfos = imports.map(({ importInfo }) => importInfo);
848
+ const meta = {
849
+ demo,
850
+ moduleImports: (0, import_utils3.groupBy)(importInfos, (importInfo) => importInfo.path),
851
+ patternId: pattern.id,
852
+ templateId: template.id,
853
+ imports,
854
+ disableReactStrictMode: this.disableReactStrictMode,
855
+ demoWrapperProps: {
856
+ pattern,
857
+ template,
858
+ demo,
859
+ patternsUsed: imports.flatMap((imp) => {
860
+ if (imp.type === "pattern-template") {
861
+ return [
862
+ {
863
+ patternId: imp.patternId,
864
+ templateId: imp.templateId
865
+ }
866
+ ];
850
867
  }
851
- ];
852
- }
853
- if (imp.type === "pattern-template-demo") {
854
- return [
855
- {
856
- patternId: imp.patternId,
857
- templateId: imp.templateId,
858
- demoId: imp.demoId
868
+ if (imp.type === "pattern-template-demo") {
869
+ return [
870
+ {
871
+ patternId: imp.patternId,
872
+ templateId: imp.templateId,
873
+ demoId: imp.demoId
874
+ }
875
+ ];
859
876
  }
860
- ];
877
+ return [];
878
+ })
861
879
  }
862
- return [];
863
- });
864
- const demoWrapperProps = {
865
- patternsUsed,
866
- pattern,
867
- template,
868
- demo
869
880
  };
870
- const demoWrapperCode = await getUsage({
871
- templateName: "DemoWrapper",
872
- props: demoWrapperProps,
873
- children: `<DemoApp />`
874
- // extraProps,
875
- });
876
- async function renderReact({
877
- patterns,
878
- theExtraImportNames,
879
- ksGlobal
880
- }) {
881
- if (!ksGlobal) {
882
- throw new Error('"window.knapsack" is null');
883
- }
884
- const components = await ksGlobal.getAllImports({
885
- patterns,
886
- extras: theExtraImportNames.map((name) => ({ name }))
887
- });
888
- return components;
889
- }
890
- __name(renderReact, "renderReact");
891
881
  let code = `
892
-
893
- ${renderReact.toString()}
894
- ${renderReact.name}({
895
- ksGlobal: window.knapsack,
896
- patterns: ${JSON.stringify(patternsUsed)},
897
- theExtraImportNames: ${JSON.stringify(extraImportNames)},
898
- }).then((components) => {
899
- const { ${importNames.join(", ")} } = components;
900
- const root = document.getElementById('render-root');
901
-
902
- ${demoApp}
903
-
904
- const reactDomVersion = parseInt(ReactDOM.version.split('.')[0], 10);
905
-
906
- const ReactRendererResult = () => {
907
- if (reactDomVersion < 17 || ${this.disableReactStrictMode}){
908
- return (
909
- <ErrorCatcher>
910
- ${demoWrapperCode}
911
- </ErrorCatcher>
912
- )
882
+ window.knapsack = window.knapsack || {};
883
+ window.knapsack.getDemoApp = ({ ${imports.map((i) => i.importInfo.name).join(", ")} }) => {
884
+ ${demoApp}
885
+ return ${demoAppName}
913
886
  }
914
-
915
- return (
916
- <React.StrictMode>
917
- <ErrorCatcher>
918
- ${demoWrapperCode}
919
- </ErrorCatcher>
920
- </React.StrictMode>
921
- )
922
- };
923
-
924
-
925
- if (reactDomVersion > 17){
926
- ReactDOM.createRoot(root).render(
927
- <ReactRendererResult />
928
- )
929
- } else {
930
- ReactDOM.render(
931
- <ReactRendererResult />,
932
- root
933
- );
934
- }
935
- }).catch((err) => {
936
- console.error(err);
937
- const root = document.getElementById('render-root');
938
- // Create a new <div> element to contain the error message
939
- const errorMsgDiv = document.createElement('div');
940
- // Insert the new <div> element before the existing element
941
- root.parentNode.insertBefore(errorMsgDiv, root);
942
- // add error message so users can see it
943
- errorMsgDiv.innerHTML = '<h1>Component Error</h1><p>' + err.message + '</p>';
944
- });
945
887
  `;
946
- let codeHadError = false;
947
888
  let errorHtmlMsg = "";
948
889
  try {
949
- code = await this.babelCodeForBrowser({
950
- code
951
- });
890
+ code = await (0, import_renderers.babelCodeForBrowser)({ code });
952
891
  } catch (e) {
953
- codeHadError = true;
954
892
  console.log(code);
955
893
  console.log("---original code before babel error ^---");
956
894
  console.trace(e.message);
957
895
  code = `console.error(${JSON.stringify(e.message)});`;
958
896
  errorHtmlMsg = `<pre><code>${e.message}</code></pre>`;
959
897
  }
960
- if (!codeHadError) {
961
- try {
962
- code = await (0, import_file_utils3.formatCode)({
963
- contents: code,
964
- path: "x.tsx"
965
- // doing this to set format language
966
- });
967
- } catch (e) {
968
- codeHadError = true;
969
- console.log(code);
970
- console.log("---original code before prettier error ^---");
971
- console.trace(e.message);
972
- code = `console.error(${JSON.stringify(e.message)});`;
973
- errorHtmlMsg = `<pre><code>${e.message}</code></pre>`;
974
- }
975
- }
976
898
  const html = `
899
+ <script type="application/json" id="${rendererMetaScriptTagId}">${JSON.stringify(
900
+ meta
901
+ )}</script>
902
+ <script type="application/javascript">${code}</script>
903
+ <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
977
904
  ${this.assets.map((asset) => `<script src="${asset}"></script>`).join("\n")}
978
-
979
905
  ${this.createHtmlTagsForAssetPaths({
980
906
  assets: this.getWebpackAssetPaths(),
981
907
  // 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
982
908
  scriptTagsAreAsync: false
983
909
  })}
984
-
985
- <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
986
- <script type="application/javascript">${code}</script>
987
- ${errorHtmlMsg}
988
-
910
+ ${errorHtmlMsg}
989
911
  `;
990
912
  return {
991
- ok: !codeHadError,
913
+ ok: !errorHtmlMsg,
992
914
  html: await (0, import_file_utils3.formatCode)({
993
915
  contents: html,
994
916
  path: "x.html"
@@ -998,18 +920,24 @@ ${errorHtmlMsg}
998
920
  templateLanguage: this.language
999
921
  };
1000
922
  }
1001
- async render(opt) {
1002
- if (_KnapsackReactRenderer.isTemplateDemo(opt.demo)) {
923
+ render = /* @__PURE__ */ __name(async (opt) => {
924
+ if (opt.demo?.type === "template") {
1003
925
  const waits = [5, 10, 20, 50, 100, 1e3, 1e3];
1004
926
  let templateDemoPath;
1005
927
  let attempt = 0;
1006
928
  while (true) {
1007
929
  try {
1008
- templateDemoPath = opt.patternManifest.getTemplateDemoAbsolutePath({
1009
- patternId: opt.pattern.id,
1010
- templateId: opt.template.id,
1011
- demoId: opt.demo.id
930
+ const { absolutePath, exists } = await (0, import_file_utils3.resolvePath)({
931
+ path: opt.demo.templateInfo.path,
932
+ pkgPathAliases: this.pkgPathAliases,
933
+ resolveFromDir: this.dataDir
1012
934
  });
935
+ if (!exists) {
936
+ throw new Error(
937
+ `Template demo file does not exist: ${absolutePath}`
938
+ );
939
+ }
940
+ templateDemoPath = absolutePath;
1013
941
  break;
1014
942
  } catch (e) {
1015
943
  const waitTime = waits[attempt];
@@ -1035,7 +963,7 @@ ${errorHtmlMsg}
1035
963
  });
1036
964
  return results;
1037
965
  }
1038
- if (_KnapsackReactRenderer.isDataDemo(opt.demo)) {
966
+ if (opt.demo?.type === "data") {
1039
967
  const { usage, imports } = await this.getUsageAndImports(opt);
1040
968
  const { code: importCode } = this.createJsImportCodeBlock({
1041
969
  imports
@@ -1043,7 +971,8 @@ ${errorHtmlMsg}
1043
971
  const [demoAppUsage, demoApp] = await Promise.all([
1044
972
  getDemoAppUsage({
1045
973
  children: usage,
1046
- imports: importCode
974
+ imports: importCode,
975
+ format: true
1047
976
  }),
1048
977
  getDemoAppUsage({
1049
978
  children: usage
@@ -1056,10 +985,14 @@ ${errorHtmlMsg}
1056
985
  renderOptions: opt
1057
986
  });
1058
987
  }
1059
- }
1060
- async getUsageAndImports(opt) {
1061
- const { pattern, template, patternManifest, demo } = opt;
1062
- if (demo?.type && _KnapsackReactRenderer.isDataDemo(demo)) {
988
+ }, "render");
989
+ getUsageAndImports = /* @__PURE__ */ __name(async ({
990
+ pattern,
991
+ template,
992
+ patternManifest,
993
+ demo
994
+ }) => {
995
+ if (demo?.type && demo.type === "data") {
1063
996
  const {
1064
997
  data: { props, slots, slotsOptionsComputed }
1065
998
  } = demo;
@@ -1083,16 +1016,16 @@ ${errorHtmlMsg}
1083
1016
  const slotItems = slots[slotName];
1084
1017
  const slotItemsUsages = await Promise.all(
1085
1018
  slotItems.filter((slotItem) => {
1086
- if (!(0, import_types2.isSlottedText)(slotItem)) {
1019
+ if (slotItem.type !== "text") {
1087
1020
  if (!slotItem.patternId) return false;
1088
1021
  if (!slotItem.templateId) return false;
1089
- if ((0, import_types2.isSlottedTemplateDemo)(slotItem) && !slotItem.demoId) {
1022
+ if (slotItem.type === "template-demo" && !slotItem.demoId) {
1090
1023
  return false;
1091
1024
  }
1092
1025
  }
1093
1026
  return true;
1094
1027
  }).map(async (slotItem) => {
1095
- if ((0, import_types2.isSlottedText)(slotItem)) {
1028
+ if (slotItem.type === "text") {
1096
1029
  if (slotItems.length === 1 && slotName !== "children") {
1097
1030
  return `\`${slotItem.text}\``;
1098
1031
  }
@@ -1104,7 +1037,7 @@ ${errorHtmlMsg}
1104
1037
  const slotTemplate = slotPattern.templates.find(
1105
1038
  (t) => t.id === slotItem.templateId
1106
1039
  );
1107
- if ((0, import_types2.isSlottedTemplateReference)(slotItem)) {
1040
+ if (slotItem.type === "template-reference") {
1108
1041
  const { usage: usage2, imports } = await this.getUsageAndImports({
1109
1042
  pattern: slotPattern,
1110
1043
  template: slotTemplate,
@@ -1113,7 +1046,7 @@ ${errorHtmlMsg}
1113
1046
  importInfos.push(...imports);
1114
1047
  return usage2;
1115
1048
  }
1116
- if ((0, import_types2.isSlottedTemplateDemo)(slotItem)) {
1049
+ if (slotItem.type === "template-demo") {
1117
1050
  const { usage: usage2, imports } = await this.getUsageAndImports({
1118
1051
  pattern: slotPattern,
1119
1052
  template: slotTemplate,
@@ -1136,7 +1069,7 @@ ${errorHtmlMsg}
1136
1069
  );
1137
1070
  slotUsages.forEach(({ slotName, slotItemsUsages }) => {
1138
1071
  const slotOptionsComputed = slotsOptionsComputed?.[slotName];
1139
- const { openTag, closeTag } = createSlotOptionsHtmlTags({
1072
+ const { openTag, closeTag } = (0, import_renderers.createSlotOptionsHtmlTags)({
1140
1073
  slotOptionsComputed,
1141
1074
  classAttributeName: "className",
1142
1075
  stylesValueType: "object"
@@ -1184,7 +1117,7 @@ ${errorHtmlMsg}
1184
1117
  imports: importInfos
1185
1118
  };
1186
1119
  }
1187
- if (demo?.type && _KnapsackReactRenderer.isTemplateDemo(demo)) {
1120
+ if (demo?.type && demo.type === "template") {
1188
1121
  const importInfo = this.getJsImport({
1189
1122
  patternId: pattern.id,
1190
1123
  templateId: template.id,
@@ -1228,11 +1161,7 @@ ${errorHtmlMsg}
1228
1161
  demo
1229
1162
  )}`
1230
1163
  );
1231
- }
1232
- async getUsage(opt) {
1233
- const { usage } = await this.getUsageAndImports(opt);
1234
- return usage;
1235
- }
1164
+ }, "getUsageAndImports");
1236
1165
  inferSpec = /* @__PURE__ */ __name(async ({
1237
1166
  template,
1238
1167
  templatePath
@@ -1251,12 +1180,12 @@ ${errorHtmlMsg}
1251
1180
  }
1252
1181
  return spec;
1253
1182
  }, "inferSpec");
1254
- async watch(opt) {
1255
- await super.watch(opt);
1183
+ watch = /* @__PURE__ */ __name(async (opt) => {
1184
+ super.watch(opt);
1256
1185
  import_app2.knapsackEvents.onPatternTemplateChanged(() => {
1257
1186
  clearInferSpecCache();
1258
1187
  });
1259
- }
1188
+ }, "watch");
1260
1189
  getTemplateMeta = /* @__PURE__ */ __name(async ({
1261
1190
  pattern,
1262
1191
  template
@@ -1299,7 +1228,10 @@ ${errorHtmlMsg}
1299
1228
  }
1300
1229
  return files;
1301
1230
  }, "getTemplateMeta");
1302
- alterTemplateMetaFiles = /* @__PURE__ */ __name(async ({ files, metaDir }) => {
1231
+ alterTemplateMetaFiles = /* @__PURE__ */ __name(async ({
1232
+ files,
1233
+ metaDir
1234
+ }) => {
1303
1235
  const imports = [];
1304
1236
  const ext = ".spec.d.ts";
1305
1237
  files.forEach((file) => {
@@ -1326,9 +1258,9 @@ ${errorHtmlMsg}
1326
1258
  }
1327
1259
  ];
1328
1260
  }, "alterTemplateMetaFiles");
1329
- async getTemplateSuggestions({
1261
+ getTemplateSuggestions = /* @__PURE__ */ __name(async ({
1330
1262
  newPath
1331
- }) {
1263
+ }) => {
1332
1264
  const { data: dataDir } = this.patterns.userConfig;
1333
1265
  const { allTemplateDemos, allTemplates } = this.getMyTemplates();
1334
1266
  const usedSuggestions = [
@@ -1379,7 +1311,7 @@ ${errorHtmlMsg}
1379
1311
  return {
1380
1312
  suggestions
1381
1313
  };
1382
- }
1314
+ }, "getTemplateSuggestions");
1383
1315
  };
1384
1316
  // Annotate the CommonJS export names for ESM import in node:
1385
1317
  0 && (module.exports = {