@knapsack/renderer-react 4.70.0--canary.4433.133de0f.0 → 4.70.0--canary.4513.12c8d13.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,85 @@ 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 meta = {
848
+ demo,
849
+ disableReactStrictMode: this.disableReactStrictMode,
850
+ neededImports: imports,
851
+ 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
+ ];
850
863
  }
851
- ];
852
- }
853
- if (imp.type === "pattern-template-demo") {
854
- return [
855
- {
856
- patternId: imp.patternId,
857
- templateId: imp.templateId,
858
- demoId: imp.demoId
864
+ if (imp.type === "pattern-template-demo") {
865
+ return [
866
+ {
867
+ patternId: imp.patternId,
868
+ templateId: imp.templateId,
869
+ demoId: imp.demoId
870
+ }
871
+ ];
859
872
  }
860
- ];
873
+ return [];
874
+ })
861
875
  }
862
- return [];
863
- });
864
- const demoWrapperProps = {
865
- patternsUsed,
866
- pattern,
867
- template,
868
- demo
869
876
  };
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
877
  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
- )
878
+ window.knapsack = window.knapsack || {};
879
+ window.knapsack.getDemoApp = ({ ${imports.map((i) => i.importInfo.name).join(", ")} }) => {
880
+ ${demoApp}
881
+ return ${demoAppName}
913
882
  }
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
883
  `;
946
- let codeHadError = false;
947
884
  let errorHtmlMsg = "";
948
885
  try {
949
- code = await this.babelCodeForBrowser({
950
- code
951
- });
886
+ code = await (0, import_renderers.babelCodeForBrowser)({ code });
952
887
  } catch (e) {
953
- codeHadError = true;
954
888
  console.log(code);
955
889
  console.log("---original code before babel error ^---");
956
890
  console.trace(e.message);
957
891
  code = `console.error(${JSON.stringify(e.message)});`;
958
892
  errorHtmlMsg = `<pre><code>${e.message}</code></pre>`;
959
893
  }
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
894
  const html = `
895
+ <script type="application/json" id="${rendererMetaScriptTagId}">${JSON.stringify(
896
+ meta
897
+ )}</script>
898
+ <script type="application/javascript">${code}</script>
899
+ <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
977
900
  ${this.assets.map((asset) => `<script src="${asset}"></script>`).join("\n")}
