-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal-api-router.mjs
More file actions
7160 lines (6781 loc) · 275 KB
/
Copy pathlocal-api-router.mjs
File metadata and controls
7160 lines (6781 loc) · 275 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomBytes } from "node:crypto";
import { Buffer } from "node:buffer";
import { readFileSync, readdirSync } from "node:fs";
import path from "node:path";
import process from "node:process";
import {
createAssetToolMockRepository,
pickerDiagnosticForRole,
} from "../persistence/tool-repositories/assets-mock-repository.js";
import {
createTagsToolMockRepository,
} from "../persistence/tool-repositories/tags-mock-repository.js";
import {
createObjectsToolMockRepository,
} from "../persistence/tool-repositories/objects-mock-repository.js";
import {
createInputMappingToolMockRepository,
} from "../persistence/tool-repositories/input-mapping-mock-repository.js";
import { createConfiguredBackupStorage, createConfiguredProjectAssetStorage } from "../storage/r2-project-asset-storage.mjs";
import {
STORAGE_PROJECTS_PREFIX_LANES,
loadStorageConfig,
normalizeStorageProjectsPrefix,
} from "../storage/storage-config.mjs";
import { createPostgresBackup } from "../database/postgres-backup-service.mjs";
import {
GFSP_PACKAGE_REQUIRED_FILES,
GFSP_PACKAGE_FILENAME_PATTERN,
createProjectPackage,
projectPackageReadinessContract,
validateProjectPackage,
} from "../project-packages/project-package-service.mjs";
import {
TOOL_IMAGE_FALLBACK,
TOOL_RELEASE_CHANNELS,
TOOL_RELEASE_CHANNEL_HELP_TEXT,
TOOL_RELEASE_CHANNEL_LABELS,
TOOL_STATUS_MODEL,
getActiveToolRegistry,
getToolImageDiagnostics,
getToolImageSource,
getToolById,
getToolProgressReadiness,
getToolReleaseChannel,
getToolReleaseChannelLabel,
getToolRoute,
} from "../guest-seeds/tool-metadata-inventory.js";
import {
PALETTE_CATALOG_CONFIG,
} from "../persistence/tool-repositories/palette-catalog-config.js";
import {
PALETTE_SOURCE_USER,
PALETTE_TOOL_KEY,
PALETTE_WORKSPACE_PATH,
createGameWorkspacePaletteRepository,
normalizePaletteSwatchInput,
validatePaletteSwatchInput,
} from "../persistence/tool-repositories/palette-workspace-repository.js";
import {
GAME_CONFIGURATION_PLAYER_MODES,
GAME_CONFIGURATION_SECTIONS,
createGameConfigurationMockRepository,
} from "../persistence/tool-repositories/game-configuration-mock-repository.js";
import {
GAME_DESIGN_GAME_TYPES,
GAME_DESIGN_GENRES,
GAME_DESIGN_PLAYER_MODES,
GAME_DESIGN_PLAY_STYLES,
createGameDesignMockRepository,
} from "../persistence/tool-repositories/game-design-mock-repository.js";
import {
GAME_JOURNEY_KEYS,
GAME_JOURNEY_STATUS_BY_ID,
GAME_JOURNEY_STATUSES,
GAME_JOURNEY_RECOMMENDED_TARGETS,
GAME_JOURNEY_SUGGESTED_TOOLS,
GAME_JOURNEY_TOOL_OWNERSHIP_AREAS,
createGameJourneyMockRepository,
} from "../persistence/tool-repositories/game-journey-mock-repository.js";
import {
GAME_WORKSPACE_MEMBER_ROLES,
GAME_WORKSPACE_GAME_PURPOSES,
GAME_WORKSPACE_GAME_STATUSES,
createGameWorkspaceMockRepository,
} from "../persistence/tool-repositories/game-workspace-mock-repository.js";
import {
createMockDbAuditFields,
getMockDbTableSchemas,
getMockDbToolGroups,
normalizeMockDbTables,
} from "../persistence/mock-db-store.js";
import { createServerSeedTables } from "../seed/server-seed-loader.mjs";
import { SEED_DB_KEYS } from "../seed/seed-db-keys.mjs";
import {
MembershipAssignmentError,
assignUserMembership,
readMembershipCatalog,
resolveActiveUserMembership,
} from "../memberships/membership-assignment-service.mjs";
import {
OwnerMembershipSettingsError,
readOwnerMembershipSettings,
updateOwnerMembershipSettings,
} from "../memberships/owner-membership-settings-service.mjs";
import {
AiCreditError,
readAiCreditDisplay,
} from "../ai/ai-credit-service.mjs";
import {
OwnerAiCreditSettingsError,
readOwnerAiCreditSettings,
updateOwnerAiCreditSettings,
} from "../ai/owner-ai-credit-settings-service.mjs";
import {
MarketplaceEntitlementError,
readMarketplaceEntitlements,
} from "../marketplace/marketplace-entitlement-service.mjs";
import {
MarketplaceCategoryError,
readMarketplaceCategories,
} from "../marketplace/marketplace-category-service.mjs";
import {
MarketplaceRevenueError,
readMarketplaceSellerRevenueModel,
} from "../marketplace/marketplace-revenue-service.mjs";
import { handleAdminNotesDirectoryApiRequest } from "../admin/admin-notes-directory.mjs";
import {
createMessagesPostgresService,
handleMessagesApiContract,
} from "../messages/messages-postgres-service.mjs";
import {
LegalDocumentError,
readPublishedLegalDocument,
} from "../legal/legal-document-service.mjs";
import {
getAdminNavigationItems,
getOwnerNavigationItems,
} from "../../api/admin-owner-navigation.js";
import { createPaletteSourceMockDbRows } from "../guest-seeds/palette-source-mock-db.js";
import {
SUPABASE_AUTH_PROVIDER_ID,
SUPABASE_POSTGRES_PROVIDER_ID,
SUPABASE_POSTGRES_PRODUCT_TABLES,
SupabaseAuthProviderAdapter,
SupabasePostgresProviderAdapter,
createProviderContractSnapshot,
} from "../auth/provider-contract-stubs.mjs";
export const SERVER_DATA_BOUNDARY_RULE = "Browser -> Server API -> Data Source";
const FIXED_ACCOUNT_SESSION_MODE = Object.freeze({
adapterId: "supabase-postgres",
adapterName: "SupabasePostgresProviderAdapter",
configured: true,
environment: "Account",
id: "account-session",
label: "Account",
persistence: "Server account session",
selectableOnLocalLogin: false,
status: "fixed-runtime",
});
const AUTH_UNAVAILABLE_MESSAGE = "The site is currently unavailable. Please try again later.";
const AUTH_READY_MESSAGE = "Account service is available.";
const ACCOUNT_IDENTITY_SETUP_MESSAGE = "Account identity setup is incomplete. Please contact support.";
const PASSWORD_RESET_RATE_LIMIT_MESSAGE = "Too many reset requests. Please wait and try again later.";
const DEFAULT_SUPABASE_ACCOUNT_ROLE = Object.freeze({
description: "Default authenticated Creator role.",
isSystemRole: false,
name: "Creator",
roleSlug: "creator",
});
const IDENTITY_TABLES = ["users", "roles", "user_roles"];
const TOOLBOX_TABLES = ["toolbox_tool_metadata", "toolbox_tool_planning", "toolbox_votes"];
const TOOL_SNAPSHOT_PERSISTENCE_EXCLUDED_TABLES = new Set([
"platform_settings",
"support_categories",
"toolbox_tool_metadata",
"toolbox_tool_planning",
"toolbox_votes",
]);
const TOOLBOX_PLANNING_FIELDS = Object.freeze([
"progressChecklist",
"readiness",
"requiredForPlayable",
"requiredForPublish",
"requiredForTestable",
"requires",
]);
const DB_VIEWER_IDENTITY_TABLES = Object.freeze(["users", "user_roles", "roles"]);
const DB_VIEWER_TOOLBOX_VOTE_TABLES = Object.freeze(["toolbox_votes", "toolbox_vote_order"]);
const DB_VIEWER_STANDALONE_LABELS = Object.freeze({
toolbox_tool_metadata: "Tool Metadata",
toolbox_tool_planning: "Tool Planning",
toolbox_votes: "Toolbox Votes",
tool_state_samples: "Tool State Samples",
platform_settings: "Platform Settings",
support_categories: "Support Categories",
invitations: "Invites",
marketplace_categories: "Marketplace Categories",
user_roles: "Creator Responsibilities",
});
const DB_VIEWER_GROUP_ORDER = Object.freeze([
Object.freeze({ id: "asset", label: "Asset", ownerId: "asset", type: "tool" }),
Object.freeze({ id: "controls", label: "Controls", ownerId: "controls", type: "tool" }),
Object.freeze({ id: "game-configuration", label: "Game Configuration", ownerId: "game-configuration", type: "tool" }),
Object.freeze({ id: "game-design", label: "Game Design", ownerId: "game-design", type: "tool" }),
Object.freeze({ id: "game-journey", label: "Game Journey", ownerId: "game-journey", type: "tool" }),
Object.freeze({ id: "game-hub", label: "Game Hub", ownerId: "game-hub", type: "tool" }),
Object.freeze({ id: "objects", label: "Objects", ownerId: "objects", type: "tool" }),
Object.freeze({ id: "palette", label: "Palette", ownerId: "palette", type: "tool" }),
Object.freeze({ id: "tags", label: "Tags", ownerId: "tags", type: "tool" }),
Object.freeze({ id: "toolbox_tool_metadata", label: "Tool Metadata", tableNames: Object.freeze(["toolbox_tool_metadata"]), type: "table" }),
Object.freeze({ id: "toolbox_tool_planning", label: "Tool Planning", tableNames: Object.freeze(["toolbox_tool_planning"]), type: "table" }),
Object.freeze({ id: "tool_state_samples", label: "Tool State Samples", tableNames: Object.freeze(["tool_state_samples"]), type: "table" }),
Object.freeze({ id: "toolbox_votes", label: "Toolbox Votes", tableNames: DB_VIEWER_TOOLBOX_VOTE_TABLES, type: "table" }),
Object.freeze({ id: "invitations", label: "Invites", tableNames: Object.freeze(["invitations"]), type: "table" }),
Object.freeze({ id: "marketplace_categories", label: "Marketplace Categories", tableNames: Object.freeze(["marketplace_categories"]), type: "table" }),
Object.freeze({ id: "user_roles", label: "Creator Responsibilities", tableNames: DB_VIEWER_IDENTITY_TABLES, type: "table" }),
]);
const TOOLBOX_DEFAULT_RELEASE_CHANNELS = Object.freeze(["wireframe", "beta", "complete"]);
const BUILD_PATH_DEFAULT_RELEASE_CHANNELS = Object.freeze(["complete"]);
const TOOLBOX_RELEASE_CHANNEL_SWATCHES = Object.freeze({
planned: "swatch-gray",
wireframe: "swatch-blue",
beta: "swatch-gold",
complete: "swatch-green",
deprecated: "swatch-purple",
});
const TOOLBOX_ROLE_FOCUS_TOOLS = Object.freeze({
Owner: null,
Designer: Object.freeze(["Game Hub", "Game Journey", "Game Design", "Game Configuration", "Objects", "Worlds", "Characters", "Colors", "Assets", "Tags"]),
"World Builder": Object.freeze(["Worlds", "Objects", "Assets", "Colors", "Tags", "Animations"]),
Artist: Object.freeze(["Assets", "Colors", "Tags", "Fonts", "Sprites", "Characters", "Objects", "Animations"]),
"Audio Creator": Object.freeze(["Audio", "Music", "Voices", "MIDI", "Audio Effects", "Voice Capture", "Text To Speech", "Assets"]),
Translator: Object.freeze(["Languages", "Voices", "Voice Capture", "Text To Speech"]),
Tester: Object.freeze(["Game Testing", "Controls", "Hitboxes", "Debug", "Performance", "Events"]),
Publisher: Object.freeze(["Publish", "Marketplace", "Community", "Cloud", "Languages"]),
Viewer: Object.freeze(["Game Hub", "Game Journey", "Game Design", "Game Configuration", "Objects", "Worlds", "Assets", "Colors", "Tags", "Audio", "Publish", "Marketplace", "Community", "Languages", "Achievements", "Ratings"]),
});
const DB_ADAPTER_CONTRACT = Object.freeze({
contract: "GameFoundryDbAdapter",
rule: SERVER_DATA_BOUNDARY_RULE,
connections: Object.freeze([
Object.freeze({
adapterId: "account-session",
adapterName: "SupabaseAuthProviderAdapter",
connection: "account",
persistence: "server account session",
selectableOnLocalLogin: false,
status: "configured",
}),
Object.freeze({
adapterId: "product-data",
adapterName: "SupabasePostgresProviderAdapter",
connection: "product data",
persistence: "server product data",
selectableOnLocalLogin: false,
status: "configured",
}),
]),
});
const PLATFORM_BANNER_SETTING_KEYS = Object.freeze({
active: "platform.banner.enabled",
message: "platform.banner.message",
tone: "platform.banner.tone",
});
const PLATFORM_BANNER_TONES = Object.freeze(["info", "warning", "danger"]);
const PLATFORM_BANNER_DEFAULTS = Object.freeze({
active: false,
message: "",
tone: "info",
});
const PUBLIC_CONFIG_ENV_KEYS = Object.freeze({
apiUrl: "GAMEFOUNDRY_API_URL",
environmentLabel: "GAMEFOUNDRY_ENVIRONMENT_LABEL",
siteUrl: "GAMEFOUNDRY_SITE_URL",
});
const ENVIRONMENT_BANNER_SOURCE = "environment-config";
const ENVIRONMENT_LABEL_HIDDEN_VALUES = Object.freeze(["prd", "production"]);
const STORAGE_PROJECTS_PREFIX_ENV_KEY = "GAMEFOUNDRY_STORAGE_PROJECTS_PREFIX";
const SYSTEM_HEALTH_LIMIT_ENV_KEYS = Object.freeze([
Object.freeze({
key: "GAMEFOUNDRY_STORAGE_LIMIT_BYTES",
label: "Storage limit bytes",
service: "Project Asset Storage / R2",
}),
Object.freeze({
key: "GAMEFOUNDRY_STORAGE_CLASS_A_LIMIT_MONTHLY",
label: "Storage Class A monthly limit",
service: "Project Asset Storage / R2",
}),
Object.freeze({
key: "GAMEFOUNDRY_STORAGE_CLASS_B_LIMIT_MONTHLY",
label: "Storage Class B monthly limit",
service: "Project Asset Storage / R2",
}),
Object.freeze({
key: "GAMEFOUNDRY_DB_SIZE_LIMIT_BYTES",
label: "Local DB size limit bytes",
service: "Product Data / Local DB",
}),
Object.freeze({
key: "GAMEFOUNDRY_DB_CONNECTION_LIMIT",
label: "Local DB connection limit",
service: "Product Data / Local DB",
}),
]);
const SYSTEM_HEALTH_LIMIT_PRESSURE_LABELS = Object.freeze(["OK", "WATCH", "UPGRADE SOON", "RISK"]);
const RUNTIME_ENV_SECRET_MARKERS = Object.freeze([
"PASSWORD",
"SECRET",
"TOKEN",
"KEY",
"SERVICE_ROLE",
"JWT",
"DATABASE_URL",
]);
const LOCAL_API_STARTUP_DEFAULT_HOST = "127.0.0.1";
const LOCAL_API_STARTUP_DEFAULT_PORT = "5501";
const LOCAL_API_STARTUP_DEFAULT_PORT_BY_PROTOCOL = Object.freeze({
"http:": "80",
"https:": "443",
});
const LOCAL_API_PROCESS_STARTED_AT = new Date().toISOString();
const SYSTEM_HEALTH_API_CONTRACT_VERSION = "2026-06-24.system-health.v1";
const SYSTEM_HEALTH_USAGE_NOT_AVAILABLE = "NOT AVAILABLE";
const SYSTEM_HEALTH_USAGE_CONTRACTS = Object.freeze({
GAMEFOUNDRY_DB_CONNECTION_LIMIT: Object.freeze({
integrationPoint: "Future Local DB pool telemetry can report active connection count through the Local API.",
}),
GAMEFOUNDRY_DB_SIZE_LIMIT_BYTES: Object.freeze({
integrationPoint: "Future Local DB storage telemetry can report database bytes used through the Local API.",
}),
GAMEFOUNDRY_STORAGE_CLASS_A_LIMIT_MONTHLY: Object.freeze({
integrationPoint: "Future R2 provider telemetry can report monthly Class A operation count through the Local API.",
}),
GAMEFOUNDRY_STORAGE_CLASS_B_LIMIT_MONTHLY: Object.freeze({
integrationPoint: "Future R2 provider telemetry can report monthly Class B operation count through the Local API.",
}),
GAMEFOUNDRY_STORAGE_LIMIT_BYTES: Object.freeze({
integrationPoint: "Future R2 provider telemetry can report project asset storage bytes used through the Local API.",
}),
});
const STORAGE_CONNECTIVITY_ACTIONS = Object.freeze([
Object.freeze({ id: "storage-bucket-connectivity", label: "Bucket connectivity", operation: "bucket-connectivity" }),
Object.freeze({ id: "storage-list", label: "List", operation: "list" }),
Object.freeze({ id: "storage-upload-test-object", label: "Upload test object", operation: "upload" }),
Object.freeze({ id: "storage-write-test-object", label: "Write test object", operation: "upload" }),
Object.freeze({ id: "storage-read-test-object", label: "Read test object", operation: "read" }),
Object.freeze({ id: "storage-delete-test-object", label: "Delete test object", operation: "delete" }),
]);
const SYSTEM_HEALTH_STORAGE_ACTION_IDS = Object.freeze([
"storage-bucket-connectivity",
"storage-list",
"storage-upload-test-object",
"storage-read-test-object",
"storage-delete-test-object",
]);
const SYSTEM_HEALTH_STORAGE_EXPANDED_VALIDATION_ACTION_ID = "storage-expanded-validation";
const SYSTEM_HEALTH_MANUAL_ACTION_LABELS = Object.freeze({
"database-check": "Run Database Check",
"full-health-check": "Run Full Health Check",
refresh: "Refresh",
"runtime-check": "Run Runtime Check",
"storage-check": "Run Storage Check",
});
const SYSTEM_HEALTH_API_ENDPOINTS = Object.freeze([
Object.freeze({ method: "GET", path: "/api/runtime/health", purpose: "Read public-safe Local API runtime health JSON." }),
Object.freeze({ method: "GET", path: "/api/admin/system-health/status", purpose: "Read current deployment System Health status." }),
Object.freeze({ method: "POST", path: "/api/admin/system-health/action", purpose: "Run current deployment manual health actions." }),
Object.freeze({ method: "POST", path: "/api/admin/system-health/storage-connectivity-action", purpose: "Run current deployment R2 folder diagnostics." }),
]);
const ADMIN_API_REGISTRY_ENTRIES = Object.freeze([
Object.freeze({ method: "GET", owner: "Team Charlie", path: "/api/runtime/health", purpose: "Runtime health JSON contract" }),
Object.freeze({ method: "GET", owner: "Team Charlie", path: "/api/admin/system-health/status", purpose: "System Health status contract" }),
Object.freeze({ method: "POST", owner: "Team Charlie", path: "/api/admin/system-health/action", purpose: "System Health manual actions" }),
Object.freeze({ method: "POST", owner: "Team Charlie", path: "/api/admin/system-health/storage-connectivity-action", purpose: "System Health R2 diagnostics" }),
Object.freeze({ method: "GET", owner: "Team Charlie", path: "/api/admin/infrastructure/storage-path-status", purpose: "Infrastructure storage path status" }),
Object.freeze({ method: "POST", owner: "Team Charlie", path: "/api/admin/infrastructure/storage-connectivity-action", purpose: "Infrastructure R2 diagnostics" }),
Object.freeze({ method: "GET", owner: "Team Charlie", path: "/api/admin/operations/status", purpose: "Admin Operations status" }),
Object.freeze({ method: "POST", owner: "Team Charlie", path: "/api/admin/operations/action", purpose: "Admin Operations actions" }),
Object.freeze({ method: "GET", owner: "Shared Admin Navigation", path: "/api/navigation/admin-menu", purpose: "Admin navigation menu contract" }),
]);
const STORAGE_CONNECTIVITY_TEST_OBJECT_CONTENT = "Game Foundry Studio storage connectivity test object.\n";
const STORAGE_CONNECTIVITY_TEST_OBJECT_RELATIVE_PATH = "connectivity/storage-connectivity-test.txt";
const SYSTEM_HEALTH_ENVIRONMENT_MODELS = Object.freeze([
Object.freeze({
databaseModel: "Local Docker PostgreSQL",
hostingModel: "VS Code + Local API",
name: "Local",
storageFolder: "/local",
}),
Object.freeze({
databaseModel: "Local Docker PostgreSQL",
hostingModel: "Local Docker",
name: "DEV",
storageFolder: "/dev",
}),
Object.freeze({
databaseModel: "Local Docker PostgreSQL",
hostingModel: "Local Docker",
name: "IST",
storageFolder: "/ist",
}),
Object.freeze({
databaseModel: "Supabase PostgreSQL",
hostingModel: "Cloudflare",
name: "UAT",
storageFolder: "/uat",
}),
Object.freeze({
databaseModel: "Supabase PostgreSQL",
hostingModel: "Cloudflare",
name: "PRD",
storageFolder: "/prd",
}),
]);
const SYSTEM_HEALTH_ENVIRONMENT_BY_NAME = new Map(SYSTEM_HEALTH_ENVIRONMENT_MODELS.map((model) => [model.name, model]));
const SYSTEM_HEALTH_ENVIRONMENT_BY_FOLDER = new Map([
...SYSTEM_HEALTH_ENVIRONMENT_MODELS.map((model) => [model.storageFolder, model.name]),
["/prod", "PRD"],
]);
const ADMIN_OPERATION_GROUPS = Object.freeze([
Object.freeze({
id: "project-packaging",
label: "Project Packaging",
message: "Project package actions run through the Local API package contract. Browser controls only submit files and confirmations.",
actions: Object.freeze([
Object.freeze({
diagnostic: "Export Project Package creates a .gfsp ZIP package for the active Game Hub record and validates it before returning diagnostics.",
id: "export-project-package",
label: "Export Project Package",
mode: "server-package",
status: "PASS",
}),
Object.freeze({
diagnostic: "Validate Project Package inspects .gfsp integrity, required files, schema validity, compatibility, and asset references without importing.",
id: "validate-project-package",
label: "Validate Project Package",
mode: "server-package",
requiresPackageFile: true,
status: "PASS",
}),
Object.freeze({
confirmationMessage: "Replace Existing requires explicit confirmation before an existing project can be overwritten.",
confirmationPhrase: "REPLACE",
diagnostic: "Import Project Package validates first, detects project conflicts, and supports Replace Existing or Import As New Project without silent overwrite.",
id: "import-project-package",
label: "Import Project Package",
mode: "server-package",
risky: true,
confirmationRequired: true,
requiresPackageFile: true,
status: "WARN",
supportsImportModes: true,
}),
]),
}),
Object.freeze({
id: "backup-recovery",
label: "Backup & Recovery",
message: "Backup and recovery actions run through guarded Local API contracts with environment-aware restore restrictions.",
actions: Object.freeze([
Object.freeze({
diagnostic: "Create Backup validates the configured Local DB connection, runs server-side pg_dump --format=custom into temporary staging, uploads the .dump to the configured R2 backup prefix, then removes staging.",
id: "create-backup",
label: "Create Backup",
mode: "server-backup",
status: "PASS",
}),
Object.freeze({
confirmationMessage: "Restore From Backup is scaffold-only until server-side pg_restore safety is approved.",
confirmationPhrase: "RESTORE",
diagnostic: "Restore From Backup reports guarded not-implemented diagnostics and does not apply browser-uploaded backup data.",
id: "restore-from-backup",
label: "Restore From Backup",
mode: "server-backup",
risky: true,
confirmationRequired: true,
requiresBackupFile: true,
status: "WARN",
}),
]),
}),
Object.freeze({
id: "database-operations",
label: "Database Operations",
message: "Database actions use Local API checks or return guarded diagnostics.",
actions: Object.freeze([
Object.freeze({
diagnostic: "Validate Current Connection checks the configured account session and Local DB connection without changing data.",
id: "validate-current-connection",
label: "Validate Current Connection",
mode: "live-check",
status: "PASS",
}),
Object.freeze({
diagnostic: "Database Connectivity Test checks the configured Local DB connection without changing data.",
id: "database-connectivity-test",
label: "Database Connectivity Test",
mode: "live-check",
status: "PASS",
}),
Object.freeze({
confirmationMessage: "Run Migration is risky and must require explicit confirmation before migration execution is implemented.",
diagnostic: "Run Migration is not implemented from Admin Operations; use reviewed server-side migration scripts.",
id: "run-migration",
label: "Run Migration",
mode: "manual-only",
notImplemented: true,
risky: true,
confirmationRequired: true,
status: "SKIP",
}),
Object.freeze({
confirmationMessage: "Reseed DEV is destructive and is only available when the configured project storage lane resolves to DEV.",
devOnly: true,
diagnostic: "Reseed DEV is not implemented from Admin Operations; use reviewed DEV-only reseed scripts.",
id: "reseed-dev",
label: "Reseed DEV",
mode: "manual-only",
notImplemented: true,
risky: true,
confirmationRequired: true,
status: "SKIP",
}),
]),
}),
]);
function clone(value) {
return JSON.parse(JSON.stringify(value));
}
function parseEnvValue(value) {
const trimmed = value.trim();
const quote = trimmed[0];
if ((quote === "\"" || quote === "'") && trimmed.endsWith(quote)) {
return trimmed.slice(1, -1);
}
const commentIndex = trimmed.indexOf(" #");
return commentIndex === -1 ? trimmed : trimmed.slice(0, commentIndex).trim();
}
function dotEnvValue(key) {
const envPath = path.resolve(process.cwd(), ".env");
let contents = "";
try {
contents = readFileSync(envPath, "utf8");
} catch {
return { found: false, value: "" };
}
let foundValue = "";
let found = false;
contents.split(/\r?\n/).forEach((line) => {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) {
return;
}
const normalized = trimmed.startsWith("export ") ? trimmed.slice(7).trim() : trimmed;
const separatorIndex = normalized.indexOf("=");
if (separatorIndex <= 0) {
return;
}
const candidateKey = normalized.slice(0, separatorIndex).trim();
if (candidateKey !== key) {
return;
}
found = true;
foundValue = parseEnvValue(normalized.slice(separatorIndex + 1));
});
return { found, value: foundValue.trim() };
}
function storageProjectsPrefixStatus() {
const currentPath = dotEnvValue(STORAGE_PROJECTS_PREFIX_ENV_KEY);
const normalizedPath = normalizeStorageProjectsPrefix(currentPath.value);
const matchedLane = STORAGE_PROJECTS_PREFIX_LANES.find((lane) => lane.path === normalizedPath);
const invalidPath = !currentPath.found || !normalizedPath || !matchedLane;
const rows = STORAGE_PROJECTS_PREFIX_LANES.map((lane) => {
if (invalidPath) {
return {
...lane,
active: false,
status: "ERROR",
value: "ERROR",
};
}
const active = normalizedPath === lane.path;
return {
...lane,
active,
status: active ? "PASS" : "SKIP",
value: active ? "yes" : "no",
};
});
return {
configured: !invalidPath,
invalidPath,
missing: !currentPath.found || !normalizedPath,
rows,
secretsExposed: false,
status: invalidPath ? "ERROR" : "PASS",
variableName: STORAGE_PROJECTS_PREFIX_ENV_KEY,
};
}
function databaseConfigStatus(env = process.env) {
const databaseUrl = String(env.GAMEFOUNDRY_DATABASE_URL || "").trim();
const sslMode = String(env.GAMEFOUNDRY_DATABASE_SSL || "").trim().toLowerCase();
if (!databaseUrl) {
return {
configured: false,
databaseName: "not configured",
databaseNameStatus: "WARN",
host: "not configured",
hostStatus: "WARN",
port: "",
portStatus: "WARN",
sslMode: sslMode || "not configured",
sslModeStatus: sslMode ? "PASS" : "WARN",
};
}
try {
const parsedUrl = new URL(databaseUrl);
if (!["postgres:", "postgresql:"].includes(parsedUrl.protocol)) {
throw new Error("Database URL must use postgres:// or postgresql://.");
}
const databaseName = decodeURIComponent(parsedUrl.pathname.replace(/^\/+/, "") || "");
return {
configured: Boolean(parsedUrl.hostname && databaseName),
databaseName: databaseName || "not configured",
databaseNameStatus: databaseName ? "PASS" : "WARN",
host: parsedUrl.hostname || "not configured",
hostStatus: parsedUrl.hostname ? "PASS" : "WARN",
port: Number(parsedUrl.port || 5432),
portStatus: "PASS",
sslMode: sslMode || "not configured",
sslModeStatus: sslMode ? "PASS" : "WARN",
};
} catch {
return {
configured: false,
databaseName: "invalid database URL",
databaseNameStatus: "FAIL",
host: "invalid database URL",
hostStatus: "FAIL",
port: "",
portStatus: "FAIL",
sslMode: sslMode || "not configured",
sslModeStatus: sslMode ? "PASS" : "WARN",
};
}
}
function systemHealthPostgresMetrics(databaseStatus = {}, checkedAt = new Date().toISOString()) {
const reason = databaseStatus.message || "Postgres metrics are reported only when the current environment database reader returns safe values.";
const tableCount = Number(databaseStatus.tableCount);
const metricRows = [
{
metric: "Connection status",
status: databaseStatus.connectivityStatus || databaseStatus.status || "WARN",
value: databaseStatus.connectivity || "Unavailable",
},
{
metric: "Database name",
status: databaseStatus.currentDatabaseNameStatus || databaseStatus.databaseNameStatus || "WARN",
value: databaseStatus.currentDatabaseName || databaseStatus.databaseName || "Unavailable",
},
{
metric: "Current schema",
status: databaseStatus.currentSchemaStatus || "WARN",
value: databaseStatus.currentSchema || "Unavailable",
},
{
metric: "Migration status",
status: databaseStatus.migrationStatus || "WARN",
value: databaseStatus.migrationStatus === "PASS"
? `DDL=${databaseStatus.migrationCounts?.DDL || 0}; DML=${databaseStatus.migrationCounts?.DML || 0}`
: "Unavailable",
},
{
metric: "Last migration",
status: databaseStatus.lastMigrationStatus || "WARN",
value: databaseStatus.lastMigration?.name || "Unavailable",
},
{
metric: "Table count",
status: Number.isFinite(tableCount) ? "PASS" : "WARN",
value: Number.isFinite(tableCount) ? String(tableCount) : "Unavailable",
},
{
metric: "Database size",
status: databaseStatus.databaseSizeStatus || "WARN",
value: databaseStatus.databaseSize || "Unavailable",
},
{
metric: "Last checked",
status: databaseStatus.lastChecked ? "PASS" : "WARN",
value: databaseStatus.lastChecked || checkedAt || "Unavailable",
},
];
return {
lastChecked: databaseStatus.lastChecked || checkedAt,
message: reason,
rows: metricRows,
secretEditingAllowed: false,
secretsExposed: false,
status: overallHealthStatus(metricRows),
};
}
function projectPackageReadinessStatus() {
const decisionPath = path.join(process.cwd(), "docs_build", "codex", "decisions", "project-packages.md");
const contract = projectPackageReadinessContract();
try {
const contents = readFileSync(decisionPath, "utf8");
const requiredContent = [
".gfsp",
"Game Foundry Studio Project",
"ZIP-based package format",
"<ProjectNameWithoutSpaces>-<YYJJJ>-<sequence>.gfsp",
"metadata/package.json",
"project/project.json",
"assets/asset-references.json",
"Export Project Package",
"Import Project Package",
"Validate Project Package",
];
const missing = requiredContent.filter((item) => !contents.includes(item));
return {
contract,
decisionPath: "docs_build/codex/decisions/project-packages.md",
message: missing.length
? `Project package decision note is missing: ${missing.join(", ")}.`
: "Project package decision note and runtime scaffold are ready for .gfsp export/import/validate package workflows.",
status: missing.length ? "WARN" : "PASS",
};
} catch {
return {
contract,
decisionPath: "docs_build/codex/decisions/project-packages.md",
message: "Project package decision note is missing. Restore docs_build/codex/decisions/project-packages.md.",
status: "WARN",
};
}
}
function parsePositiveIntegerConfig(rawValue) {
const value = String(rawValue || "").trim();
if (!/^[1-9]\d*$/.test(value)) {
return null;
}
const numberValue = Number(value);
return Number.isSafeInteger(numberValue) ? numberValue : null;
}
function systemHealthConfiguredLimit(limit) {
const configuredLimit = dotEnvValue(limit.key);
if (!configuredLimit.found || !configuredLimit.value) {
return {
message: `Set ${limit.key} in the selected .env.<target> copy-source, copy it to .env, and restart validation.`,
numericValue: null,
status: "WARN",
value: "not configured",
};
}
const numericValue = parsePositiveIntegerConfig(configuredLimit.value);
if (numericValue === null) {
return {
message: `${limit.key} must be a positive integer value in bytes, operations, or connection count as applicable.`,
numericValue: null,
status: "WARN",
value: configuredLimit.value,
};
}
return {
message: `${limit.key} is configured with a positive integer value.`,
numericValue,
status: "PASS",
value: configuredLimit.value,
};
}
function systemHealthCurrentUsage(limit) {
const contract = SYSTEM_HEALTH_USAGE_CONTRACTS[limit.key] || {};
return {
integrationPoint: contract.integrationPoint || "Future provider telemetry can report usage through the Local API.",
numericValue: null,
status: SYSTEM_HEALTH_USAGE_NOT_AVAILABLE,
value: SYSTEM_HEALTH_USAGE_NOT_AVAILABLE,
};
}
function systemHealthPressure(configuredLimit, currentUsage) {
if (configuredLimit.numericValue === null || currentUsage.numericValue === null) {
return {
calculated: false,
label: SYSTEM_HEALTH_USAGE_NOT_AVAILABLE,
status: SYSTEM_HEALTH_USAGE_NOT_AVAILABLE,
};
}
const ratio = currentUsage.numericValue / configuredLimit.numericValue;
if (ratio >= 0.95) {
return { calculated: true, label: "RISK", status: "RISK" };
}
if (ratio >= 0.85) {
return { calculated: true, label: "UPGRADE SOON", status: "UPGRADE SOON" };
}
if (ratio >= 0.7) {
return { calculated: true, label: "WATCH", status: "WATCH" };
}
return { calculated: true, label: "OK", status: "OK" };
}
function systemHealthLimitRows() {
return SYSTEM_HEALTH_LIMIT_ENV_KEYS.map((limit) => {
const configuredLimit = systemHealthConfiguredLimit(limit);
const currentUsage = systemHealthCurrentUsage(limit);
const pressure = systemHealthPressure(configuredLimit, currentUsage);
return {
area: limit.service,
configuredLimit,
currentUsage,
field: limit.label,
limit: configuredLimit.value,
nextStep: configuredLimit.status === "PASS"
? currentUsage.integrationPoint
: configuredLimit.message,
pressure: pressure.label,
pressureCalculation: pressure,
pressureLabels: SYSTEM_HEALTH_LIMIT_PRESSURE_LABELS,
status: configuredLimit.status,
usage: currentUsage.value,
variableName: limit.key,
};
});
}
function systemHealthLimitStatus(rows) {
return rows.some((row) => row.status !== "PASS") ? "WARN" : "PASS";
}
function normalizeHealthStatus(status) {
const normalized = String(status || "").toUpperCase();
if (normalized === "ERROR") {
return "FAIL";
}
if (normalized === "PASS" || normalized === "WARN" || normalized === "FAIL") {
return normalized;
}
return "WARN";
}
function systemHealthCounts(rows) {
return rows.reduce((counts, row) => {
counts[normalizeHealthStatus(row.status)] += 1;
return counts;
}, { FAIL: 0, PASS: 0, WARN: 0 });
}
function overallHealthStatus(rows) {
const statuses = rows.map((row) => normalizeHealthStatus(row.status));
if (statuses.includes("FAIL")) {
return "FAIL";
}
if (statuses.includes("WARN")) {
return "WARN";
}
return "PASS";
}
function localApiStartupPortFromUrl(value) {
const rawValue = String(value || "").trim();
if (!rawValue) {
return "not configured";
}
try {
const parsedUrl = new URL(rawValue);
return parsedUrl.port || LOCAL_API_STARTUP_DEFAULT_PORT_BY_PROTOCOL[parsedUrl.protocol] || "not configured";
} catch {
return "invalid URL";
}
}
function localApiStartupUrlDisplay(value, fallback = "not configured") {
const rawValue = String(value || "").trim();
if (!rawValue) {
return fallback;
}
try {
const parsedUrl = new URL(rawValue);
if (parsedUrl.username) {
parsedUrl.username = "********";
}
if (parsedUrl.password) {
parsedUrl.password = "********";
}
parsedUrl.search = "";
parsedUrl.hash = "";
return parsedUrl.toString();
} catch {
return "invalid URL";
}
}
function localApiStartupBindTarget(env = process.env) {
const host = String(env.GAMEFOUNDRY_LOCAL_API_HOST || LOCAL_API_STARTUP_DEFAULT_HOST).trim() || LOCAL_API_STARTUP_DEFAULT_HOST;
const port = String(env.GAMEFOUNDRY_LOCAL_API_PORT || LOCAL_API_STARTUP_DEFAULT_PORT).trim() || LOCAL_API_STARTUP_DEFAULT_PORT;
const portStatus = /^[1-9]\d*$/.test(port) ? "PASS" : "WARN";
return {
host,
port,
status: portStatus,
value: `${host}:${port}`,
};
}
function systemHealthLocalApiStartupDiagnostics(env = process.env) {
const bindTarget = localApiStartupBindTarget(env);
const configuredApiUrl = String(env.GAMEFOUNDRY_API_URL || "").trim();
const derivedApiUrl = `http://${bindTarget.value}/api`;
const siteUrl = String(env.GAMEFOUNDRY_SITE_URL || "").trim();
const rows = [
{
field: "Approved diagnostics format",
reason: "Startup output includes deterministic Environment Variables and All Runtime Ports sections.",
status: "PASS",
value: "Environment Variables + All Runtime Ports",
},
{
field: "Environment variable diagnostics",
reason: "Startup output masks secret-like values and redacts URL credentials before printing.",
status: "PASS",
value: "masked and redacted",
},
{
field: "Configured startup bind target",
reason: bindTarget.status === "PASS"
? "Local API startup uses the configured or default host and port for the bind target."
: "GAMEFOUNDRY_LOCAL_API_PORT must be a positive integer.",
status: bindTarget.status,
value: bindTarget.value,
},
{
field: "Configured site URL",
reason: siteUrl
? "GAMEFOUNDRY_SITE_URL is available for startup diagnostics."
: "GAMEFOUNDRY_SITE_URL is not configured; startup diagnostics will print not configured.",
status: siteUrl ? "PASS" : "WARN",
value: localApiStartupUrlDisplay(siteUrl),
},
{
field: "Configured API URL",
reason: configuredApiUrl
? "GAMEFOUNDRY_API_URL is configured and displayed without URL credentials."
: "GAMEFOUNDRY_API_URL is not configured; startup diagnostics derive /api from the bind target.",
status: "PASS",
value: localApiStartupUrlDisplay(configuredApiUrl || derivedApiUrl),
},
{
field: "Configured API URL port",
reason: "Port is derived from the configured or startup-derived API URL for display only.",
status: "PASS",
value: localApiStartupPortFromUrl(configuredApiUrl || derivedApiUrl),
},
{
field: "Configurable multiple runtime ports",
reason: "Configurable multiple runtime ports are explicitly deferred/cancelled for this PR.",
status: "PENDING",
value: "deferred/cancelled",
},
];
const actionableRows = rows.filter((row) => row.status !== "PENDING");
return {
message: "Local API startup diagnostics use the approved safe output format; configurable multiple runtime ports remain deferred.",
rows,
secretEditingAllowed: false,
secretsExposed: false,
status: overallHealthStatus(actionableRows),
};
}
function systemHealthEnvironmentMap() {
return SYSTEM_HEALTH_ENVIRONMENT_MODELS.map((model) => ({ ...model }));
}
function systemHealthEnvironmentComparison({ checkedAt = new Date().toISOString(), environmentIdentity = {} } = {}) {
const currentEnvironmentName = normalizeEnvironmentName(environmentIdentity.name);
const comparisonModels = [
{
canonicalName: "Local",
databaseModel: "Local Docker PostgreSQL",
displayName: "Local (VS Code)",
hostingModel: "VS Code + Local API",
runtimeExpectation: "Local static server + Local API + developer workstation",
storageFolder: "/local",
},
{
canonicalName: "DEV",