@latticexyz/cli 2.0.0-alpha.78 → 2.0.0-alpha.79

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 (52) hide show
  1. package/dist/{chunk-DO7OWTMM.js → chunk-K25KS5QJ.js} +2 -4
  2. package/dist/{chunk-TPZUS44H.js → chunk-SADK4UCO.js} +1 -1
  3. package/dist/{chunk-KPBNUPK6.js → chunk-SKNB74MT.js} +155 -159
  4. package/dist/{chunk-TLEAEDUA.js → chunk-WZFBU6KC.js} +36 -36
  5. package/dist/{chunk-XUNWAEP7.js → chunk-YNVRICE5.js} +59 -36
  6. package/dist/index.d.ts +2 -4
  7. package/dist/index.js +0 -22
  8. package/dist/mud.js +5 -7
  9. package/dist/mud2.js +5 -7
  10. package/dist/render-solidity/index.d.ts +1 -2
  11. package/dist/render-solidity/index.js +2 -3
  12. package/dist/render-ts/index.d.ts +1 -2
  13. package/dist/render-ts/index.js +2 -3
  14. package/dist/utils/index.d.ts +2 -15
  15. package/dist/utils/index.js +3 -14
  16. package/package.json +12 -14
  17. package/src/commands/deploy-v2.ts +3 -3
  18. package/src/commands/set-version.ts +3 -2
  19. package/src/commands/tablegen.ts +1 -1
  20. package/src/commands/tsgen.ts +1 -1
  21. package/src/commands/worldgen.ts +1 -2
  22. package/src/index.ts +1 -15
  23. package/src/render-solidity/renderTypesFromConfig.ts +1 -1
  24. package/src/render-solidity/tableOptions.ts +1 -1
  25. package/src/render-solidity/tablegen.ts +1 -1
  26. package/src/render-solidity/userType.ts +1 -2
  27. package/src/render-solidity/worldgen.ts +1 -1
  28. package/src/render-ts/recsV1TableOptions.ts +1 -1
  29. package/src/render-ts/tsgen.ts +1 -1
  30. package/src/utils/contractToInterface.ts +1 -1
  31. package/src/utils/deploy-v2.ts +2 -2
  32. package/src/utils/errors.ts +3 -23
  33. package/dist/chunk-5NC2OON2.js +0 -164
  34. package/dist/chunk-MN3HYFJK.js +0 -442
  35. package/dist/config/index.d.ts +0 -409
  36. package/dist/config/index.js +0 -85
  37. package/dist/parseStoreConfig-8aa69ac9.d.ts +0 -377
  38. package/src/config/commonSchemas.ts +0 -34
  39. package/src/config/dynamicResolution.ts +0 -49
  40. package/src/config/index.ts +0 -24
  41. package/src/config/loadConfig.ts +0 -40
  42. package/src/config/loadStoreConfig.ts +0 -18
  43. package/src/config/parseStoreConfig.test-d.ts +0 -40
  44. package/src/config/parseStoreConfig.ts +0 -317
  45. package/src/config/validation.ts +0 -163
  46. package/src/config/world/index.ts +0 -4
  47. package/src/config/world/loadWorldConfig.test-d.ts +0 -11
  48. package/src/config/world/loadWorldConfig.ts +0 -26
  49. package/src/config/world/parseWorldConfig.ts +0 -56
  50. package/src/config/world/resolveWorldConfig.ts +0 -80
  51. package/src/config/world/userTypes.ts +0 -74
  52. package/src/utils/typeUtils.ts +0 -17