978
-
979
901
  ${this.createHtmlTagsForAssetPaths({
980
902
  assets: this.getWebpackAssetPaths(),
981
903
  // 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
904
  scriptTagsAreAsync: false
983
905
  })}
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
-
906
+ ${errorHtmlMsg}
989
907
  `;
990
908
  return {
991
- ok: !codeHadError,
909
+ ok: !errorHtmlMsg,
992
910
  html: await (0, import_file_utils3.formatCode)({
993
911
  contents: html,
994
912
  path: "x.html"
@@ -998,18 +916,22 @@ ${errorHtmlMsg}
998
916
  templateLanguage: this.language
999
917
  };
1000
918
  }
1001
- async render(opt) {
1002
- if (_KnapsackReactRenderer.isTemplateDemo(opt.demo)) {
919
+ render = /* @__PURE__ */ __name(async (opt) => {
920
+ if (opt.demo?.type === "template") {
1003
921
  const waits = [5, 10, 20, 50, 100, 1e3, 1e3];
1004
922
  let templateDemoPath;
1005
923
  let attempt = 0;
1006
924
  while (true) {
1007
925
  try {
1008
- templateDemoPath = opt.patternManifest.getTemplateDemoAbsolutePath({
1009
- patternId: opt.pattern.id,
1010
- templateId: opt.template.id,
1011
- demoId: opt.demo.id
1012
- });
926
+ const { absolutePath, exists } = await this.resolvePath(
927
+ opt.demo.templateInfo.path
928
+ );
929
+ if (!exists) {
930
+ throw new Error(
931
+ `Template demo file does not exist: ${absolutePath}`
932
+ );
933
+ }
934
+ templateDemoPath = absolutePath;
1013
935
  break;
1014
936
  } catch (e) {
1015
937
  const waitTime = waits[attempt];
@@ -1035,7 +957,7 @@ ${errorHtmlMsg}
1035
957
  });
1036
958
  return results;
1037
959
  }
1038
- if (_KnapsackReactRenderer.isDataDemo(opt.demo)) {
960
+ if (opt.demo?.type === "data") {
1039
961
  const { usage, imports } = await this.getUsageAndImports(opt);
1040
962
  const { code: importCode } = this.createJsImportCodeBlock({
1041
963
  imports
@@ -1043,7 +965,8 @@ ${errorHtmlMsg}
1043
965
  const [demoAppUsage, demoApp] = await Promise.all([
1044
966
  getDemoAppUsage({
1045
967
  children: usage,
1046
- imports: importCode
968
+ imports: importCode,
969
+ format: true
1047
970
  }),
1048
971
  getDemoAppUsage({
1049
972
  children: usage
@@ -1056,10 +979,14 @@ ${errorHtmlMsg}
1056
979
  renderOptions: opt
1057
980
  });
1058
981
  }
1059
- }
1060
- async getUsageAndImports(opt) {
1061
- const { pattern, template, patternManifest, demo } = opt;
1062
- if (demo?.type && _KnapsackReactRenderer.isDataDemo(demo)) {
982
+ }, "render");
983
+ getUsageAndImports = /* @__PURE__ */ __name(async ({
984
+ pattern,
985
+ template,
986
+ patternManifest,
987
+ demo
988
+ }) => {
989
+ if (demo?.type && demo.type === "data") {
1063
990
  const {
1064
991
  data: { props, slots, slotsOptionsComputed }
1065
992
  } = demo;
@@ -1083,16 +1010,16 @@ ${errorHtmlMsg}
1083
1010
  const slotItems = slots[slotName];
1084
1011
  const slotItemsUsages = await Promise.all(
1085
1012
  slotItems.filter((slotItem) => {
1086
- if (!(0, import_types2.isSlottedText)(slotItem)) {
1013
+ if (slotItem.type !== "text") {
1087
1014
  if (!slotItem.patternId) return false;
1088
1015
  if (!slotItem.templateId) return false;
1089
- if ((0, import_types2.isSlottedTemplateDemo)(slotItem) && !slotItem.demoId) {
1016
+ if (slotItem.type === "template-demo" && !slotItem.demoId) {
1090
1017
  return false;
1091
1018
  }
1092
1019
  }
1093
1020
  return true;
1094
1021
  }).map(async (slotItem) => {
1095
- if ((0, import_types2.isSlottedText)(slotItem)) {
1022
+ if (slotItem.type === "text") {
1096
1023
  if (slotItems.length === 1 && slotName !== "children") {
1097
1024
  return `\`${slotItem.text}\``;
1098
1025
  }
@@ -1104,7 +1031,7 @@ ${errorHtmlMsg}
1104
1031
  const slotTemplate = slotPattern.templates.find(
1105
1032
  (t) => t.id === slotItem.templateId
1106
1033
  );
