@aws-blocks/core 0.4.0 → 0.5.0

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 (90) hide show
  1. package/README.md +12 -0
  2. package/dist/cdk/blocks-backend.d.ts +4 -1
  3. package/dist/cdk/blocks-backend.d.ts.map +1 -1
  4. package/dist/cdk/blocks-backend.js +56 -10
  5. package/dist/cdk/blocks-backend.test.js +71 -1
  6. package/dist/cdk/blocks-defaults.d.ts +11 -0
  7. package/dist/cdk/blocks-defaults.d.ts.map +1 -1
  8. package/dist/cdk/blocks-stack.test.js +23 -3
  9. package/dist/cdk/compute/compute.d.ts +80 -2
  10. package/dist/cdk/compute/compute.d.ts.map +1 -1
  11. package/dist/cdk/compute/compute.js +57 -3
  12. package/dist/cdk/config-registry.test.js +12 -0
  13. package/dist/cdk/dashboard-registry.d.ts +41 -0
  14. package/dist/cdk/dashboard-registry.d.ts.map +1 -0
  15. package/dist/cdk/dashboard-registry.js +61 -0
  16. package/dist/cdk/index.d.ts +67 -11
  17. package/dist/cdk/index.d.ts.map +1 -1
  18. package/dist/cdk/index.js +100 -18
  19. package/dist/cdk/internal.d.ts +3 -1
  20. package/dist/cdk/internal.d.ts.map +1 -1
  21. package/dist/cdk/internal.js +4 -1
  22. package/dist/cdk/tracer-registry.d.ts +31 -0
  23. package/dist/cdk/tracer-registry.d.ts.map +1 -0
  24. package/dist/cdk/tracer-registry.js +49 -0
  25. package/dist/cdk/vpc-requirements-registry.d.ts +33 -0
  26. package/dist/cdk/vpc-requirements-registry.d.ts.map +1 -0
  27. package/dist/cdk/vpc-requirements-registry.js +46 -0
  28. package/dist/cdk/vpc-types.d.ts +151 -0
  29. package/dist/cdk/vpc-types.d.ts.map +1 -0
  30. package/dist/cdk/vpc-types.js +3 -0
  31. package/dist/cdk/vpc.d.ts +59 -0
  32. package/dist/cdk/vpc.d.ts.map +1 -0
  33. package/dist/cdk/vpc.js +298 -0
  34. package/dist/cdk/vpc.test.d.ts +2 -0
  35. package/dist/cdk/vpc.test.d.ts.map +1 -0
  36. package/dist/cdk/vpc.test.js +285 -0
  37. package/dist/errors.d.ts +5 -0
  38. package/dist/errors.d.ts.map +1 -1
  39. package/dist/errors.js +5 -0
  40. package/dist/hosting.d.ts.map +1 -1
  41. package/dist/hosting.js +2 -0
  42. package/dist/hosting.test.js +39 -1
  43. package/dist/index.cdk.d.ts +2 -1
  44. package/dist/index.cdk.d.ts.map +1 -1
  45. package/dist/index.cdk.js +1 -1
  46. package/dist/lambda-handler.js +9 -2
  47. package/dist/lambda-handler.test.js +61 -1
  48. package/dist/raw-route.d.ts +15 -1
  49. package/dist/raw-route.d.ts.map +1 -1
  50. package/dist/raw-route.js +96 -12
  51. package/dist/raw-route.test.js +332 -1
  52. package/dist/scripts/dev-server.d.ts.map +1 -1
  53. package/dist/scripts/dev-server.js +11 -0
  54. package/dist/scripts/extract-ts-types.d.ts.map +1 -1
  55. package/dist/scripts/extract-ts-types.js +107 -23
  56. package/dist/scripts/extract-ts-types.test.js +225 -26
  57. package/dist/scripts/generate-spec.d.ts.map +1 -1
  58. package/dist/scripts/generate-spec.js +14 -5
  59. package/dist/scripts/generate-spec.test.js +93 -0
  60. package/dist/version.d.ts +1 -1
  61. package/dist/version.js +1 -1
  62. package/package.json +8 -1
  63. package/src/cdk/blocks-backend.test.ts +144 -60
  64. package/src/cdk/blocks-backend.ts +298 -239
  65. package/src/cdk/blocks-defaults.ts +12 -0
  66. package/src/cdk/blocks-stack.test.ts +32 -13
  67. package/src/cdk/compute/compute.ts +105 -3
  68. package/src/cdk/config-registry.test.ts +14 -0
  69. package/src/cdk/dashboard-registry.ts +68 -0
  70. package/src/cdk/index.ts +426 -298
  71. package/src/cdk/internal.ts +6 -2
  72. package/src/cdk/tracer-registry.ts +54 -0
  73. package/src/cdk/vpc-requirements-registry.ts +63 -0
  74. package/src/cdk/vpc-types.ts +158 -0
  75. package/src/cdk/vpc.test.ts +348 -0
  76. package/src/cdk/vpc.ts +336 -0
  77. package/src/errors.ts +5 -0
  78. package/src/hosting.test.ts +59 -1
  79. package/src/hosting.ts +3 -0
  80. package/src/index.cdk.ts +7 -0
  81. package/src/lambda-handler.test.ts +79 -1
  82. package/src/lambda-handler.ts +11 -2
  83. package/src/raw-route.test.ts +427 -1
  84. package/src/raw-route.ts +125 -12
  85. package/src/scripts/dev-server.ts +12 -1
  86. package/src/scripts/extract-ts-types.test.ts +228 -26
  87. package/src/scripts/extract-ts-types.ts +104 -20
  88. package/src/scripts/generate-spec.test.ts +101 -0
  89. package/src/scripts/generate-spec.ts +15 -5
  90. package/src/version.ts +1 -1
