statum-mkpstm.vala 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. using Xml;
  2. using Html;
  3. using Astralis;
  4. using Invercargill;
  5. using Invercargill.DataStructures;
  6. namespace Statum.Tools {
  7. /**
  8. * `statum-mkpstm` — the build-time Statum pre-rendering pipeline.
  9. *
  10. * Turns an app HTML page (plus its templates/fragments) into a Vala
  11. * {@link Statum.StatumPage} subclass: a static, precompressed document whose
  12. * route comes from its `<pstm-uri>`. Composition (templates, fragments,
  13. * `pstm-res` rewriting, legacy statum.js expansion) is applied, then the
  14. * result is precompressed with identity/gzip/zstd/br.
  15. *
  16. * Legacy client references: a `<script pstm-res-src="statum.js">` (the
  17. * pre-split single-file client) expands into the module tags in
  18. * canonical load order, with plain final `src` attributes. Explicit
  19. * module references the expansion covers are subsumed and later
  20. * duplicates dropped, so each module appears exactly once; one build
  21. * warning per page names the page, the expansion and any dedupe. Pages
  22. * referencing only module files (or plain `src` scripts) are untouched
  23. * and unwarned.
  24. */
  25. public class Mkpstm : Object {
  26. private static string? output_file = null;
  27. private static string? namespace_name = null;
  28. private static string? class_name_override = null;
  29. private static string? route_override = null;
  30. private static List<string> template_dirs = new List<string>();
  31. private Dictionary<string, Xml.Doc*> templates_by_name = new Dictionary<string, Xml.Doc*>();
  32. private Dictionary<string, Xml.Doc*> fragments_by_name = new Dictionary<string, Xml.Doc*>();
  33. /**
  34. * The Statum client ships as modules with a strict load order (core
  35. * first: every later module registers into the seams core installs). A
  36. * legacy single-file `pstm-res-src="statum.js"` reference expands at
  37. * build time into exactly these tags. statum-forms.js was folded
  38. * into statum-document.js (core is headless); statum-binding.js
  39. * adds the client-side variable layer.
  40. */
  41. private const string[] CLIENT_MODULE_ORDER = {
  42. "statum-core.js", "statum-document.js", "statum-markdown.js", "statum-binding.js"
  43. };
  44. private const OptionEntry[] options = {
  45. { "output", 'o', 0, OptionArg.FILENAME, ref output_file, "Output Vala file name", "FILE" },
  46. { "ns", '\0', 0, OptionArg.STRING, ref namespace_name, "Namespace for the generated class", "NAMESPACE" },
  47. { "name", 'n', 0, OptionArg.STRING, ref class_name_override, "Generated class name (default: <InputName>Page)", "NAME" },
  48. { "route", 'r', 0, OptionArg.STRING, ref route_override, "Page route (default: from <pstm-uri>)", "ROUTE" },
  49. { "template-dir", 't', 0, OptionArg.FILENAME_ARRAY, ref template_dirs, "Directory to search for templates/fragments (repeatable)", "DIR" },
  50. { null }
  51. };
  52. public static int main(string[] args) {
  53. try {
  54. var opt = new OptionContext("PAGE_FILE - Generate a Statum StatumPage");
  55. opt.add_main_entries(options, null);
  56. opt.parse(ref args);
  57. } catch (OptionError e) {
  58. stderr.printf("Error: %s\n", e.message);
  59. return 1;
  60. }
  61. string? page_file = null;
  62. if (args.length > 1) {
  63. page_file = args[1];
  64. }
  65. if (page_file == null) {
  66. stderr.printf("Error: No page file specified.\n");
  67. return 1;
  68. }
  69. try {
  70. var tool = new Mkpstm();
  71. var generated = tool.run((!)page_file);
  72. var out_path = tool.output_file ?? (make_pascal_case((!)page_file) + "Page.vala");
  73. write_file(out_path, generated);
  74. stdout.printf("Generated: %s\n", out_path);
  75. return 0;
  76. } catch (GLib.Error e) {
  77. stderr.printf("Error: %s\n", e.message);
  78. return 1;
  79. }
  80. }
  81. public string run(string page_file) throws GLib.Error {
  82. if (template_dirs.length() == 0) {
  83. var parent = File.new_for_path(page_file).get_parent();
  84. template_dirs.append(parent != null ? ((!)parent).get_path() : ".");
  85. }
  86. load_templates_and_fragments(page_file);
  87. var doc = parse_html_file(page_file);
  88. validate_document(doc, page_file);
  89. validate_head_directives(doc, page_file);
  90. // Capture the page's routes before composition (the <pstm-uri>
  91. // directive is dropped while merging templates).
  92. var routes = read_routes(doc);
  93. doc = compose_templates(doc);
  94. inline_fragments(doc);
  95. expand_legacy_client(doc, page_file);
  96. rewrite_resources(doc);
  97. var variant = build_variant(doc);
  98. var class_name = class_name_override ?? (make_pascal_case(page_file) + "Page");
  99. var route = route_override ?? (routes.length > 0 ? routes[0] : "");
  100. return emit(class_name, route, variant);
  101. }
  102. // ------------------------------------------------------------------
  103. // Template/fragment loading
  104. // ------------------------------------------------------------------
  105. private void load_templates_and_fragments(string page_file) throws GLib.Error {
  106. foreach (var dir in template_dirs) {
  107. var dir_file = File.new_for_path(dir);
  108. if (!dir_file.query_exists()) {
  109. continue;
  110. }
  111. var enumerator = dir_file.enumerate_children("standard::name", 0);
  112. FileInfo info;
  113. while ((info = enumerator.next_file()) != null) {
  114. var name = info.get_name();
  115. if (!name.has_suffix(".html") || name.has_prefix(".")) {
  116. continue;
  117. }
  118. var path = Path.build_filename(dir, name);
  119. if (path == page_file) {
  120. continue;
  121. }
  122. var tdoc = parse_html_file(path);
  123. var source = Path.build_filename(dir, name);
  124. validate_document(tdoc, source);
  125. validate_head_directives(tdoc, source);
  126. var tname = read_pstm_name(tdoc);
  127. if (tname == null) {
  128. continue;
  129. }
  130. if (find_first_element(tdoc->get_root_element(), "pstm-content") != null) {
  131. templates_by_name.set((!)tname, tdoc);
  132. } else {
  133. fragments_by_name.set((!)tname, tdoc);
  134. }
  135. }
  136. }
  137. }
  138. // ------------------------------------------------------------------
  139. // Composition
  140. // ------------------------------------------------------------------
  141. private Xml.Doc* compose_templates(Xml.Doc* doc) throws GLib.Error {
  142. Xml.Doc* current_doc = doc;
  143. string merged_title = read_directive_in_doc(current_doc, "pstm-title") ?? "";
  144. // Guard against cyclic template chains (A templates B templates A).
  145. var visited = new HashSet<string>();
  146. while (true) {
  147. var parent_name = read_directive_in_doc(current_doc, "pstm-template");
  148. if (parent_name == null || parent_name.length == 0) {
  149. break;
  150. }
  151. if (visited.contains((!)parent_name)) {
  152. break;
  153. }
  154. visited.add((!)parent_name);
  155. Xml.Doc* parent_doc;
  156. if (!templates_by_name.try_get((!)parent_name, out parent_doc)) {
  157. throw new IOError.FAILED(@"Unknown template \"$((!)parent_name)\"");
  158. }
  159. // Merge this document's <head> into the parent's <head> (so
  160. // pages, templates and nested components can all declare head
  161. // tags), then splice its <body> into the parent's content outlet.
  162. merge_head(current_doc, parent_doc);
  163. splice_body(current_doc, parent_doc);
  164. var parent_title = read_directive_in_doc(parent_doc, "pstm-title");
  165. if (parent_title != null && parent_title.length > 0) {
  166. merged_title = merged_title + (!)parent_title;
  167. }
  168. current_doc = parent_doc;
  169. }
  170. apply_title(current_doc, merged_title);
  171. return current_doc;
  172. }
  173. /**
  174. * Copies the children of `child_doc`'s <head> into `parent_doc`'s <head>,
  175. * skipping the consumed structural directives (pstm-template/name/title/
  176. * uri) which are page-level metadata and must not be carried up.
  177. */
  178. private void merge_head(Xml.Doc* child_doc, Xml.Doc* parent_doc) {
  179. var child_head = find_head(child_doc);
  180. var parent_head = find_head(parent_doc);
  181. if (child_head == null || parent_head == null) {
  182. return;
  183. }
  184. for (var child = child_head->children; child != null; child = child->next) {
  185. if (!is_element(child)) {
  186. continue;
  187. }
  188. var name = (string) child->name;
  189. if (name == "pstm-template" || name == "pstm-name" || name == "pstm-title" || name == "pstm-uri") {
  190. continue;
  191. }
  192. var copied = child->doc_copy(parent_doc, 1);
  193. if (copied != null) {
  194. parent_head->add_child(copied);
  195. }
  196. }
  197. }
  198. /**
  199. * Splices `child_doc`'s <body> into `parent_doc`'s <pstm-content> outlet
  200. * (or appends to the parent's <body> when there is no outlet). When the
  201. * child <body> carries `pstm-materialise-as`, it is wrapped in an element
  202. * of that tag (carrying the body's non-pstm attributes); otherwise its
  203. * children are spliced directly.
  204. */
  205. private void splice_body(Xml.Doc* child_doc, Xml.Doc* parent_doc) {
  206. var child_body = find_body(child_doc);
  207. var parent_body = find_body(parent_doc);
  208. if (child_body == null || parent_body == null) {
  209. return;
  210. }
  211. var outlet = find_first_element(parent_body, "pstm-content");
  212. var materialise_as = child_body->get_prop("pstm-materialise-as");
  213. if (materialise_as != null) {
  214. var wrapper = parent_body->new_child(null, (!)materialise_as, null);
  215. wrapper->unlink();
  216. copy_non_pstm_attrs(child_body, wrapper);
  217. for (var child = child_body->children; child != null; child = child->next) {
  218. if (is_structural_directive(child)) {
  219. continue;
  220. }
  221. var copied = child->doc_copy(parent_doc, 1);
  222. if (copied != null) {
  223. wrapper->add_child(copied);
  224. }
  225. }
  226. if (outlet != null) {
  227. outlet->add_prev_sibling(wrapper);
  228. } else {
  229. parent_body->add_child(wrapper);
  230. }
  231. } else {
  232. for (var child = child_body->children; child != null; child = child->next) {
  233. if (is_structural_directive(child)) {
  234. continue;
  235. }
  236. var copied = child->doc_copy(parent_doc, 1);
  237. if (copied == null) {
  238. continue;
  239. }
  240. if (outlet != null) {
  241. outlet->add_prev_sibling(copied);
  242. } else {
  243. parent_body->add_child(copied);
  244. }
  245. }
  246. }
  247. if (outlet != null) {
  248. outlet->unlink();
  249. }
  250. }
  251. /** Copies an element's non-`pstm-*` attributes onto another element. */
  252. private static void copy_non_pstm_attrs(Xml.Node* src, Xml.Node* dst) {
  253. for (var attr = src->properties; attr != null; attr = attr->next) {
  254. var attr_name = (string) attr->name;
  255. if (attr_name.has_prefix("pstm-")) {
  256. continue;
  257. }
  258. var value = src->get_prop(attr_name);
  259. if (value != null) {
  260. dst->set_prop(attr_name, (!)value);
  261. }
  262. }
  263. }
  264. private static string? read_directive_in_doc(Xml.Doc* doc, string name) {
  265. var root = doc->get_root_element();
  266. if (root == null) {
  267. return null;
  268. }
  269. return read_directive_text(root, name);
  270. }
  271. private static bool is_structural_directive(Xml.Node* node) {
  272. if (!is_element(node)) {
  273. return false;
  274. }
  275. var name = (string) node->name;
  276. return name == "pstm-template" || name == "pstm-name" || name == "pstm-title" || name == "pstm-uri" || name == "pstm-content";
  277. }
  278. /** Fragment-body metadata elements skipped when inlining (e.g. pstm-input). */
  279. private static bool is_fragment_metadata(Xml.Node* node) {
  280. if (!is_element(node)) {
  281. return false;
  282. }
  283. var name = (string) node->name;
  284. return name == "pstm-input" || name.has_prefix("pstm-");
  285. }
  286. private void inline_fragments(Xml.Doc* doc) {
  287. bool changed = true;
  288. while (changed) {
  289. changed = false;
  290. var includes = find_all_elements(doc, "pstm-fragment");
  291. foreach (var include in includes) {
  292. if (inline_one_fragment(doc, include)) {
  293. changed = true;
  294. }
  295. }
  296. }
  297. }
  298. private bool inline_one_fragment(Xml.Doc* doc, Xml.Node* include) {
  299. var name = include->get_prop("name");
  300. if (name == null) {
  301. return false;
  302. }
  303. Xml.Doc* fragment_doc;
  304. if (!fragments_by_name.try_get((!)name, out fragment_doc)) {
  305. return false;
  306. }
  307. var fragment_body = find_body(fragment_doc);
  308. if (fragment_body == null) {
  309. return false;
  310. }
  311. // Merge the fragment's <head> into the document's <head>.
  312. merge_head(fragment_doc, doc);
  313. var inputs = collect_input_names(fragment_body);
  314. var include_materialise = include->get_prop("pstm-materialise-as");
  315. var fragment_materialise = fragment_body->get_prop("pstm-materialise-as");
  316. var materialise_as = include_materialise ?? fragment_materialise;
  317. bool wrap = (materialise_as != null) || inputs.length > 0;
  318. string tag = materialise_as ?? "div";
  319. if (wrap) {
  320. var parent = include->parent;
  321. if (parent == null) {
  322. return false;
  323. }
  324. var wrapper = parent->new_child(null, tag, null);
  325. wrapper->unlink();
  326. include->add_prev_sibling(wrapper);
  327. // Carry the fragment <body>'s attributes when it supplied the tag.
  328. if (include_materialise == null && fragment_materialise != null) {
  329. copy_non_pstm_attrs(fragment_body, wrapper);
  330. }
  331. for (var child = fragment_body->children; child != null; child = child->next) {
  332. if (is_fragment_metadata(child)) {
  333. continue;
  334. }
  335. var copied = child->doc_copy(doc, 1);
  336. if (copied != null) {
  337. wrapper->add_child(copied);
  338. }
  339. }
  340. foreach (var input_name in inputs) {
  341. var expr = include->get_prop(input_name);
  342. if (expr != null) {
  343. wrapper->set_prop(@"stm-local-$input_name", (!)expr);
  344. }
  345. }
  346. } else {
  347. for (var child = fragment_body->children; child != null; child = child->next) {
  348. if (is_fragment_metadata(child)) {
  349. continue;
  350. }
  351. var copied = child->doc_copy(doc, 1);
  352. if (copied != null) {
  353. include->add_prev_sibling(copied);
  354. }
  355. }
  356. }
  357. include->unlink();
  358. return true;
  359. }
  360. private string[] collect_input_names(Xml.Node* fragment_body) {
  361. var names = new string[0];
  362. for (var n = fragment_body->children; n != null; n = n->next) {
  363. if (is_element(n) && (string) n->name == "pstm-input") {
  364. var input_name = n->get_prop("name");
  365. if (input_name != null) {
  366. names += (!)input_name;
  367. }
  368. }
  369. }
  370. return names;
  371. }
  372. private void rewrite_resources(Xml.Doc* doc) {
  373. var root = doc->get_root_element();
  374. if (root != null) {
  375. rewrite_resources_in(root);
  376. }
  377. }
  378. /**
  379. * Expands a legacy single-file client reference into the four ordered
  380. * module tags.
  381. *
  382. * `<script pstm-res-src="statum.js">` (the pre-split client, no longer
  383. * an embedded resource) becomes one `<script src="/_statum/resource/
  384. * statum-<mod>.js">` tag per module, in canonical load order. Later
  385. * duplicate `statum.js` references on the same page are dropped, and
  386. * explicit `pstm-res-src="statum-<mod>.js"` references the expansion
  387. * already covers are removed (subsumed) so every module appears exactly
  388. * once. Pages referencing only module files (or only plain `src="…"`
  389. * scripts, which are already final) are left entirely alone.
  390. *
  391. * Runs on the composed document before {@link rewrite_resources}: the
  392. * inserted tags use plain `src` attributes, so the generic rewrite and
  393. * `strip_pstm` both leave them alone.
  394. */
  395. private void expand_legacy_client(Xml.Doc* doc, string page_file) {
  396. var root = doc->get_root_element();
  397. if (root == null) {
  398. return;
  399. }
  400. Xml.Node* legacy = null;
  401. var refs = new ClientRefs();
  402. collect_client_refs(root, refs);
  403. legacy = refs.legacy;
  404. if (legacy == null) {
  405. return;
  406. }
  407. var parent = legacy->parent;
  408. if (parent == null) {
  409. return;
  410. }
  411. foreach (var module in CLIENT_MODULE_ORDER) {
  412. var tag = ((!)parent)->new_child(null, "script", null);
  413. tag->unlink();
  414. // Script tags carrying pstm-res-src carry no other attributes
  415. // today; copy any extras onto all four for good measure.
  416. copy_non_pstm_attrs(legacy, tag);
  417. tag->set_prop("src", @"/_statum/resource/$module");
  418. legacy->add_prev_sibling(tag);
  419. }
  420. string[] subsumed = new string[0];
  421. foreach (var node in refs.modules) {
  422. var name = node->get_prop("pstm-res-src");
  423. if (name != null) {
  424. subsumed += (!)name;
  425. }
  426. node->unlink();
  427. }
  428. foreach (var node in refs.duplicates) {
  429. node->unlink();
  430. }
  431. legacy->unlink();
  432. // Exactly one build warning per page, naming the page and the
  433. // expansion.
  434. var page = page_name(page_file);
  435. stderr.printf("warning: %s: expanding legacy pstm-res-src=\"statum.js\" into %s",
  436. page, string.joinv(", ", CLIENT_MODULE_ORDER));
  437. if (subsumed.length > 0) {
  438. stderr.printf("; subsumed explicit module tag(s): %s", string.joinv(", ", subsumed));
  439. }
  440. if (refs.duplicates.length > 0) {
  441. stderr.printf("; dropped %d duplicate statum.js reference(s)", refs.duplicates.length);
  442. }
  443. stderr.printf("\n");
  444. }
  445. /**
  446. * Collects the client script references of a composed document: the
  447. * first `<script pstm-res-src="statum.js">` (if any), every explicit
  448. * module `pstm-res-src="statum-<mod>.js"` reference, and the count of
  449. * further `statum.js` duplicates.
  450. */
  451. private void collect_client_refs(Xml.Node* node, ClientRefs refs) {
  452. if (!is_element(node)) {
  453. return;
  454. }
  455. if ((string) node->name == "script") {
  456. var res = node->get_prop("pstm-res-src");
  457. if (res != null) {
  458. if ((!)res == "statum.js") {
  459. if (refs.legacy == null) {
  460. refs.legacy = node;
  461. } else {
  462. refs.duplicates += node;
  463. }
  464. } else if (is_client_module((!)res)) {
  465. refs.modules += node;
  466. }
  467. }
  468. }
  469. for (var child = node->children; child != null; child = child->next) {
  470. collect_client_refs(child, refs);
  471. }
  472. }
  473. /** The page's short name, as warnings name it (e.g. `home`). */
  474. private static string page_name(string page_file) {
  475. var page = Path.get_basename(page_file);
  476. var dot = page.last_index_of(".");
  477. if (dot > 0) {
  478. page = page.substring(0, dot);
  479. }
  480. return page;
  481. }
  482. private static bool is_client_module(string name) {
  483. foreach (var module in CLIENT_MODULE_ORDER) {
  484. if (name == module) {
  485. return true;
  486. }
  487. }
  488. return false;
  489. }
  490. private void rewrite_resources_in(Xml.Node* node) {
  491. if (!is_element(node)) {
  492. return;
  493. }
  494. string[] to_add_attr = new string[0];
  495. string[] to_add_val = new string[0];
  496. string[] to_remove = new string[0];
  497. for (var attr = node->properties; attr != null; attr = attr->next) {
  498. var attr_name = (string) attr->name;
  499. if (attr_name.has_prefix("pstm-res-")) {
  500. var target_attr = attr_name.substring("pstm-res-".length);
  501. var value = node->get_prop(attr_name);
  502. if (value != null) {
  503. to_add_attr += target_attr;
  504. to_add_val += @"/_statum/resource/$((!)value)";
  505. }
  506. to_remove += attr_name;
  507. }
  508. }
  509. for (int i = 0; i < to_add_attr.length; i++) {
  510. node->set_prop(to_add_attr[i], to_add_val[i]);
  511. }
  512. foreach (var attr_name in to_remove) {
  513. node->unset_prop(attr_name);
  514. }
  515. for (var child = node->children; child != null; child = child->next) {
  516. rewrite_resources_in(child);
  517. }
  518. }
  519. // ------------------------------------------------------------------
  520. // Variant rendering
  521. // ------------------------------------------------------------------
  522. /**
  523. * Renders the composed document to its single HTML form (stripping every
  524. * `pstm-*` directive) and precompresses it. Pages no longer have
  525. * variants: a page is a static, precompressed document, so there is
  526. * exactly one.
  527. */
  528. private VariantData build_variant(Xml.Doc* doc) throws GLib.Error {
  529. strip_pstm(doc);
  530. var html = serialize(doc);
  531. return compress_variant(html);
  532. }
  533. private VariantData compress_variant(string html) throws GLib.Error {
  534. var data = new VariantData();
  535. data.identity = html.data;
  536. var buffer = new ByteBuffer.from_byte_array(html.data);
  537. var gzip = new GzipCompressor(9).compress_buffer(buffer, null).to_array();
  538. var zstd = new ZstdCompressor(19).compress_buffer(buffer, null).to_array();
  539. var br = new BrotliCompressor(11).compress_buffer(buffer, null).to_array();
  540. data.has_gzip = gzip.length < html.length;
  541. data.has_zstd = zstd.length < html.length;
  542. data.has_br = br.length < html.length;
  543. data.gzip = data.has_gzip ? gzip : null;
  544. data.zstd = data.has_zstd ? zstd : null;
  545. data.br = data.has_br ? br : null;
  546. return data;
  547. }
  548. /** Remove every `pstm-*` attribute and `pstm-*` element from the tree. */
  549. private void strip_pstm(Xml.Doc* doc) {
  550. var root = doc->get_root_element();
  551. if (root != null) {
  552. strip_pstm_from(root);
  553. }
  554. }
  555. private void strip_pstm_from(Xml.Node* node) {
  556. string[] to_remove = new string[0];
  557. for (var attr = node->properties; attr != null; attr = attr->next) {
  558. var attr_name = (string) attr->name;
  559. if (attr_name.has_prefix("pstm-")) {
  560. to_remove += attr_name;
  561. }
  562. }
  563. foreach (var attr_name in to_remove) {
  564. node->unset_prop(attr_name);
  565. }
  566. var child = node->children;
  567. while (child != null) {
  568. var next = child->next;
  569. if (is_element(child) && ((string) child->name).has_prefix("pstm-")) {
  570. child->unlink();
  571. } else if (is_element(child)) {
  572. strip_pstm_from(child);
  573. }
  574. child = next;
  575. }
  576. }
  577. // ------------------------------------------------------------------
  578. // Code generation
  579. // ------------------------------------------------------------------
  580. private string emit(string class_name, string route, VariantData variant) throws GLib.Error {
  581. var page_hash = compute_hash(variant.identity);
  582. var b = new StringBuilder();
  583. string i1 = namespace_name != null ? " " : "";
  584. string i2 = namespace_name != null ? " " : " ";
  585. string i3 = namespace_name != null ? " " : " ";
  586. b.append("using Statum;\n");
  587. b.append("using Invercargill;\n");
  588. b.append("using Invercargill.DataStructures;\n");
  589. b.append("using Astralis;\n\n");
  590. if (namespace_name != null) {
  591. b.append_printf("namespace %s {\n\n", namespace_name);
  592. }
  593. b.append_printf("%s// Generated by statum-mkpstm\n", i1);
  594. b.append_printf("%spublic class %s : StatumPage {\n\n", i1, class_name);
  595. b.append_printf("%spublic override string route { get { return \"%s\"; } }\n", i2, escape(route));
  596. b.append_printf("%spublic override string content_type { get { return \"text/html; charset=utf-8\"; } }\n\n", i2);
  597. // get_best_encoding: smallest available supported encoding.
  598. b.append_printf("%spublic override string get_best_encoding(Set<string> supported) {\n", i2);
  599. if (variant.has_br) {
  600. b.append_printf("%sif (supported.has(\"br\")) return \"br\";\n", i3);
  601. }
  602. if (variant.has_zstd) {
  603. b.append_printf("%sif (supported.has(\"zstd\")) return \"zstd\";\n", i3);
  604. }
  605. if (variant.has_gzip) {
  606. b.append_printf("%sif (supported.has(\"gzip\")) return \"gzip\";\n", i3);
  607. }
  608. b.append_printf("%sreturn \"identity\";\n", i3);
  609. b.append_printf("%s}\n\n", i2);
  610. // get_encoding
  611. b.append_printf("%spublic override unowned uint8[] get_encoding(string encoding) {\n", i2);
  612. b.append_printf("%sswitch (encoding) {\n", i3);
  613. b.append_printf("%scase \"identity\": return IDENTITY;\n", i3);
  614. if (variant.has_gzip && variant.gzip != null) {
  615. b.append_printf("%scase \"gzip\": return GZIP;\n", i3);
  616. }
  617. if (variant.has_zstd && variant.zstd != null) {
  618. b.append_printf("%scase \"zstd\": return ZSTD;\n", i3);
  619. }
  620. if (variant.has_br && variant.br != null) {
  621. b.append_printf("%scase \"br\": return BR;\n", i3);
  622. }
  623. b.append_printf("%sdefault: return IDENTITY;\n", i3);
  624. b.append_printf("%s}\n", i3);
  625. b.append_printf("%s}\n\n", i2);
  626. // get_etag_for (ETag = "<page-hash>-<encoding>")
  627. b.append_printf("%spublic override string get_etag_for(string encoding) {\n", i2);
  628. b.append_printf("%sreturn \"\\\"%s-%%s\\\"\".printf(encoding);\n", i3, page_hash);
  629. b.append_printf("%s}\n\n", i2);
  630. // Byte arrays.
  631. emit_one_array(b, i2, i3, "IDENTITY", variant.identity);
  632. if (variant.has_gzip && variant.gzip != null) {
  633. emit_one_array(b, i2, i3, "GZIP", (!)variant.gzip);
  634. }
  635. if (variant.has_zstd && variant.zstd != null) {
  636. emit_one_array(b, i2, i3, "ZSTD", (!)variant.zstd);
  637. }
  638. if (variant.has_br && variant.br != null) {
  639. emit_one_array(b, i2, i3, "BR", (!)variant.br);
  640. }
  641. b.append_printf("%s}\n", i1);
  642. if (namespace_name != null) {
  643. b.append("}\n");
  644. }
  645. return b.str;
  646. }
  647. private void emit_one_array(StringBuilder b, string i2, string i3, string name, uint8[] data) {
  648. b.append_printf("%sprivate const uint8[] %s = {\n", i2, name);
  649. for (int i = 0; i < data.length; i++) {
  650. if (i == 0) {
  651. b.append(i3);
  652. } else if (i % 16 == 0) {
  653. b.append(",\n").append(i3);
  654. } else {
  655. b.append(", ");
  656. }
  657. b.append_printf("0x%02x", data[i]);
  658. }
  659. b.append_printf("\n%s};\n\n", i2);
  660. }
  661. // ------------------------------------------------------------------
  662. // DOM helpers
  663. // ------------------------------------------------------------------
  664. private Xml.Doc* parse_html_file(string path) throws GLib.Error {
  665. var file = File.new_for_path(path);
  666. if (!file.query_exists()) {
  667. throw new IOError.NOT_FOUND(@"Page file '$path' does not exist");
  668. }
  669. uint8[] contents;
  670. string etag_out;
  671. file.load_contents(null, out contents, out etag_out);
  672. // Parse with libxml2's HTML parser (mirrors Astralis' MarkupDocument)
  673. // so the tree has HTML semantics and serializes as HTML, not XML.
  674. int opts = (int)(Html.ParserOption.RECOVER |
  675. Html.ParserOption.NOERROR |
  676. Html.ParserOption.NOWARNING |
  677. Html.ParserOption.NOBLANKS |
  678. Html.ParserOption.NONET);
  679. char[] buffer = ((string) contents).to_utf8();
  680. var doc = Html.Doc.read_memory(buffer, buffer.length, path, "utf-8", opts);
  681. if (doc == null) {
  682. throw new IOError.FAILED(@"Failed to parse HTML file '$path'");
  683. }
  684. return doc;
  685. }
  686. private static Xml.Node* find_body(Xml.Doc* doc) {
  687. var root = doc->get_root_element();
  688. if (root == null) {
  689. return null;
  690. }
  691. return find_first_element(root, "body");
  692. }
  693. private static Xml.Node* find_head(Xml.Doc* doc) {
  694. var root = doc->get_root_element();
  695. if (root == null) {
  696. return null;
  697. }
  698. return find_first_element(root, "head");
  699. }
  700. /**
  701. * Validates that `doc` has both a <head> and a <body> element, which every
  702. * Statum HTML input (pages, templates and fragments) must declare.
  703. */
  704. private void validate_document(Xml.Doc* doc, string source) throws GLib.Error {
  705. if (find_head(doc) == null) {
  706. throw new IOError.FAILED(@"\"$source\" has no <head> element (a <head> and <body> are required)");
  707. }
  708. if (find_body(doc) == null) {
  709. throw new IOError.FAILED(@"\"$source\" has no <body> element (a <head> and <body> are required)");
  710. }
  711. }
  712. /**
  713. * Validates that the structural directives <pstm-title>, <pstm-template>
  714. * and <pstm-name> appear only inside <head>.
  715. */
  716. private void validate_head_directives(Xml.Doc* doc, string source) throws GLib.Error {
  717. var root = doc->get_root_element();
  718. if (root == null) {
  719. return;
  720. }
  721. string[] names = { "pstm-title", "pstm-template", "pstm-name", "pstm-uri" };
  722. foreach (var name in names) {
  723. var nodes = new Series<Xml.Node*>();
  724. find_all_from(root, name, nodes);
  725. foreach (var node in nodes) {
  726. if (!is_descendant_of_head(node)) {
  727. throw new IOError.FAILED(@"\"$source\": <$name> must appear inside <head>");
  728. }
  729. }
  730. }
  731. }
  732. /** Walks the ancestor chain to determine whether `node` is within <head>. */
  733. private static bool is_descendant_of_head(Xml.Node* node) {
  734. for (var p = node->parent; p != null; p = p->parent) {
  735. if (is_element(p) && ((string) p->name).down() == "head") {
  736. return true;
  737. }
  738. }
  739. return false;
  740. }
  741. private static Xml.Node* find_first_element(Xml.Node* root, string name) {
  742. if (!is_element(root)) {
  743. return null;
  744. }
  745. if (((string) root->name).down() == name.down()) {
  746. return root;
  747. }
  748. for (var child = root->children; child != null; child = child->next) {
  749. var found = find_first_element(child, name);
  750. if (found != null) {
  751. return found;
  752. }
  753. }
  754. return null;
  755. }
  756. private static Xml.Node*[] find_all_elements(Xml.Doc* doc, string name) {
  757. var collected = new Series<Xml.Node*>();
  758. var root = doc->get_root_element();
  759. if (root != null) {
  760. find_all_from(root, name, collected);
  761. }
  762. return collected.to_array();
  763. }
  764. private static void find_all_from(Xml.Node* node, string name, Series<Xml.Node*> result) {
  765. if (is_element(node) && ((string) node->name).down() == name.down()) {
  766. result.add(node);
  767. }
  768. if (is_element(node)) {
  769. for (var child = node->children; child != null; child = child->next) {
  770. find_all_from(child, name, result);
  771. }
  772. }
  773. }
  774. private static string? read_directive_text(Xml.Node* body, string directive) {
  775. var node = find_first_element(body, directive);
  776. if (node == null) {
  777. return null;
  778. }
  779. var text = element_text(node);
  780. return text.strip().length > 0 ? text.strip() : null;
  781. }
  782. private static string? read_pstm_name(Xml.Doc* doc) {
  783. var node = find_first_element(doc->get_root_element(), "pstm-name");
  784. if (node == null) {
  785. return null;
  786. }
  787. return element_text(node).strip();
  788. }
  789. private static string[] read_routes(Xml.Doc* doc) {
  790. string[] routes = new string[0];
  791. var nodes = find_all_elements(doc, "pstm-uri");
  792. foreach (var node in nodes) {
  793. var text = element_text(node).strip();
  794. if (text.length > 0) {
  795. routes += text;
  796. }
  797. }
  798. return routes;
  799. }
  800. private static string element_text(Xml.Node* node) {
  801. var b = new StringBuilder();
  802. for (var child = node->children; child != null; child = child->next) {
  803. if (child->type == ElementType.TEXT_NODE && child->content != null) {
  804. b.append((string) child->content);
  805. } else if (is_element(child)) {
  806. b.append(element_text(child));
  807. }
  808. }
  809. return b.str;
  810. }
  811. private static void apply_title(Xml.Doc* doc, string? title) {
  812. if (title == null || title.length == 0) {
  813. return;
  814. }
  815. var head = find_first_element(doc->get_root_element(), "head");
  816. if (head == null) {
  817. return;
  818. }
  819. var title_node = find_first_element(head, "title");
  820. if (title_node == null) {
  821. title_node = head->new_child(null, "title", null);
  822. }
  823. for (var child = title_node->children; child != null; child = child->next) {
  824. child->unlink();
  825. }
  826. title_node->add_content(title);
  827. }
  828. private static string serialize(Xml.Doc* doc) {
  829. // Serialize with libxml2's HTML serializer (htmlDocDumpMemory) so the
  830. // output is valid HTML: no <?xml?> prolog, no self-closing
  831. // `<script/>`, and correct void/non-void element handling. The doc was
  832. // produced by the HTML parser, so it carries HTML structure.
  833. string mem;
  834. int len;
  835. ((Html.Doc*) doc)->dump_memory(out mem, out len);
  836. return len > 0 ? mem.substring(0, len) : mem;
  837. }
  838. private static bool is_element(Xml.Node* node) {
  839. return node != null && node->type == ElementType.ELEMENT_NODE;
  840. }
  841. private static string compute_hash(uint8[] data) {
  842. var checksum = new Checksum(ChecksumType.SHA512);
  843. checksum.update(data, data.length);
  844. return checksum.get_string();
  845. }
  846. private static string escape(string s) {
  847. return s.replace("\\", "\\\\").replace("\"", "\\\"");
  848. }
  849. private static void write_file(string path, string contents) throws GLib.Error {
  850. var file = File.new_for_path(path);
  851. var stream = new DataOutputStream(file.replace(null, false, FileCreateFlags.NONE));
  852. stream.put_string(contents);
  853. stream.close();
  854. }
  855. private static string make_pascal_case(string input) {
  856. var basename = Path.get_basename(input);
  857. var dot = basename.last_index_of(".");
  858. if (dot > 0) {
  859. basename = basename.substring(0, dot);
  860. }
  861. var result = new StringBuilder();
  862. var capitalize_next = true;
  863. foreach (var c in basename.data) {
  864. if (c == '-' || c == '_' || c == ' ' || c == '.') {
  865. capitalize_next = true;
  866. } else {
  867. if (capitalize_next) {
  868. result.append_printf("%c", c >= 'a' && c <= 'z' ? c - 32 : c);
  869. capitalize_next = false;
  870. } else {
  871. result.append_printf("%c", c);
  872. }
  873. }
  874. }
  875. return result.str;
  876. }
  877. // ------------------------------------------------------------------
  878. // Model
  879. // ------------------------------------------------------------------
  880. /** Scratch state for {@link collect_client_refs}. */
  881. private class ClientRefs : Object {
  882. public Xml.Node* legacy = null;
  883. public Xml.Node*[] modules = new Xml.Node*[0];
  884. public Xml.Node*[] duplicates = new Xml.Node*[0];
  885. }
  886. private class VariantData : Object {
  887. public uint8[] identity;
  888. public uint8[]? gzip;
  889. public uint8[]? zstd;
  890. public uint8[]? br;
  891. public bool has_gzip;
  892. public bool has_zstd;
  893. public bool has_br;
  894. }
  895. }
  896. }