1107
- if ((0, import_types2.isSlottedTemplateReference)(slotItem)) {
1034
+ if (slotItem.type === "template-reference") {
1108
1035
  const { usage: usage2, imports } = await this.getUsageAndImports({
1109
1036
  pattern: slotPattern,
1110
1037
  template: slotTemplate,
@@ -1113,7 +1040,7 @@ ${errorHtmlMsg}
1113
1040
  importInfos.push(...imports);
1114
1041
  return usage2;
1115
1042
  }
1116
- if ((0, import_types2.isSlottedTemplateDemo)(slotItem)) {
1043
+ if (slotItem.type === "template-demo") {
1117
1044
  const { usage: usage2, imports } = await this.getUsageAndImports({
1118
1045
  pattern: slotPattern,
1119
1046
  template: slotTemplate,
@@ -1136,7 +1063,7 @@ ${errorHtmlMsg}
1136
1063
  );
1137
1064
  slotUsages.forEach(({ slotName, slotItemsUsages }) => {
1138
1065
  const slotOptionsComputed = slotsOptionsComputed?.[slotName];
1139
- const { openTag, closeTag } = createSlotOptionsHtmlTags({
1066
+ const { openTag, closeTag } = (0, import_renderers.createSlotOptionsHtmlTags)({
1140
1067
  slotOptionsComputed,
1141
1068
  classAttributeName: "className",
1142
1069
  stylesValueType: "object"
@@ -1184,7 +1111,7 @@ ${errorHtmlMsg}
1184
1111
  imports: importInfos
1185
1112
  };
1186
1113
  }
1187
- if (demo?.type && _KnapsackReactRenderer.isTemplateDemo(demo)) {
1114
+ if (demo?.type && demo.type === "template") {
1188
1115
  const importInfo = this.getJsImport({
1189
1116
  patternId: pattern.id,
1190
1117
  templateId: template.id,
@@ -1228,11 +1155,7 @@ ${errorHtmlMsg}
1228
1155
  demo
1229
1156
  )}`
1230
1157
  );
1231
- }
1232
- async getUsage(opt) {
1233
- const { usage } = await this.getUsageAndImports(opt);
1234
- return usage;
1235
- }
1158
+ }, "getUsageAndImports");
1236
1159
  inferSpec = /* @__PURE__ */ __name(async ({
1237
1160
  template,
1238
1161
  templatePath
@@ -1251,12 +1174,12 @@ ${errorHtmlMsg}
1251
1174
  }
1252
1175
  return spec;
1253
1176
  }, "inferSpec");
1254
- async watch(opt) {
1255
- await super.watch(opt);
1177
+ watch = /* @__PURE__ */ __name(async (opt) => {
1178
+ super.watch(opt);
1256
1179
  import_app2.knapsackEvents.onPatternTemplateChanged(() => {
1257
1180
  clearInferSpecCache();
1258
1181
  });
1259
- }
1182
+ }, "watch");
1260
1183
  getTemplateMeta = /* @__PURE__ */ __name(async ({
1261
1184
  pattern,
1262
1185
  template
@@ -1299,7 +1222,10 @@ ${errorHtmlMsg}
1299
1222
  }
1300
1223
  return files;
1301
1224
  }, "getTemplateMeta");
1302
- alterTemplateMetaFiles = /* @__PURE__ */ __name(async ({ files, metaDir }) => {
1225
+ alterTemplateMetaFiles = /* @__PURE__ */ __name(async ({
1226
+ files,
1227
+ metaDir
1228
+ }) => {
1303
1229
  const imports = [];
1304
1230
  const ext = ".spec.d.ts";
1305
1231
  files.forEach((file) => {
@@ -1326,9 +1252,9 @@ ${errorHtmlMsg}
1326
1252
  }
1327
1253
  ];
1328
1254
  }, "alterTemplateMetaFiles");
1329
- async getTemplateSuggestions({
1255
+ getTemplateSuggestions = /* @__PURE__ */ __name(async ({
1330
1256
  newPath
1331
- }) {
1257
+ }) => {
1332
1258
  const { data: dataDir } = this.patterns.userConfig;
1333
1259
  const { allTemplateDemos, allTemplates } = this.getMyTemplates();
1334
1260
  const usedSuggestions = [
@@ -1379,7 +1305,7 @@ ${errorHtmlMsg}
1379
1305
  return {
1380
1306
  suggestions
1381
1307
  };
1382
- }
1308
+ }, "getTemplateSuggestions");
1383
1309
  };
1384
1310
  // Annotate the CommonJS export names for ESM import in node:
1385
1311
  0 && (module.exports = {