@@ -1,8 +1,14 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import { describe, it, beforeEach } from 'node:test';
4
+ import { describe, it, before, beforeEach } from 'node:test';
5
5
  import assert from 'node:assert';
6
+ import { spawnSync } from 'node:child_process';
7
+ import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { tmpdir } from 'node:os';
9
+ import { dirname, join } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { buildSync } from 'esbuild';
6
12
  import {
7
13
  compilePath,
8
14
  registerRoute,
@@ -15,6 +21,7 @@ import {
15
21
  derivePathFromScope,
16
22
  resolveRoutePath,
17
23
  } from './raw-route.js';
24
+ import type { RegisteredRoute } from './raw-route.js';
18
25
  import type { BlocksContext } from './api.js';
19
26
 
20
27
  const noop = async (_ctx: BlocksContext) => {};
@@ -817,3 +824,422 @@ describe('resolveRoutePath', () => {
817
824
  assert.strictEqual(path, '/v1/users');
818
825
  });
819
826
  });
827
+
828
+ // ── Cross-copy registry sharing ─────────────────────────────────────────────
829
+ //
830
+ // A bundle can contain more than one physical copy of @aws-blocks/core (an
831
+ // unlucky dependency tree, no dedupe). With module-local registry state, every
832
+ // copy gets its own route table: Building Blocks register into theirs, the
833
+ // dispatcher reads its own, and the routes 404 silently.
834
+ //
835
+ // These tests stand in for a second copy: they poke the shared state directly
836
+ // through globalThis, exactly as a second copy of the module would see it.
837
+ // The key is spelled out as a literal on purpose — it IS the cross-copy
838
+ // contract, so changing it must break a test.
839
+
840
+ const REGISTRY_KEY = '__AWS_BLOCKS_RAW_ROUTE_REGISTRY_V1__';
841
+
842
+ interface SharedRegistryState {
843
+ routes: RegisteredRoute[];
844
+ locked: boolean;
845
+ copies: number;
846
+ }
847
+
848
+ type GlobalWithRegistry = typeof globalThis & { [REGISTRY_KEY]?: SharedRegistryState };
849
+
850
+ /** Read the registry state that a second core copy would share with us. */
851
+ function sharedState(): SharedRegistryState {
852
+ const state = (globalThis as GlobalWithRegistry)[REGISTRY_KEY];
853
+ assert.ok(state, `route registry state must live on globalThis['${REGISTRY_KEY}']`);
854
+ return state;
855
+ }
856
+
857
+ describe('registry state is shared across core copies', () => {
858
+ it('matchRoute() resolves a route registered by another core copy', () => {
859
+ const { pattern, paramNames } = compilePath('/from-other-copy');
860
+ sharedState().routes.push({
861
+ method: 'GET',
862
+ path: '/from-other-copy',
863
+ pattern,
864
+ paramNames,
865
+ handler: noop,
866
+ });
867
+
868
+ const result = matchRoute('GET', '/from-other-copy');
869
+ assert.ok(result, 'route registered by another copy must be dispatchable');
870
+ assert.strictEqual(result.route.path, '/from-other-copy');
871
+ });
872
+
873
+ it('getRegisteredRoutes() reports routes registered by another core copy', () => {
874
+ const { pattern, paramNames } = compilePath('/synth-visible');
875
+ sharedState().routes.push({
876
+ method: 'GET',
877
+ path: '/synth-visible',
878
+ pattern,
879
+ paramNames,
880
+ handler: noop,
881
+ });
882
+
883
+ // Synth-time consumers (CloudFront behaviors in hosting.ts) iterate this.
884
+ assert.ok(getRegisteredRoutes().some((r) => r.path === '/synth-visible'));
885
+ });
886
+
887
+ it('registerRoute() publishes the route into the shared state', () => {
888
+ registerRoute({ method: 'POST', path: '/published', handler: noop });
889
+
890
+ assert.ok(
891
+ sharedState().routes.some((r) => r.method === 'POST' && r.path === '/published'),
892
+ 'another copy must be able to see routes we registered',
893
+ );
894
+ });
895
+
896
+ it('registerRoute() honours a lock set by another core copy', () => {
897
+ sharedState().locked = true;
898
+
899
+ assert.throws(
900
+ () => registerRoute({ method: 'GET', path: '/after-foreign-lock', handler: noop }),
901
+ (err: Error) => {
902
+ assert.ok(err.message.includes('Cannot register routes after handler creation'));
903
+ return true;
904
+ },
905
+ );
906
+ });
907
+
908
+ it('lockRouteRegistry() locks the shared state, not a module-local flag', () => {
909
+ lockRouteRegistry();
910
+ assert.strictEqual(sharedState().locked, true);
911
+ });
912
+
913
+ it('clearRouteRegistry() clears the shared state and releases the shared lock', () => {
914
+ registerRoute({ method: 'GET', path: '/leftover', handler: noop });
915
+ lockRouteRegistry();
916
+
917
+ clearRouteRegistry();
918
+
919
+ assert.deepStrictEqual(sharedState().routes, []);
920
+ assert.strictEqual(sharedState().locked, false);
921
+ });
922
+
923
+ it('clearRouteRegistry() does not reset the copy counter', () => {
924
+ const before = sharedState().copies;
925
+ clearRouteRegistry();
926
+ assert.strictEqual(sharedState().copies, before, 'copies counts module loads, not routes');
927
+ });
928
+
929
+ // Behavior change, deliberately kept: with a shared registry, duplicate
930
+ // detection reaches across copies for the first time. An app with two core
931
+ // copies AND two instances of the same Building Block used to split the
932
+ // routes silently (half of them 404ing); it now fails loudly at startup.
933
+ // The app was already broken — this only makes it say so.
934
+ it('rejects a duplicate of a route another core copy registered', () => {
935
+ const { pattern, paramNames } = compilePath('/shared-path');
936
+ sharedState().routes.push({
937
+ method: 'GET',
938
+ path: '/shared-path',
939
+ pattern,
940
+ paramNames,
941
+ handler: noop,
942
+ });
943
+
944
+ assert.throws(
945
+ () => registerRoute({ method: 'GET', path: '/shared-path', handler: noop }),
946
+ (err: Error) => {
947
+ assert.strictEqual(err.name, RawRouteErrors.DuplicateRoute);
948
+ return true;
949
+ },
950
+ );
951
+ });
952
+ });
953
+
954
+ describe('duplicate core copies are announced', () => {
955
+ /**
956
+ * Use raw-route.js in a fresh process, optionally pre-seeding the shared
957
+ * state as an earlier copy would have left it, and return stderr.
958
+ *
959
+ * The copy must be *used*, not merely imported: the counter increments on
960
+ * first registry access, so a copy that never touches the registry is never
961
+ * counted — deliberately, since only routing copies matter here.
962
+ */
963
+ function useInFreshProcess(preSeededCopies: number | null): string {
964
+ const moduleUrl = new URL('./raw-route.js', import.meta.url).href;
965
+ const seed =
966
+ preSeededCopies === null
967
+ ? ''
968
+ : `globalThis[${JSON.stringify(REGISTRY_KEY)}] = { routes: [], locked: false, copies: ${preSeededCopies} };`;
969
+ const script = `${seed}const m = await import(${JSON.stringify(moduleUrl)}); m.registerRoute({ method: 'GET', path: '/probe', handler: async () => {} });`;
970
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8' });
971
+ assert.strictEqual(result.status, 0, `using raw-route.js failed: ${result.stderr}`);
972
+ return result.stderr;
973
+ }
974
+
975
+ it('warns when a second copy of @aws-blocks/core joins the shared registry', () => {
976
+ const stderr = useInFreshProcess(1);
977
+ assert.match(stderr, /2 copies of @aws-blocks\/core/);
978
+ });
979
+
980
+ it('stays silent for a healthy single-copy install', () => {
981
+ const stderr = useInFreshProcess(null);
982
+ assert.doesNotMatch(stderr, /copies of @aws-blocks\/core/);
983
+ });
984
+
985
+ it('warns once per copy, not once per registry access', () => {
986
+ const moduleUrl = new URL('./raw-route.js', import.meta.url).href;
987
+ const script = `globalThis[${JSON.stringify(REGISTRY_KEY)}] = { routes: [], locked: false, copies: 1 };
988
+ const m = await import(${JSON.stringify(moduleUrl)});
989
+ m.registerRoute({ method: 'GET', path: '/a', handler: async () => {} });
990
+ m.registerRoute({ method: 'GET', path: '/b', handler: async () => {} });
991
+ m.matchRoute('GET', '/a');`;
992
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8' });
993
+ assert.strictEqual(result.status, 0, result.stderr);
994
+
995
+ const warnings = result.stderr.split('\n').filter((line) => line.includes('copies of @aws-blocks/core'));
996
+ assert.strictEqual(warnings.length, 1, `expected exactly one warning, got: ${JSON.stringify(warnings)}`);
997
+ });
998
+ });
999
+
1000
+ // ── A peer copy's state is adopted, not trusted ─────────────────────────────
1001
+ //
1002
+ // The registry key is a permanent contract: copies sharing a process are
1003
+ // usually different *versions* of @aws-blocks/core, so the shape may only grow
1004
+ // — a copy that renamed the key would re-split the registry silently, each key
1005
+ // holding its own copy counter. The other half of that contract is this side:
1006
+ // a copy must cope with a state a peer left without the fields it expects.
1007
+ describe('registry state from a peer copy is adopted, not trusted', () => {
1008
+ /**
1009
+ * Import raw-route.js in a fresh process on top of a pre-seeded shared state
1010
+ * and report what the copy made of it.
1011
+ *
1012
+ * `seed` stands in for a copy whose registry shape differs from this one's.
1013
+ * Fields are omitted, never renamed — that is exactly the evolution the key's
1014
+ * contract permits.
1015
+ */
1016
+ function useOnTopOf(seed: string): { matched: boolean; copies: number | null } {
1017
+ const moduleUrl = new URL('./raw-route.js', import.meta.url).href;
1018
+ const script = `globalThis[${JSON.stringify(REGISTRY_KEY)}] = ${seed};
1019
+ const m = await import(${JSON.stringify(moduleUrl)});
1020
+ m.registerRoute({ method: 'GET', path: '/probe', handler: async () => {} });
1021
+ console.log(JSON.stringify({
1022
+ matched: m.matchRoute('GET', '/probe') !== null,
1023
+ copies: m.getLoadedCoreCopies(),
1024
+ }));`;
1025
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8' });
1026
+ assert.strictEqual(result.status, 0, `using raw-route.js failed: ${result.stderr}`);
1027
+ // NaN serializes to null — which is the point of reporting it this way.
1028
+ return JSON.parse(result.stdout.trim());
1029
+ }
1030
+
1031
+ it('registers into a state that arrived without a route table', () => {
1032
+ const { matched } = useOnTopOf('{ locked: false, copies: 1 }');
1033
+ assert.strictEqual(matched, true, 'a missing route table must be created, not thrown on');
1034
+ });
1035
+
1036
+ it('keeps the copy count a number when the state arrived without one', () => {
1037
+ const { copies } = useOnTopOf('{ routes: [], locked: false }');
1038
+ assert.strictEqual(copies, 1, 'a missing counter must restart at a number — NaN would mute the warning');
1039
+ });
1040
+ });
1041
+
1042
+ // ── A real duplicate install: two physical copies of the package ────────────
1043
+ //
1044
+ // Everything above stands in for a second core copy by writing to globalThis
1045
+ // directly. That pins the contract, but it cannot tell a working fix apart
1046
+ // from one that only appears to work because both "copies" were the same
1047
+ // module instance all along — which is precisely the mistake that produced the
1048
+ // original defect. This block loads two genuinely separate copies (two
1049
+ // directory trees, two module instances, the shape a bundler emits from a
1050
+ // nested `node_modules/@aws-blocks/core`) and replays the production sequence:
1051
+ // a Building Block registers its route through one copy, the dispatcher looks
1052
+ // it up through the other.
1053
+ //
1054
+ // Against the pre-fix implementation this returns no match and an empty route
1055
+ // table — the silent 404 reported in aws-blocks#355.
1056
+
1057
+ interface TwoCopyProbe {
1058
+ /** Whether the two imports really produced separate module instances. */
1059
+ distinctInstances: boolean;
1060
+ /** Path the dispatcher copy resolved, or null when nothing matched. */
1061
+ matchedPath: string | null;
1062
+ /** Size of the route table the dispatcher copy consulted. */
1063
+ routesSeenByDispatcher: number;
1064
+ /** Copy count the dispatcher copy reports, or null if it cannot report one. */
1065
+ copiesReported: number | null;
1066
+ /** Everything the probe wrote to stderr (carries the duplicate warning). */
1067
+ stderr: string;
1068
+ /** The bundled source, when the probe was bundled first; otherwise null. */
1069
+ bundleText: string | null;
1070
+ }
1071
+
1072
+ /**
1073
+ * The probe itself: a Building Block registers its route through one copy of
1074
+ * the package, the dispatcher looks it up through the other.
1075
+ *
1076
+ * Kept as a standalone ES module with static imports so the very same source
1077
+ * can be run as-is and, in the test below, sent through a bundler first.
1078
+ */
1079
+ const TWO_COPY_ENTRY = `
1080
+ import * as a from './copy-a/dist/raw-route.js';
1081
+ import * as b from './copy-b/dist/raw-route.js';
1082
+
1083
+ a.registerRoute({ method: 'GET', path: '/aws-blocks/auth/signin/google', handler: async () => {} });
1084
+ const matched = b.matchRoute('GET', '/aws-blocks/auth/signin/google');
1085
+
1086
+ const observed = {
1087
+ distinctInstances: a !== b,
1088
+ matchedPath: matched ? matched.route.path : null,
1089
+ routesSeenByDispatcher: b.getRegisteredRoutes().length,
1090
+ copiesReported: null,
1091
+ };
1092
+ // Report the routing facts even if the diagnostics helper is missing or
1093
+ // throws — whether the route resolves is what this probe is about, and a
1094
+ // build that lost the helper must not hide that behind a crashed child.
1095
+ try {
1096
+ observed.copiesReported = b.getLoadedCoreCopies();
1097
+ } catch {}
1098
+ console.log(JSON.stringify(observed));
1099
+ `;
1100
+
1101
+ /**
1102
+ * Install two physical copies of this package and route a request across them.
1103
+ *
1104
+ * Runs in a child process so the copies start from a clean `globalThis` and
1105
+ * cannot leak registry state into this test run. The whole directory is copied
1106
+ * rather than the two files currently needed, so the probe keeps working when
1107
+ * `raw-route.js` grows an import.
1108
+ *
1109
+ * With `bundle`, the probe is first bundled the way a deployed handler is —
1110
+ * `NodejsFunction` runs esbuild with `--conditions=aws-runtime` — before it is
1111
+ * executed.
1112
+ */
1113
+ function runTwoCopyProbe({ bundle }: { bundle: boolean }): TwoCopyProbe {
1114
+ const distDir = dirname(fileURLToPath(import.meta.url));
1115
+ const packageDir = dirname(distDir);
1116
+ const root = mkdtempSync(join(tmpdir(), 'aws-blocks-two-copies-'));
1117
+ try {
1118
+ // Copy A belongs to the Building Block, copy B to the dispatcher. Each is
1119
+ // laid out as an installed package — `package.json` beside `dist/`, the
1120
+ // shape npm produces for a nested `node_modules/@aws-blocks/core`. The
1121
+ // manifest has to come along: a real install has one, and it is what a
1122
+ // bundler reads for `type` and `sideEffects` — without it the bundle here
1123
+ // would be built under different rules than the deployed one.
1124
+ for (const copy of ['copy-a', 'copy-b']) {
1125
+ cpSync(distDir, join(root, copy, 'dist'), { recursive: true });
1126
+ cpSync(join(packageDir, 'package.json'), join(root, copy, 'package.json'));
1127
+ }
1128
+
1129
+ const entry = join(root, 'entry.mjs');
1130
+ writeFileSync(entry, TWO_COPY_ENTRY);
1131
+
1132
+ let script = entry;
1133
+ let bundleText: string | null = null;
1134
+ if (bundle) {
1135
+ const outfile = join(root, 'bundle.mjs');
1136
+ buildSync({
1137
+ entryPoints: [entry],
1138
+ outfile,
1139
+ bundle: true,
1140
+ format: 'esm',
1141
+ platform: 'node',
1142
+ conditions: ['aws-runtime'],
1143
+ minify: true,
1144
+ logLevel: 'silent',
1145
+ });
1146
+ bundleText = readFileSync(outfile, 'utf8');
1147
+ script = outfile;
1148
+ }
1149
+
1150
+ const result = spawnSync(process.execPath, [script], { encoding: 'utf8' });
1151
+ assert.strictEqual(result.status, 0, `two-copy probe failed: ${result.stderr}`);
1152
+ return {
1153
+ ...(JSON.parse(result.stdout) as Omit<TwoCopyProbe, 'stderr' | 'bundleText'>),
1154
+ stderr: result.stderr,
1155
+ bundleText,
1156
+ };
1157
+ } finally {
1158
+ rmSync(root, { recursive: true, force: true });
1159
+ }
1160
+ }
1161
+
1162
+ describe('two physical core copies share one registry', () => {
1163
+ let probe: TwoCopyProbe;
1164
+
1165
+ before(() => {
1166
+ probe = runTwoCopyProbe({ bundle: false });
1167
+ });
1168
+
1169
+ it('loads two separate module instances', () => {
1170
+ // Guards the probe itself: if this ever collapses to one instance, the
1171
+ // tests below would pass without exercising anything.
1172
+ assert.strictEqual(probe.distinctInstances, true);
1173
+ });
1174
+
1175
+ it('dispatches a route the other copy registered', () => {
1176
+ assert.strictEqual(
1177
+ probe.matchedPath,
1178
+ '/aws-blocks/auth/signin/google',
1179
+ 'the dispatcher copy must resolve a route registered through the other copy',
1180
+ );
1181
+ });
1182
+
1183
+ it('shows the route in the table the dispatcher consults', () => {
1184
+ // A zero here is the fingerprint of the original defect: registration
1185
+ // succeeded, and the dispatcher looked at an empty table.
1186
+ assert.strictEqual(probe.routesSeenByDispatcher, 1);
1187
+ });
1188
+
1189
+ it('counts and announces both copies', () => {
1190
+ assert.strictEqual(probe.copiesReported, 2);
1191
+ assert.match(probe.stderr, /2 copies of @aws-blocks\/core/);
1192
+ });
1193
+ });
1194
+
1195
+ // ── The same thing, but bundled ─────────────────────────────────────────────
1196
+ //
1197
+ // Duplicate copies are a bundling phenomenon: the reported defect was found in
1198
+ // a deployed bundle, not in a node_modules tree at rest. A deployed handler is
1199
+ // built by `NodejsFunction`, which runs esbuild with `--conditions=aws-runtime`
1200
+ // (see cdk/blocks-backend.ts), so this repeats that step and then runs the
1201
+ // result. Minified on purpose — it is the harsher case, and passing it implies
1202
+ // the unminified one.
1203
+ //
1204
+ // What this pins down that the unbundled probe cannot:
1205
+ //
1206
+ // - that a bundler keeps two copies of the same file at different paths
1207
+ // rather than collapsing them, i.e. that the failure mode reaches the
1208
+ // deployed artifact at all;
1209
+ // - that reaching the registry through `globalThis[<string key>]` survives
1210
+ // minification, so the two copies still meet;
1211
+ // - that the key stays a greppable literal, which is the documented way to
1212
+ // diagnose a duplicate install in a deployed bundle (and the reason it is
1213
+ // a plain string rather than a `Symbol.for()` key).
1214
+ //
1215
+ // What it deliberately does *not* claim: that counting copies on first use
1216
+ // rather than at module load is required to survive tree-shaking. That was
1217
+ // measured — with `sideEffects` honoured and `--minify` on, esbuild retains a
1218
+ // top-level counter here, because a module whose exports are used is kept
1219
+ // whole. Counting on first use stands on its other stated reason: it counts the
1220
+ // copies that take part in routing, not the ones merely imported.
1221
+
1222
+ describe('the shared registry survives bundling', () => {
1223
+ let probe: TwoCopyProbe;
1224
+
1225
+ before(() => {
1226
+ probe = runTwoCopyProbe({ bundle: true });
1227
+ });
1228
+
1229
+ it('keeps two participating copies in one bundle', () => {
1230
+ // Also guards the test: were the two copies collapsed into one module
1231
+ // scope, the assertions below would pass without ever crossing a copy
1232
+ // boundary — and there would be no defect left to protect against.
1233
+ assert.strictEqual(probe.copiesReported, 2, 'the bundle must still contain two participating copies');
1234
+ assert.strictEqual(probe.distinctInstances, true);
1235
+ });
1236
+
1237
+ it('dispatches a route the other copy registered', () => {
1238
+ assert.strictEqual(probe.matchedPath, '/aws-blocks/auth/signin/google');
1239
+ assert.strictEqual(probe.routesSeenByDispatcher, 1);
1240
+ });
1241
+
1242
+ it('keeps the registry key greppable in the bundle', () => {
1243
+ assert.ok(probe.bundleText?.includes('__AWS_BLOCKS_RAW_ROUTE_REGISTRY_V1__'));
1244
+ });
1245
+ });
package/src/raw-route.ts CHANGED
@@ -105,19 +105,126 @@ export interface RegisteredRoute {
105
105
  handler: (context: BlocksContext) => Promise<void>;
106
106
  }
