@analogjs/router 3.0.0-alpha.92 → 3.0.0-alpha.93

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/fesm2022/analogjs-router-i18n.mjs +4 -0
  2. package/fesm2022/analogjs-router-i18n.mjs.map +1 -1
  3. package/fesm2022/analogjs-router-server-actions.mjs +416 -2
  4. package/fesm2022/analogjs-router-server-actions.mjs.map +1 -0
  5. package/fesm2022/analogjs-router-server.mjs +294 -63
  6. package/fesm2022/analogjs-router-server.mjs.map +1 -1
  7. package/fesm2022/analogjs-router-tanstack-query-server.mjs +4 -4
  8. package/fesm2022/analogjs-router-tanstack-query-server.mjs.map +1 -1
  9. package/fesm2022/analogjs-router-tanstack-query.mjs +70 -2
  10. package/fesm2022/analogjs-router-tanstack-query.mjs.map +1 -1
  11. package/fesm2022/analogjs-router-tokens.mjs.map +1 -1
  12. package/fesm2022/analogjs-router.mjs +144 -78
  13. package/fesm2022/analogjs-router.mjs.map +1 -1
  14. package/fesm2022/debug.page.mjs +3 -3
  15. package/fesm2022/route-files.mjs +1 -1
  16. package/package.json +4 -4
  17. package/types/server/actions/src/define-action.d.ts +8 -15
  18. package/types/server/actions/src/define-api-route.d.ts +2 -3
  19. package/types/server/actions/src/define-page-load.d.ts +8 -9
  20. package/types/server/actions/src/define-server-route.d.ts +1 -1
  21. package/types/server/actions/src/index.d.ts +3 -2
  22. package/types/server/actions/src/parse-request-data.d.ts +3 -4
  23. package/types/server/actions/src/standard-schema.d.ts +39 -0
  24. package/types/server/actions/src/validate.d.ts +1 -1
  25. package/types/server/src/defer-reconcile-runtime.d.ts +1 -1
  26. package/types/server/src/ssr-navigation.d.ts +6 -0
  27. package/types/server/src/utils/ssr-stream-lifecycle.d.ts +14 -0
  28. package/types/server/src/utils/stream-shell.d.ts +3 -0
  29. package/types/src/index.d.ts +2 -4
  30. package/types/src/lib/form-action.directive.d.ts +11 -9
  31. package/types/src/lib/server-fn/inject-server-fn.d.ts +1 -1
  32. package/types/tanstack-query/server/src/define-page-load-queries.d.ts +4 -6
  33. package/types/tanstack-query/server/src/index.d.ts +1 -1
  34. package/types/tanstack-query/server/src/provide-server-analog-query.d.ts +2 -0
  35. package/types/tanstack-query/src/index.d.ts +3 -2
  36. package/types/tanstack-query/src/server-query.d.ts +1 -1
  37. package/types/tokens/src/index.d.ts +8 -0
  38. package/fesm2022/provide-analog-query.mjs +0 -72
  39. package/fesm2022/provide-analog-query.mjs.map +0 -1
  40. package/fesm2022/src.mjs +0 -334
  41. package/fesm2022/src.mjs.map +0 -1
@@ -1,12 +1,13 @@
1
1
  import { BASE_URL as BASE_URL$1, INTERNAL_FETCH, LOCALE as LOCALE$1, REQUEST as REQUEST$1, RESPONSE as RESPONSE$1 } from "./analogjs-router-tokens.mjs";
2
- import { InjectionToken, Injector, enableProdMode, runInInjectionContext } from "@angular/core";
2
+ import { NavigationEnd, NavigationError, Router } from "@angular/router";
3
+ import { DestroyRef, ENVIRONMENT_INITIALIZER, InjectionToken, Injector, enableProdMode, inject, makeEnvironmentProviders, runInInjectionContext } from "@angular/core";
3
4
  import { HttpErrorResponse } from "@angular/common/http";
4
5
  import { bootstrapApplication, createApplication } from "@angular/platform-browser";
5
6
  import { BASE_URL, LOCALE, REQUEST, RESPONSE } from "@analogjs/router/tokens";