@@ -1,317 +0,0 @@
1
- import { AbiType, AbiTypes, StaticAbiType, StaticAbiTypes } from "@latticexyz/schema-type";
2
- import { RefinementCtx, z, ZodIssueCode } from "zod";
3
- import { AsDependent, ExtractUserTypes, RequireKeys, StaticArray, StringForUnion } from "../utils/typeUtils.js";
4
- import { zObjectName, zSelector, zUserEnum, zValueName } from "./commonSchemas.js";
5
- import { getDuplicates, parseStaticArray } from "./validation.js";
6
-
7
- const zTableName = zObjectName;
8
- const zKeyName = zValueName;
9
- const zColumnName = zValueName;
10
- const zUserEnumName = zObjectName;
11
-
12
- // Fields can use AbiType or one of user-defined wrapper types
13
- // (user types are refined later, based on the appropriate config options)
14
- const zFieldData = z.string();
15
-
16
- type FieldData<UserTypes extends StringForUnion> = AbiType | StaticArray | UserTypes;
17
-
18
- // Primary keys allow only static types
19
- // (user types are refined later, based on the appropriate config options)
20
- const zPrimaryKey = z.string();
21
- const zPrimaryKeys = z.record(zKeyName, zPrimaryKey).default({ key: "bytes32" });
22
-
23
- type PrimaryKey<StaticUserTypes extends StringForUnion> = StaticAbiType | StaticUserTypes;
24
-
25
- /************************************************************************
26
- *
27
- * TABLE SCHEMA
28
- *
29
- ************************************************************************/
30
-
31
- export type FullSchemaConfig<UserTypes extends StringForUnion = StringForUnion> = Record<string, FieldData<UserTypes>>;
32
- export type ShorthandSchemaConfig<UserTypes extends StringForUnion = StringForUnion> = FieldData<UserTypes>;
33
- export type SchemaConfig<UserTypes extends StringForUnion = StringForUnion> =
34
- | FullSchemaConfig<UserTypes>
35
- | ShorthandSchemaConfig<UserTypes>;
36
-
37
- const zFullSchemaConfig = z
38
- .record(zColumnName, zFieldData)
39
- .refine((arg) => Object.keys(arg).length > 0, "Table schema may not be empty");
40
-
41
- const zShorthandSchemaConfig = zFieldData.transform((fieldData) => {
42
- return zFullSchemaConfig.parse({
43
- value: fieldData,
44
- });
45
- });
46
-
47
- export const zSchemaConfig = zFullSchemaConfig.or(zShorthandSchemaConfig);
48
-
49
- /************************************************************************
50
- *
51
- * TABLE
52
- *
53
- ************************************************************************/
54
-
55
- export interface TableConfig<
56
- UserTypes extends StringForUnion = StringForUnion,
57
- StaticUserTypes extends StringForUnion = StringForUnion
58
- > {
59
- /** Output directory path for the file. Default is "tables" */
60
- directory?: string;
61
- /**
62
- * The fileSelector is used with the namespace to register the table and construct its id.
63
- * The table id will be uint256(bytes32(abi.encodePacked(bytes16(namespace), bytes16(fileSelector)))).
64
- * Default is "<tableName>"
65
- * */
66
- fileSelector?: string;
67
- /** Make methods accept `tableId` argument instead of it being a hardcoded constant. Default is false */
68
- tableIdArgument?: boolean;
69
- /** Include methods that accept a manual `IStore` argument. Default is true. */
70
- storeArgument?: boolean;
71
- /** Include a data struct and methods for it. Default is false for 1-column tables; true for multi-column tables. */
72
- dataStruct?: boolean;
73
- /** Table's primary key names mapped to their types. Default is `{ key: "bytes32" }` */
74
- primaryKeys?: Record<string, PrimaryKey<StaticUserTypes>>;
75
- /** Table's column names mapped to their types. Table name's 1st letter should be lowercase. */
76
- schema: SchemaConfig<UserTypes>;
77
- }
78
-
79
- const zFullTableConfig = z
80
- .object({
81
- directory: z.string().default("tables"),
82
- fileSelector: zSelector.optional(),
83
- tableIdArgument: z.boolean().default(false),
84
- storeArgument: z.boolean().default(true),
85
- primaryKeys: zPrimaryKeys,
86
- schema: zSchemaConfig,
87
- dataStruct: z.boolean().optional(),
88
- })
89
- .transform((arg) => {
90
- // default dataStruct value depends on schema's length
91
- if (Object.keys(arg.schema).length === 1) {
92
- arg.dataStruct ??= false;
93
- } else {
94
- arg.dataStruct ??= true;
95
- }
96
- return arg as RequireKeys<typeof arg, "dataStruct">;
97
- });
98
-
99
- const zShorthandTableConfig = zFieldData.transform((fieldData) => {
100
- return zFullTableConfig.parse({
101
- schema: {
102
- value: fieldData,
103
- },
104
- });
105
- });
106
-
107
- export const zTableConfig = zFullTableConfig.or(zShorthandTableConfig);
108
-
109
- /************************************************************************
110
- *
111
- * TABLES
112
- *
113
- ************************************************************************/
114
-
115
- export type TablesConfig<
116
- UserTypes extends StringForUnion = StringForUnion,
117
- StaticUserTypes extends StringForUnion = StringForUnion
118
- > = Record<string, TableConfig<UserTypes, StaticUserTypes> | FieldData<UserTypes>>;
119
-
120
- export const zTablesConfig = z.record(zTableName, zTableConfig).transform((tables) => {
121
- // default fileSelector depends on tableName
122
- for (const tableName of Object.keys(tables)) {
123
- const table = tables[tableName];
124
- table.fileSelector ??= tableName;
125
-
126
- tables[tableName] = table;
127
- }
128
- return tables as Record<string, RequireKeys<(typeof tables)[string], "fileSelector">>;
129
- });
130
-
131
- /************************************************************************
132
- *
133
- * USER TYPES
134
- *
135
- ************************************************************************/
136
-
137
- export type EnumsConfig<EnumNames extends StringForUnion> = never extends EnumNames
138
- ? {
139
- /**
140
- * Enum names mapped to lists of their member names
141
- *
142
- * (enums are inferred to be absent)
143
- */
144
- enums?: Record<EnumNames, string[]>;
145
- }
146
- : StringForUnion extends EnumNames
147
- ? {
148
- /**
149
- * Enum names mapped to lists of their member names
150
- *
151
- * (enums aren't inferred - use `mudConfig` or `storeConfig` helper, and `as const` for variables)
152
- */
153
- enums?: Record<EnumNames, string[]>;
154
- }
155
- : {
156
- /**
157
- * Enum names mapped to lists of their member names
158
- *
159
- * Enums defined here can be used as types in table schemas/keys
160
- */
161
- enums: Record<EnumNames, string[]>;
162
- };
163
-
164
- export const zEnumsConfig = z.object({
165
- enums: z.record(zUserEnumName, zUserEnum).default({}),
166
- });
167
-
168
- /************************************************************************
169
- *
170
- * FINAL
171
- *
172
- ************************************************************************/
173
-
174
- // zod doesn't preserve doc comments
175
- export type StoreUserConfig<
176
- EnumNames extends StringForUnion = StringForUnion,
177
- StaticUserTypes extends ExtractUserTypes<EnumNames> = ExtractUserTypes<EnumNames>
178
- > = EnumsConfig<EnumNames> & {
179
- /** The namespace for table ids. Default is "" (empty string) */
180
- namespace?: string;
181
- /** Path for store package imports. Default is "@latticexyz/store/src/" */
182
- storeImportPath?: string;
183
- /**
184
- * Configuration for each table.
185
- *
186
- * The key is the table name (capitalized).
187
- *
188
- * The value:
189
- * - abi or user type for a single-value table.
190
- * - FullTableConfig object for multi-value tables (or for customizable options).
191
- */
192
- tables: TablesConfig<AsDependent<StaticUserTypes>, AsDependent<StaticUserTypes>>;
193
- /** Path to the file where common user types will be generated and imported from. Default is "Types" */
194
- userTypesPath?: string;
195
- /** Path to the directory where generated files will be placed. (Default is "codegen") */
196
- codegenDirectory?: string;
197
- };
198
-
199
- /** Type helper for defining StoreUserConfig */
200
- export function storeConfig<
201
- // (`never` is overridden by inference, so only the defined enums can be used by default)
202
- EnumNames extends StringForUnion = never,
203
- StaticUserTypes extends ExtractUserTypes<EnumNames> = ExtractUserTypes<EnumNames>
204
- >(config: StoreUserConfig<EnumNames, StaticUserTypes>) {
205
- return config;
206
- }
207
-
208
- export type StoreConfig = z.output<typeof zStoreConfig>;
209
-
210
- const StoreConfigUnrefined = z
211
- .object({
212
- namespace: zSelector.default(""),
213
- storeImportPath: z.string().default("@latticexyz/store/src/"),
214
- tables: zTablesConfig,
215
- userTypesPath: z.string().default("Types"),
216
- codegenDirectory: z.string().default("codegen"),
217
- })
218
- .merge(zEnumsConfig);
219
-
220
- // finally validate global conditions
221
- export const zStoreConfig = StoreConfigUnrefined.superRefine(validateStoreConfig);
222
-
223
- export function parseStoreConfig(config: unknown) {
224
- return zStoreConfig.parse(config);
225
- }
226
-
227
- /************************************************************************
228
- *
229
- * HELPERS
230
- *
231
- ************************************************************************/
232
-
233
- // Validate conditions that check multiple different config options simultaneously
234
- function validateStoreConfig(config: z.output<typeof StoreConfigUnrefined>, ctx: RefinementCtx) {
235
- // Local table variables must be unique within the table
236
- for (const table of Object.values(config.tables)) {
237
- const primaryKeyNames = Object.keys(table.primaryKeys);
238
- const fieldNames = Object.keys(table.schema);
239
- const duplicateVariableNames = getDuplicates([...primaryKeyNames, ...fieldNames]);
240
- if (duplicateVariableNames.length > 0) {
241
- ctx.addIssue({
242
- code: ZodIssueCode.custom,
243
- message: `Field and primary key names within one table must be unique: ${duplicateVariableNames.join(", ")}`,
244
- });
245
- }
246
- }
247
- // Global names must be unique
248
- const tableNames = Object.keys(config.tables);
249
- const staticUserTypeNames = Object.keys(config.enums);
250
- const userTypeNames = staticUserTypeNames;
251
- const globalNames = [...tableNames, ...userTypeNames];
252
- const duplicateGlobalNames = getDuplicates(globalNames);
253
- if (duplicateGlobalNames.length > 0) {
254
- ctx.addIssue({
255
- code: ZodIssueCode.custom,
256
- message: `Table, enum names must be globally unique: ${duplicateGlobalNames.join(", ")}`,
257
- });
258
- }
259
- // User types must exist
260
- for (const table of Object.values(config.tables)) {
261
- for (const primaryKeyType of Object.values(table.primaryKeys)) {
262
- validateStaticAbiOrUserType(staticUserTypeNames, primaryKeyType, ctx);
263
- }
264
- for (const fieldType of Object.values(table.schema)) {
265
- validateAbiOrUserType(userTypeNames, staticUserTypeNames, fieldType, ctx);
266
- }
267
- }
268
- }
269
-
270
- function validateAbiOrUserType(
271
- userTypeNames: string[],
272
- staticUserTypeNames: string[],
273
- type: string,
274
- ctx: RefinementCtx
275
- ) {
276
- if (!(AbiTypes as string[]).includes(type) && !userTypeNames.includes(type)) {
277
- const staticArray = parseStaticArray(type);
278
- if (staticArray) {
279
- validateStaticArray(staticUserTypeNames, staticArray.elementType, staticArray.staticLength, ctx);
280
- } else {
281
- ctx.addIssue({
282
- code: ZodIssueCode.custom,
283
- message: `${type} is not a valid abi type, and is not defined in userTypes`,
284
- });
285
- }
286
- }
287
- }
288
-
289
- function validateStaticAbiOrUserType(staticUserTypeNames: string[], type: string, ctx: RefinementCtx) {
290
- if (!(StaticAbiTypes as string[]).includes(type) && !staticUserTypeNames.includes(type)) {
291
- ctx.addIssue({
292
- code: ZodIssueCode.custom,
293
- message: `${type} is not a static type`,
294
- });
295
- }
296
- }
297
-
298
- function validateStaticArray(
299
- staticUserTypeNames: string[],
300
- elementType: string,
301
- staticLength: number,
302
- ctx: RefinementCtx
303
- ) {
304
- validateStaticAbiOrUserType(staticUserTypeNames, elementType, ctx);
305
-
306
- if (staticLength === 0) {
307
- ctx.addIssue({
308
- code: ZodIssueCode.custom,
309
- message: `Static array length must not be 0`,
310
- });
311
- } else if (staticLength >= 2 ** 16) {
312
- ctx.addIssue({
313
- code: ZodIssueCode.custom,
314
- message: `Static array length must be less than 2**16`,
315
- });
316
- }
317
- }
@@ -1,163 +0,0 @@
1
- import { ethers } from "ethers";
2
- import { ZodIssueCode, RefinementCtx } from "zod";
3
-
4
- export function validateName(name: string, ctx: RefinementCtx) {
5
- if (!/^\w+$/.test(name)) {
6
- ctx.addIssue({
7
- code: ZodIssueCode.custom,
8
- message: `Name must contain only alphanumeric & underscore characters`,
9
- });
10
- }
11
- }
12
-
13
- export function validateCapitalizedName(name: string, ctx: RefinementCtx) {
14
- validateName(name, ctx);
15
-
16
- if (!/^[A-Z]/.test(name)) {
17
- ctx.addIssue({
18
- code: ZodIssueCode.custom,
19
- message: `Name must start with a capital letter`,
20
- });
21
- }
22
- }
23
-
24
- export function validateUncapitalizedName(name: string, ctx: RefinementCtx) {
25
- validateName(name, ctx);
26
-
27
- if (!/^[a-z]/.test(name)) {
28
- ctx.addIssue({
29
- code: ZodIssueCode.custom,
30
- message: `Name must start with a lowercase letter`,
31
- });
32
- }
33
- }
34
-
35
- // validates only the enum array, not the names of enum members
36
- export function validateEnum(members: string[], ctx: RefinementCtx) {
37
- if (members.length === 0) {
38
- ctx.addIssue({
39
- code: ZodIssueCode.custom,
40
- message: `Enum must not be empty`,
41
- });
42
- }
43
- if (members.length >= 256) {
44
- ctx.addIssue({
45
- code: ZodIssueCode.custom,
46
- message: `Length of enum must be < 256`,
47
- });
48
- }
49
-
50
- const duplicates = getDuplicates(members);
51
- if (duplicates.length > 0) {
52
- ctx.addIssue({
53
- code: ZodIssueCode.custom,
54
- message: `Enum must not have duplicate names for: ${duplicates.join(", ")}`,
55
- });
56
- }
57
- }
58
-
59
- function _factoryForValidateRoute(requireNonEmpty: boolean, requireSingleLevel: boolean) {
60
- return (route: string, ctx: RefinementCtx) => {
61
- if (route === "") {
62
- if (requireNonEmpty) {
63
- ctx.addIssue({
64
- code: ZodIssueCode.custom,
65
- message: `Route must not be empty`,
66
- });
67
- }
68
- // we can skip further validation for empty routes
69
- return;
70
- }
71
-
72
- if (route[0] !== "/") {
73
- ctx.addIssue({
74
- code: ZodIssueCode.custom,
75
- message: `Route must start with "/"`,
76
- });
77
- }
78
-
79
- if (route[route.length - 1] === "/") {
80
- ctx.addIssue({
81
- code: ZodIssueCode.custom,
82
- message: `Route must not end with "/"`,
83
- });
84
- }
85
-
86
- const parts = route.split("/");
87
- if (requireSingleLevel && parts.length > 2) {
88
- ctx.addIssue({
89
- code: ZodIssueCode.custom,
90
- message: `Route must only have one level (e.g. "/foo")`,
91
- });
92
- }
93
-
94
- // start at 1 to skip the first empty part
95
- for (let i = 1; i < parts.length; i++) {
96
- if (parts[i] === "") {
97
- ctx.addIssue({
98
- code: ZodIssueCode.custom,
99
- message: `Route must not contain empty route fragments (e.g. "//")`,
100
- });
101
- }
102
-
103
- if (!/^\w+$/.test(parts[i])) {
104
- ctx.addIssue({
105
- code: ZodIssueCode.custom,
106
- message: `Route must contain only alphanumeric & underscore characters`,
107
- });
108
- }
109
- }
110
- };
111
- }
112
-
113
- export const validateRoute = _factoryForValidateRoute(true, false);
114
-
115
- export const validateBaseRoute = _factoryForValidateRoute(false, false);
116
-
117
- export const validateSingleLevelRoute = _factoryForValidateRoute(true, true);
118
-
119
- export function validateEthereumAddress(address: string, ctx: RefinementCtx) {
120
- if (!ethers.utils.isAddress(address)) {
121
- ctx.addIssue({
122
- code: ZodIssueCode.custom,
123
- message: `Address must be a valid Ethereum address`,
124
- });
125
- }
126
- }
127
-
128
- export function getDuplicates<T>(array: T[]) {
129
- const checked = new Set<T>();
130
- const duplicates = new Set<T>();
131
- for (const element of array) {
132
- if (checked.has(element)) {
133
- duplicates.add(element);
134
- }
135
- checked.add(element);
136
- }
137
- return [...duplicates];
138
- }
139
-
140
- export function validateSelector(name: string, ctx: RefinementCtx) {
141
- if (name.length > 16) {
142
- ctx.addIssue({
143
- code: ZodIssueCode.custom,
144
- message: `Selector must be <= 16 characters`,
145
- });
146
- }
147
- if (!/^\w*$/.test(name)) {
148
- ctx.addIssue({
149
- code: ZodIssueCode.custom,
150
- message: `Selector must contain only alphanumeric & underscore characters`,
151
- });
152
- }
153
- }
154
-
155
- /** Returns null if the type does not look like a static array, otherwise element and length data */
156
- export function parseStaticArray(abiType: string) {
157
- const matches = abiType.match(/^(\w+)\[(\d+)\]$/);
158
- if (!matches) return null;
159
- return {
160
- elementType: matches[1],
161
- staticLength: Number.parseInt(matches[2]),
162
- };
163
- }
@@ -1,4 +0,0 @@
1
- export * from "./loadWorldConfig.js";
2
- export * from "./parseWorldConfig.js";
3
- export * from "./resolveWorldConfig.js";
4
- export * from "./userTypes.js";
@@ -1,11 +0,0 @@
1
- import { describe, expectTypeOf } from "vitest";
2
- import { z } from "zod";
3
- import { zWorldConfig, WorldUserConfig } from "./index.js";
4
-
5
- describe("loadWorldConfig", () => {
6
- // Typecheck manual interfaces against zod
7
- expectTypeOf<WorldUserConfig>().toEqualTypeOf<z.input<typeof zWorldConfig>>();
8
- // type equality isn't deep for optionals
9
- expectTypeOf<WorldUserConfig["overrideSystems"]>().toEqualTypeOf<z.input<typeof zWorldConfig>["overrideSystems"]>();
10
- // TODO If more nested schemas are added, provide separate tests for them
11
- });
@@ -1,26 +0,0 @@
1
- import { ZodError } from "zod";
2
- import { fromZodErrorCustom } from "../../utils/errors.js";
3
- import { loadConfig } from "../loadConfig.js";
4
- import { zWorldConfig } from "./parseWorldConfig.js";
5
- import { resolveWorldConfig } from "./resolveWorldConfig.js";
6
-
7
- /**
8
- * Loads and resolves the world config.
9
- * @param configPath Path to load the config from. Defaults to "mud.config.mts" or "mud.config.ts"
10
- * @param existingContracts Optional list of existing contract names to validate system names against. If not provided, no validation is performed. Contract names ending in `System` will be added to the config with default values.
11
- * @returns Promise of ResolvedWorldConfig object
12
- */
13
- export async function loadWorldConfig(configPath?: string, existingContracts?: string[]) {
14
- const config = await loadConfig(configPath);
15
-
16
- try {
17
- const parsedConfig = zWorldConfig.parse(config);
18
- return resolveWorldConfig(parsedConfig, existingContracts);
19
- } catch (error) {
20
- if (error instanceof ZodError) {
21
- throw fromZodErrorCustom(error, "WorldConfig Validation Error");
22
- } else {
23
- throw error;
24
- }
25
- }
26
- }
@@ -1,56 +0,0 @@
1
- import { z } from "zod";
2
- import { zEthereumAddress, zObjectName, zSelector } from "../commonSchemas.js";
3
- import { DynamicResolutionType } from "../dynamicResolution.js";
4
-
5
- const zSystemName = zObjectName;
6
- const zModuleName = zObjectName;
7
- const zSystemAccessList = z.array(zSystemName.or(zEthereumAddress)).default([]);
8
-
9
- // The system config is a combination of a fileSelector config and access config
10
- const zSystemConfig = z.intersection(
11
- z.object({
12
- fileSelector: zSelector,
13
- registerFunctionSelectors: z.boolean().default(true),
14
- }),
15
- z.discriminatedUnion("openAccess", [
16
- z.object({
17
- openAccess: z.literal(true),
18
- }),
19
- z.object({
20
- openAccess: z.literal(false),
21
- accessList: zSystemAccessList,
22
- }),
23
- ])
24
- );
25
-
26
- const zValueWithType = z.object({
27
- value: z.union([z.string(), z.number(), z.instanceof(Uint8Array)]),
28
- type: z.string(),
29
- });
30
- const zDynamicResolution = z.object({ type: z.nativeEnum(DynamicResolutionType), input: z.string() });
31
-
32
- const zModuleConfig = z.object({
33
- name: zModuleName,
34
- root: z.boolean().default(false),
35
- args: z.array(z.union([zValueWithType, zDynamicResolution])).default([]),
36
- });
37
-
38
- // The parsed world config is the result of parsing the user config
39
- export const zWorldConfig = z.object({
40
- namespace: zSelector.default(""),
41
- worldContractName: z.string().optional(),
42
- worldInterfaceName: z.string().default("IWorld"),
43
- overrideSystems: z.record(zSystemName, zSystemConfig).default({}),
44
- excludeSystems: z.array(zSystemName).default([]),
45
- postDeployScript: z.string().default("PostDeploy"),
46
- deploysDirectory: z.string().default("./deploys"),
47
- worldgenDirectory: z.string().default("world"),
48
- worldImportPath: z.string().default("@latticexyz/world/src/"),
49
- modules: z.array(zModuleConfig).default([]),
50
- });
51
-
52
- export async function parseWorldConfig(config: unknown) {
53
- return zWorldConfig.parse(config);
54
- }
55
-
56
- export type ParsedWorldConfig = z.output<typeof zWorldConfig>;
@@ -1,80 +0,0 @@
1
- import { UnrecognizedSystemErrorFactory } from "../../utils/errors.js";
2
- import { ParsedWorldConfig } from "./parseWorldConfig.js";
3
- import { SystemUserConfig } from "./userTypes.js";
4
-
5
- export type ResolvedSystemConfig = ReturnType<typeof resolveSystemConfig>;
6
-
7
- export type ResolvedWorldConfig = ReturnType<typeof resolveWorldConfig>;
8
-
9
- /**
10
- * Resolves the world config by combining the default and overridden system configs,
11
- * filtering out excluded systems, validate system names refer to existing contracts, and
12
- * splitting the access list into addresses and system names.
13
- */
14
- export function resolveWorldConfig(config: ParsedWorldConfig, existingContracts?: string[]) {
15
- // Include contract names ending in "System", but not the base "System" contract, and not Interfaces
16
- const defaultSystemNames =
17
- existingContracts?.filter((name) => name.endsWith("System") && name !== "System" && !name.match(/^I[A-Z]/)) ?? [];
18
- const overriddenSystemNames = Object.keys(config.overrideSystems);
19
-
20
- // Validate every key in overrideSystems refers to an existing system contract (and is not called "World")
21
- if (existingContracts) {
22
- for (const systemName of overriddenSystemNames) {
23
- if (!existingContracts.includes(systemName) || systemName === "World") {
24
- throw UnrecognizedSystemErrorFactory(["overrideSystems", systemName], systemName);
25
- }
26
- }
27
- }
28
-
29
- // Combine the default and overridden system names and filter out excluded systems
30
- const systemNames = [...new Set([...defaultSystemNames, ...overriddenSystemNames])].filter(
31
- (name) => !config.excludeSystems.includes(name)
32
- );
33
-
34
- // Resolve the config
35
- const resolvedSystems: Record<string, ResolvedSystemConfig> = systemNames.reduce((acc, systemName) => {
36
- return {
37
- ...acc,
38
- [systemName]: resolveSystemConfig(systemName, config.overrideSystems[systemName], existingContracts),
39
- };
40
- }, {});
41
-
42
- const { overrideSystems, excludeSystems, ...otherConfig } = config;
43
- return { ...otherConfig, systems: resolvedSystems };
44
- }
45
-
46
- /**
47
- * Resolves the system config by combining the default and overridden system configs,
48
- * @param systemName name of the system
49
- * @param config optional SystemConfig object, if none is provided the default config is used
50
- * @param existingContracts optional list of existing contract names, used to validate system names in the access list. If not provided, no validation is performed.
51
- * @returns ResolvedSystemConfig object
52
- * Default value for fileSelector is `systemName`
53
- * Default value for registerFunctionSelectors is true
54
- * Default value for openAccess is true
55
- * Default value for accessListAddresses is []
56
- * Default value for accessListSystems is []
57
- */
58
- export function resolveSystemConfig(systemName: string, config?: SystemUserConfig, existingContracts?: string[]) {
59
- const fileSelector = config?.fileSelector ?? systemName;
60
- const registerFunctionSelectors = config?.registerFunctionSelectors ?? true;
61
- const openAccess = config?.openAccess ?? true;
62
- const accessListAddresses: string[] = [];
63
- const accessListSystems: string[] = [];
64
- const accessList = config && !config.openAccess ? config.accessList : [];
65
-
66
- // Split the access list into addresses and system names
67
- for (const accessListItem of accessList) {
68
- if (accessListItem.startsWith("0x")) {
69
- accessListAddresses.push(accessListItem);
70
- } else {
71
- // Validate every system refers to an existing system contract
72
- if (existingContracts && !existingContracts.includes(accessListItem)) {
73
- throw UnrecognizedSystemErrorFactory(["overrideSystems", systemName, "accessList"], accessListItem);
74
- }
75
- accessListSystems.push(accessListItem);
76
- }
77
- }
78
-
79
- return { fileSelector, registerFunctionSelectors, openAccess, accessListAddresses, accessListSystems };
80
- }