107
107
 
108
- const routeRegistry: RegisteredRoute[] = [];
109
- let registrationLocked = false;
108
+ /**
109
+ * Registry state shared by every copy of `@aws-blocks/core` in the process.
110
+ *
111
+ * A bundle can end up carrying more than one physical copy of this package
112
+ * (an unlucky dependency tree, no dedupe). With module-local state each copy
113
+ * would keep its own route table: Building Blocks register into theirs, the
114
+ * dispatcher reads its own, and every route registered through the "wrong"
115
+ * copy answers 404 without a log line. The synth path has the same split —
116
+ * `hosting.ts` builds CloudFront behaviors from `getRegisteredRoutes()`.
117
+ *
118
+ * `locked` travels with `routes` on purpose: splitting them would let one copy
119
+ * lock the shared table while another is still registering, trading a silent
120
+ * loss for a spurious throw.
121
+ */
122
+ interface RawRouteRegistryState {
123
+ routes: RegisteredRoute[];
124
+ locked: boolean;
125
+ /** Number of core copies that have joined this registry (1 = healthy). */
126
+ copies: number;
127
+ }
128
+
129
+ /**
130
+ * Well-known `globalThis` key holding the shared registry state.
131
+ *
132
+ * A plain string rather than a `Symbol.for()` key, deliberately: duplicate
133
+ * copies are diagnosed by counting strings in the deployed bundle, and a
134
+ * symbol would be invisible to that. It also matches the existing
135
+ * `__BLOCKS_LAMBDA_EVENT_HANDLERS__` precedent.
136
+ *
137
+ * **The key is a permanent contract — do not bump it.** `_V1_` names the shape
138
+ * this file introduced; it is not a license to mint `_V2_`. The copies that
139
+ * share a process are usually *different versions* of `@aws-blocks/core` — that
140
+ * is how a tree ends up with duplicates in the first place — so a copy reading
141
+ * a different key does not get a private namespace, it re-splits the registry:
142
+ * routes registered through one key, dispatched through the other, 404. And
143
+ * silently, because each key carries its own `copies` counter, so both sides
144
+ * report `copies: 1` and the duplicate warning never fires. That is the bug
145
+ * this module exists to fix, reintroduced with its own diagnostic switched off.
146
+ *
147
+ * Evolve the shape **additively** instead: add optional fields, and tolerate
148
+ * fields a peer copy did not write (`getState()` does). If a `_V2_` key ever
149
+ * proves unavoidable, it has to adopt the V1 state — read it, and keep writing
150
+ * it — so that a mixed tree still routes through one table.
151
+ */
152
+ const REGISTRY_KEY = '__AWS_BLOCKS_RAW_ROUTE_REGISTRY_V1__';
153
+
154
+ type GlobalWithRegistry = typeof globalThis & { [REGISTRY_KEY]?: RawRouteRegistryState };
155
+
156
+ /** Whether *this* module copy has already counted itself. Intentionally module-local. */
157
+ let thisCopyCounted = false;
158
+
159
+ /**
160
+ * Resolve the shared registry state, creating it on first access.
161
+ *
162
+ * The copy count is incremented here rather than at module load so that it
163
+ * counts the copies actually taking part in routing, not every copy a bundle
164
+ * happens to carry. Bundled code is where duplicate copies occur, and a copy
165
+ * that is imported but never routes is not what the diagnostic is about.
166
+ *
167
+ * Tree-shaking is not the reason. `sideEffects` in package.json lets a bundler
168
+ * drop this module whole when nothing it exports is used, but a module that
169
+ * *is* used keeps its top-level statements — measured with esbuild under
170
+ * `--bundle --minify`, and covered by the bundling test in `raw-route.test.ts`.
171
+ */
172
+ function getState(): RawRouteRegistryState {
173
+ const g = globalThis as GlobalWithRegistry;
174
+ let state = g[REGISTRY_KEY];
175
+ if (!state) {
176
+ state = { routes: [], locked: false, copies: 0 };
177
+ g[REGISTRY_KEY] = state;
178
+ }
179
+
180
+ // The state may have been left by a copy that evolved the shape (see the
181
+ // contract on REGISTRY_KEY), so fill in what this copy needs rather than
182
+ // assume it is there. A missing `routes` would throw on the first
183
+ // registration, and a missing `copies` would go NaN on the increment below —
184
+ // silencing the duplicate warning, which is the failure this module exists to
185
+ // report. `locked` needs no default: absent reads as unlocked, which is what
186
+ // a registry still accepting registrations means.
187
+ if (!Array.isArray(state.routes)) state.routes = [];
188
+ if (typeof state.copies !== 'number') state.copies = 0;
189
+
190
+ if (!thisCopyCounted) {
191
+ thisCopyCounted = true;
192
+ state.copies += 1;
193
+ if (state.copies > 1) {
194
+ console.warn(
195
+ `AWS Blocks: ${state.copies} copies of @aws-blocks/core loaded in this process. ` +
196
+ 'They now share one RawRoute registry, but duplicate copies indicate a ' +
197
+ 'dependency-tree problem — deduplicate @aws-blocks/core.',
198
+ );
199
+ }
200
+ }
201
+
202
+ return state;
203
+ }
204
+
205
+ /**
206
+ * Number of `@aws-blocks/core` copies taking part in the shared route registry.
207
+ *
208
+ * `1` for a healthy install. A higher number means the dependency tree carries
209
+ * duplicates — routes still work (the registry is shared), but it is worth
210
+ * reporting in diagnostics.
211
+ *
212
+ * **Internal.** Not re-exported from the package entry point.
213
+ */
214
+ export function getLoadedCoreCopies(): number {
215
+ return getState().copies;
216
+ }
110
217
 