6
- import { eventHandler, getRouterParam, readBody } from "h3";
7
- import { INITIAL_CONFIG, platformServer, provideServerRendering, renderApplication, ɵSERVER_CONTEXT, ɵrenderInternal } from "@angular/platform-server";
7
+ import { INITIAL_CONFIG, PlatformState, platformServer, provideServerRendering, renderApplication, ɵSERVER_CONTEXT, ɵrenderInternal } from "@angular/platform-server";
8
8
  import { SERVER_FN_DISPATCHER, createServerFnRef } from "@analogjs/router";
9
9
  import { AsyncLocalStorage } from "node:async_hooks";
10
+ import { eventHandler, getRouterParam, readBody } from "h3";
10
11
  //#region packages/router/server/src/server-fn/registry.ts
11
12
  /**
12
13
  * Server-side registry of server functions, keyed by id. A `.server.ts` module
@@ -395,6 +396,7 @@ function parseAcceptLanguage(header) {
395
396
  * prevents registration on the server.
396
397
  */
397
398
  function resetComponentDefTViews() {
399
+ if (typeof ANALOG_I18N_FIXED_LOCALE !== "undefined" && ANALOG_I18N_FIXED_LOCALE) return;
398
400
  const defs = globalThis.__ngComponentDefs;
399
401
  if (!defs) return;
400
402
  for (const def of defs) def.tView = null;
@@ -453,6 +455,34 @@ function headInner(html) {
453
455
  return html.slice(start, end > -1 ? end : start);
454
456
  }
455
457
  //#endregion
458
+ //#region packages/router/server/src/utils/stream-shell.ts
459
+ /** Preload bootstrap modules, but leave execution to the authoritative tail. */
460
+ function createStreamShell(platform) {
461
+ const document = platform.injector.get(PlatformState).getDocument().cloneNode(true);
462
+ for (const script of Array.from(document.head.querySelectorAll("script[type=\"module\"]"))) {
463
+ const src = script.getAttribute("src");
464
+ if (src) {
465
+ const preload = document.createElement("link");
466
+ preload.setAttribute("rel", "modulepreload");
467
+ preload.setAttribute("href", src);
468
+ for (const name of [
469
+ "crossorigin",
470
+ "integrity",
471
+ "referrerpolicy",
472
+ "nonce",
473
+ "fetchpriority"
474
+ ]) {
475
+ const value = script.getAttribute(name);
476
+ if (value !== null) preload.setAttribute(name, value);
477
+ }
478
+ script.parentNode.replaceChild(preload, script);
479
+ } else script.parentNode.removeChild(script);
480
+ }
481
+ while (document.body.firstChild) document.body.removeChild(document.body.firstChild);
482
+ const html = runInInjectionContext(platform.injector, () => new PlatformState(document).renderToString());
483
+ return html.slice(0, html.lastIndexOf("</body>"));
484
+ }
485
+ //#endregion
456
486
  //#region packages/router/server/src/utils/stream-request.ts
457
487
  /**
458
488
  * Per-request decisions about whether the streaming renderer should fall back
@@ -481,6 +511,7 @@ function isLikelyBot(serverContext) {
481
511
  * response, the header is forwarded on the request instead.
482
512
  */
483
513
  function streamingDisabledByRoute(serverContext) {
514
+ if (serverContext?.streaming !== void 0) return !serverContext.streaming;
484
515
  return serverContext?.res?.getHeader?.("x-analog-no-streaming") === "true" || serverContext?.req?.headers?.["x-analog-no-streaming"] === "true";
485
516
  }
486
517
  //#endregion
@@ -509,9 +540,48 @@ function streamingDisabledByRoute(serverContext) {
509
540
  */
510
541
  var DEFER_RECONCILE_RUNTIME = `
511
542
  (function () {
543
+ var completed = false;
544
+ var headModules = [];
545
+ function activateModule(source) {
546
+ var script = document.createElement('script');
547
+ Array.from(source.attributes).forEach(function (attr) {
548
+ script.setAttribute(attr.name, attr.value);
549
+ });
550
+ if (source.hasAttribute('nonce')) script.nonce = source.nonce;
551
+ if (!source.hasAttribute('async')) script.async = false;
552
+ script.textContent = source.textContent;
553
+ return script;
554
+ }
512
555
  function region() {
513
556
  return document.querySelector('[data-analog-stream]');
514
557
  }
558
+ function showError() {
559
+ document.title = 'Unable to load this page';
560
+ var robots = document.head.querySelector('meta[name="robots"]');
561
+ if (!robots) {
562
+ robots = document.createElement('meta');
563
+ robots.setAttribute('name', 'robots');
564
+ document.head.appendChild(robots);
565
+ }
566
+ robots.setAttribute('content', 'noindex');
567
+ var error = document.createElement('main');
568
+ error.setAttribute('data-analog-render-error', '');
569
+ error.setAttribute('role', 'alert');
570
+ var heading = document.createElement('h1');
571
+ heading.textContent = 'Unable to load this page';
572
+ var message = document.createElement('p');
573
+ message.textContent = 'The page could not finish loading.';
574
+ error.appendChild(heading);
575
+ error.appendChild(message);
576
+ document.body.replaceChildren(error);
577
+ }
578
+ function checkCompletion() {
579
+ if (!completed && region()) showError();
580
+ }
581
+ window.__analogFail = showError;
582
+ // A Worker HTTP adapter can turn a stream error into ordinary EOF. The
583
+ // authoritative tail, rather than transport completion, proves SSR success.
584
+ document.addEventListener('DOMContentLoaded', checkCompletion, { once: true });
515
585
  window.__analogPaint = function (id) {
516
586
  var tpl = document.querySelector('template[data-analog-defer="' + id + '"]');
517
587
  var r = region();
@@ -530,6 +600,9 @@ var DEFER_RECONCILE_RUNTIME = `
530
600
  if (!tpl) return;
531
601
  var frag = tpl.content;
532
602
  var head = document.head;
603
+ frag.querySelectorAll('script[type="module"]').forEach(function (script) {
604
+ headModules.push(script.cloneNode(true));
605
+ });
533
606
  var title = frag.querySelector('title');
534
607
  if (title) document.title = title.textContent || '';
535
608
  function metaKey(m) {
@@ -568,14 +641,154 @@ var DEFER_RECONCILE_RUNTIME = `
568
641
  window.__analogFinalize = function () {
569
642
  var auth = document.querySelector('template[data-analog-authoritative]');
570
643
  if (!auth) return;
644
+ completed = true;
645
+ document.removeEventListener('DOMContentLoaded', checkCompletion);
571
646
  // Replace the entire body — preview region, block templates and runtime
572
647
  // scripts — with just the authoritative body, so the reconciled DOM matches
573
648
  // a buffered render byte-for-byte before hydration boots.
574
- document.body.replaceChildren(auth.content.cloneNode(true));
649
+ var body = auth.content.cloneNode(true);
650
+ var bodyModules = Array.from(body.querySelectorAll('script[type="module"]'));
651
+ document.body.replaceChildren(body);
652
+ headModules.forEach(function (script) {
653
+ document.head.appendChild(activateModule(script));
654
+ });
655
+ headModules = [];
656
+ bodyModules.forEach(function (script) {
657
+ script.replaceWith(activateModule(script));
658
+ });
575
659
  };
576
660
  })();
577
661
  `;
578
662
  //#endregion
663
+ //#region packages/router/server/src/utils/ssr-stream-lifecycle.ts
664
+ function createSsrStream(options) {
665
+ const encoder = new TextEncoder();
666
+ const pending = /* @__PURE__ */ new Map();
667
+ let state = "rendering";
668
+ let capturing = true;
669
+ let cleanup;
670
+ let controller;
671
+ let keepAlive;
672
+ let complete;
673
+ const completed = new Promise((resolve) => {
674
+ complete = resolve;
675
+ });
676
+ function destroy() {
677
+ capturing = false;
678
+ clearInterval(keepAlive);
679
+ options.signal?.removeEventListener("abort", abort);
680
+ for (const [timer, task] of pending) {
681
+ clearTimeout(timer);
682
+ task.resolve();
683
+ }
684
+ pending.clear();
685
+ return cleanup ??= Promise.resolve().then(options.destroy).finally(complete);
686
+ }
687
+ function fail(error, aborted = false) {
688
+ if (state !== "rendering" && state !== "closing") return;
689
+ const documentComplete = state === "closing";
690
+ state = "failed";
691
+ if (options.errorHtml && !aborted) {
692
+ console.error("[analog ssr]", error);
693
+ if (!documentComplete) controller.enqueue(encoder.encode(options.errorHtml));
694
+ controller.close();
695
+ } else controller.error(error);
696
+ destroy().catch(() => void 0);
697
+ }
698
+ function abort() {
699
+ fail(options.signal?.reason ?? new DOMException("The render was aborted.", "AbortError"), true);
700
+ }
701
+ const writer = {
702
+ get active() {
703
+ return state === "rendering";
704
+ },
705
+ enqueue(html) {
706
+ if (state === "rendering") controller.enqueue(encoder.encode(html));
707
+ },
708
+ scheduleBlock(serialize) {
709
+ if (state !== "rendering" || !capturing) return;
710
+ let resolve;
711
+ const promise = new Promise((finish) => {
712
+ resolve = finish;
713
+ });
714
+ const timer = setTimeout(() => {
715
+ try {
716
+ if (state === "rendering") writer.enqueue(serialize());
717
+ } catch (error) {
718
+ fail(error);
719
+ } finally {
720
+ pending.delete(timer);
721
+ resolve();
722
+ }
723
+ }, 0);
724
+ pending.set(timer, {
725
+ promise,
726
+ resolve
727
+ });
728
+ },
729
+ async finishBlocks() {
730
+ capturing = false;
731
+ await Promise.all([...pending.values()].map((task) => task.promise));
732
+ }
733
+ };
734
+ return new ReadableStream({
735
+ start(streamController) {
736
+ controller = streamController;
737
+ if (options.waitUntil) {
738
+ options.waitUntil(completed);
739
+ keepAlive = setInterval(() => writer.enqueue("<!--analog-render-pending-->"), 1e3);
740
+ }
741
+ options.signal?.addEventListener("abort", abort, { once: true });
742
+ if (options.signal?.aborted) abort();
743
+ (async () => {
744
+ try {
745
+ if (state === "rendering") await options.render(writer);
746
+ if (state === "rendering") {
747
+ state = "closing";
748
+ await destroy();
749
+ if (state === "closing") {
750
+ state = "closed";
751
+ controller.close();
752
+ }
753
+ }
754
+ } catch (error) {
755
+ fail(error);
756
+ } finally {
757
+ await destroy();
758
+ }
759
+ })().catch(fail);
760
+ },
761
+ cancel() {
762
+ state = "cancelled";
763
+ return destroy();
764
+ }
765
+ });
766
+ }
767
+ //#endregion
768
+ //#region packages/router/server/src/ssr-navigation.ts
769
+ /** Angular can settle initial navigation after an error without rejecting renderApplication. */
770
+ function createSsrNavigationTracker() {
771
+ let failure;
772
+ return {
773
+ provider: makeEnvironmentProviders([{
774
+ provide: ENVIRONMENT_INITIALIZER,
775
+ multi: true,
776
+ useValue() {
777
+ const router = inject(Router, { optional: true });
778
+ if (!router) return;
779
+ const subscription = router.events.subscribe((event) => {
780
+ if (event instanceof NavigationError) failure = event;
781
+ else if (event instanceof NavigationEnd) failure = void 0;
782
+ });
783
+ inject(DestroyRef).onDestroy(() => subscription.unsubscribe());
784
+ }
785
+ }]),
786
+ throwIfFailed() {
787
+ if (failure) throw failure.error;
788
+ }
789
+ };
790
+ }
791
+ //#endregion
579
792
  //#region packages/router/server/src/render-stream.ts
580
793
  /**
581
794
  * Progressive streaming SSR renderer — EXPERIMENTAL.
@@ -618,12 +831,23 @@ function streamingPrimitiveAvailable() {
618
831
  * no-op.
619
832
  */
620
833
  var captureStore = new AsyncLocalStorage();
834
+ var CAPTURE_ZONE_KEY = "analogSsrDeferCapture";
835
+ function currentCaptureZone() {
836
+ return globalThis.Zone?.current;
837
+ }
838
+ function runWithCapture(handler, render) {
839
+ const zone = currentCaptureZone();
840
+ return captureStore.run(handler, () => zone === void 0 ? render() : zone.fork({
841
+ name: "analog-ssr-capture",
842
+ properties: { [CAPTURE_ZONE_KEY]: handler }
843
+ }).run(render));
844
+ }
621
845
  function installCaptureDispatcher() {
622
846
  const g = globalThis;
623
847
  if (g.__analogSsrDeferCapture?.__analogDispatcher) return;
624
- const dispatch = ((ev) => {
625
- captureStore.getStore()?.(ev);
626
- });
848
+ const dispatch = (ev) => {
849
+ (currentCaptureZone()?.get(CAPTURE_ZONE_KEY) ?? captureStore.getStore())?.(ev);
850
+ };
627
851
  dispatch.__analogDispatcher = true;
628
852
  g.__analogSsrDeferCapture = dispatch;
629
853
  }
@@ -639,15 +863,20 @@ function serializeLContainerHtml(lContainer) {
639
863
  const nodes = [];
640
864
  collect(lContainer, nodes);
641
865
  let html = "";
642
- for (const n of nodes) html += n?.outerHTML ?? n?.data ?? n?.nodeValue ?? "";
866
+ for (const node of nodes) if (node.nodeType === 1) html += node.outerHTML ?? "";
867
+ else if (node.nodeType === 3) html += (node.data ?? node.nodeValue ?? "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
643
868
  return html;
644
869
  }
645
870
  /** Destroy the platform on a macrotask, matching `renderApplication`. */
646
871
  function asyncDestroyPlatform(platformRef) {
647
- return new Promise((resolve) => {
872
+ return new Promise((resolve, reject) => {
648
873
  setTimeout(() => {
649
- platformRef.destroy();
650
- resolve();
874
+ try {
875
+ platformRef.destroy();
876
+ resolve();
877
+ } catch (error) {
878
+ reject(error);
879
+ }
651
880
  }, 0);
652
881
  });
653
882
  }
@@ -661,77 +890,79 @@ function asyncDestroyPlatform(platformRef) {
661
890
  * ```
662
891
  */
663
892
  function renderStream(rootComponent, config, platformProviders = []) {
664
- function bootstrap(context) {
665
- return bootstrapApplication(rootComponent, config, context);
666
- }
667
893
  return async function renderStream(url, document, serverContext) {
894
+ serverContext.signal?.throwIfAborted();
895
+ const navigation = createSsrNavigationTracker();
896
+ const applicationConfig = {
897
+ ...config,
898
+ providers: [...config.providers, navigation.provider]
899
+ };
900
+ const bootstrap = (context) => bootstrapApplication(rootComponent, applicationConfig, context);
668
901
  resetComponentDefTViews();
669
902
  const primitiveAvailable = streamingPrimitiveAvailable();
670
903
  const bot = isLikelyBot(serverContext);
671
904
  const routeDisabled = streamingDisabledByRoute(serverContext);
672
905
  if (bot || routeDisabled || !primitiveAvailable) {
673
906
  if (!bot && !routeDisabled && !primitiveAvailable) warnMissingPrimitiveOnce();
674
- const html = await renderApplication((context) => bootstrapApplication(rootComponent, config, context), {
907
+ const html = await renderApplication(bootstrap, {
675
908
  document,
676
909
  url,
677
910
  platformProviders: [provideServerContext(serverContext), platformProviders]
678
911
  });
912
+ navigation.throwIfFailed();
679
913
  return new ReadableStream({ start(controller) {
680
914
  controller.enqueue(new TextEncoder().encode(html));
681
915
  controller.close();
682
916
  } });
683
917
  }
684
918
  installCaptureDispatcher();
685
- const encoder = new TextEncoder();
686
- return new ReadableStream({ async start(controller) {
687
- const enqueue = (s) => controller.enqueue(encoder.encode(s));
688
- let blockIndex = 0;
689
- let capturing = true;
690
- const seen = /* @__PURE__ */ new Set();
691
- const pendingFlushes = [];
692
- const onBlockResolved = (ev) => {
693
- if (!capturing || seen.has(ev.lContainer)) return;
694
- seen.add(ev.lContainer);
695
- const id = `s${blockIndex++}`;
696
- pendingFlushes.push(new Promise((resolve) => {
697
- setTimeout(() => {
698
- enqueue(`<template data-analog-defer="${id}">${serializeLContainerHtml(ev.lContainer)}</template><script>window.__analogPaint&&window.__analogPaint(${JSON.stringify(id)})<\/script>`);
699
- resolve();
700
- }, 0);
701
- }));
702
- };
703
- await captureStore.run(onBlockResolved, async () => {
704
- const platformRef = platformServer([
705
- {
706
- provide: INITIAL_CONFIG,
707
- useValue: {
708
- document,
709
- url
710
- }
711
- },
712
- provideServerContext(serverContext),
713
- platformProviders
714
- ]);
715
- enqueue(document.slice(0, afterBodyOpen(document)) + `<script>${DEFER_RECONCILE_RUNTIME}<\/script><div data-analog-stream></div>`);
716
- let appRef;
717
- let errored = false;
718
- try {
719
- appRef = await bootstrap({ platformRef });
919
+ const platformRef = platformServer([
920
+ {
921
+ provide: INITIAL_CONFIG,
922
+ useValue: {
923
+ document,
924
+ url
925
+ }
926
+ },
927
+ provideServerContext(serverContext),
928
+ platformProviders
929
+ ]);
930
+ let shell;
931
+ try {
932
+ shell = createStreamShell(platformRef);
933
+ } catch (error) {
934
+ await asyncDestroyPlatform(platformRef);
935
+ throw error;
936
+ }
937
+ return createSsrStream({
938
+ signal: serverContext.signal,
939
+ waitUntil: serverContext.waitUntil,
940
+ errorHtml: serverContext.renderErrorsAsHtml ? "<script data-analog-error>window.__analogFail&&window.__analogFail();<\/script></body></html>" : void 0,
941
+ destroy: () => asyncDestroyPlatform(platformRef),
942
+ async render(writer) {
943
+ let blockIndex = 0;
944
+ const seen = /* @__PURE__ */ new Set();
945
+ const onBlockResolved = (event) => {
946
+ if (!writer.active || seen.has(event.lContainer)) return;
947
+ seen.add(event.lContainer);
948
+ const id = `s${blockIndex++}`;
949
+ writer.scheduleBlock(() => `<template data-analog-defer="${id}">${serializeLContainerHtml(event.lContainer)}</template><script>window.__analogPaint&&window.__analogPaint(${JSON.stringify(id)})<\/script>`);
950
+ };
951
+ await runWithCapture(onBlockResolved, async () => {
952
+ writer.enqueue(shell + `<script>${DEFER_RECONCILE_RUNTIME}<\/script><div data-analog-stream></div>`);
953
+ const appRef = await bootstrap({ platformRef });
954
+ if (!writer.active) return;
720
955
  await appRef.whenStable();
721
- await Promise.all(pendingFlushes);
722
- capturing = false;
956
+ if (!writer.active) return;
957
+ navigation.throwIfFailed();
958
+ await writer.finishBlocks();
959
+ if (!writer.active) return;
723
960
  const authoritative = await ɵrenderInternal(platformRef, appRef);
724
- enqueue(`<template data-analog-head>${headInner(authoritative)}</template><template data-analog-authoritative>${bodyInner(authoritative)}</template><script>window.__analogReconcileHead&&window.__analogReconcileHead();window.__analogFinalize&&window.__analogFinalize()<\/script></body></html>`);
725
- } catch (err) {
726
- errored = true;
727
- console.error(`[@analogjs/router] renderStream failed for ${url} after ${blockIndex} block(s); response truncated.`, err);
728
- controller.error(err);
729
- } finally {
730
- await asyncDestroyPlatform(platformRef);
731
- if (!errored) controller.close();
732
- }
733
- });
734
- } });
961
+ navigation.throwIfFailed();
962
+ writer.enqueue(`<template data-analog-head>${headInner(authoritative)}</template><template data-analog-authoritative>${bodyInner(authoritative)}</template><script>window.__analogReconcileHead&&window.__analogReconcileHead();window.__analogFinalize&&window.__analogFinalize()<\/script></body></html>`);
963
+ });
964
+ }
965
+ });
735
966
  };
736
967
  }
737
968
  //#endregion