111
218
  const VALID_METHODS = new Set<string>(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']);
112
219
 
113
220
  /** Prevent further route registration. Call after initialization is complete. */
114
221
  export function lockRouteRegistry(): void {
115
- registrationLocked = true;
222
+ getState().locked = true;
116
223
  }
117
224
 
118
225
  /** Re-allow route registration (useful in tests after lock). */
119
226
  export function unlockRouteRegistry(): void {
120
- registrationLocked = false;
227
+ getState().locked = false;
121
228
  }
122
229
 
123
230
  /**
@@ -132,7 +239,8 @@ export function unlockRouteRegistry(): void {
132
239
  * @throws {RawRouteErrors.DuplicateRoute} If the same method+path is registered twice.
133
240
  */
134
241
  export function registerRoute(options: RawRouteOptions & { path: string }): void {
135
- if (registrationLocked) {
242
+ const state = getState();
243
+ if (state.locked) {
136
244
  throw new Error('Routes must be registered during initialization. Cannot register routes after handler creation.');
137
245
  }
138
246
 
@@ -150,7 +258,7 @@ export function registerRoute(options: RawRouteOptions & { path: string }): void
150
258
  throw new Error(`Cannot register RawRoute at ${BLOCKS_NAMESPACE} or ${BLOCKS_RPC_PREFIX}/* — these paths are reserved for RPC dispatch`);
151
259
  }
152
260
 
153
- const existing = routeRegistry.find(
261
+ const existing = state.routes.find(
154
262
  (r) => r.method === options.method && r.path === normalizedPath,
155
263
  );
156
264
  if (existing) {
@@ -163,7 +271,7 @@ export function registerRoute(options: RawRouteOptions & { path: string }): void
163
271
 
164
272
  const { pattern, paramNames } = compilePath(normalizedPath);
165
273
 
166
- routeRegistry.push({
274
+ state.routes.push({
167
275
  method: options.method,
168
276
  path: normalizedPath,
169
277
  pattern,
@@ -174,13 +282,18 @@ export function registerRoute(options: RawRouteOptions & { path: string }): void
174
282
 
175
283
  /** Return a read-only snapshot of all registered routes. */
176
284
  export function getRegisteredRoutes(): readonly RegisteredRoute[] {
177
- return routeRegistry;
285
+ return getState().routes;
178
286
  }
179
287
 
180
- /** Remove all registered routes and unlock registration (used by tests). */
288
+ /**
289
+ * Remove all registered routes and unlock registration (used by tests).
290
+ *
291
+ * Leaves the copy counter alone — it tracks module copies, not routes.
292
+ */
181
293
  export function clearRouteRegistry(): void {
182
- routeRegistry.length = 0;
183
- registrationLocked = false;
294
+ const state = getState();
295
+ state.routes.length = 0;
296
+ state.locked = false;
184
297
  }
185
298
 
186
299
  /**
@@ -195,7 +308,7 @@ export function matchRoute(
195
308
  // Normalize incoming path: collapse double slashes
196
309
  path = path.replace(/\/+/g, '/');
197
310
 
198
- for (const route of routeRegistry) {
311
+ for (const route of getState().routes) {
199
312
  if (route.method !== method) continue;
200
313
  const match = route.pattern.exec(path);
201
314
  if (match) {
@@ -6,7 +6,8 @@ import { pathToFileURL, URL } from 'node:url';
6
6
  import { resolve, dirname, join } from 'node:path';
7
7
  import { writeFileSync, mkdirSync, readFileSync, unlinkSync, renameSync } from 'node:fs';
8
8
  import { spawn, type ChildProcess } from 'node:child_process';
9
- import { createConnection } from 'node:net';
9
+ import { createConnection, type Socket } from 'node:net';
10
+ import type { Duplex } from 'node:stream';
10
11
  import httpProxy from 'http-proxy';
11
12
  import { writeClientCode } from './generate-client.js';
12
13
  import { ApiError } from '../errors.js';
@@ -952,6 +953,10 @@ export async function startDevServer(options: DevServerOptions) {
952
953
 
953
954
  // WebSocket upgrade — route to frontend (HMR) or dev attachments
954
955
  server.on('upgrade', (req, socket, head) => {
956
+ // A stale client can reset the connection mid-upgrade (ECONNRESET). The raw
957
+ // socket has no 'error' listener at this point, so Node's default handler
958
+ // would kill the dev server. Attach one before any parsing/routing.
959
+ socket.on('error', () => socket.destroy());
955
960
  const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
956
961
  if (url.pathname === '/realtime') return; // handled by dev attachment (noServer mode)
957
962
  if (frontendProxy) {
@@ -1043,6 +1048,12 @@ export async function startDevServer(options: DevServerOptions) {
1043
1048
  onExhausted: () => process.exit(1),
1044
1049
  warn: (msg) => console.error(msg),
1045
1050
  });
1051
+ // Malformed/aborted requests must not become unhandled socket errors.
1052
+ server.on('clientError', (_err: Error, socket: Duplex) => {
1053
+ if ((socket as Socket).writable) socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
1054
+ else socket.destroy();
1055
+ });
1056
+
1046
1057
  server.on('error', (err: NodeJS.ErrnoException) => {
1047
1058
  if (err.code === 'EADDRINUSE') {
1048
1059
  // Keep the telemetry signal (unchanged) …