@terreno/syncdb 57.0.0-beta.1 → 57.2.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 (151) hide show
  1. package/README.md +33 -0
  2. package/dist/client.d.ts +5 -0
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +64 -1
  5. package/dist/client.js.map +1 -1
  6. package/dist/client.test.js +73 -1
  7. package/dist/client.test.js.map +1 -1
  8. package/dist/codegen/cli.d.ts +3 -0
  9. package/dist/codegen/cli.d.ts.map +1 -0
  10. package/dist/codegen/cli.js +47 -0
  11. package/dist/codegen/cli.js.map +1 -0
  12. package/dist/codegen/cli.test.d.ts +2 -0
  13. package/dist/codegen/cli.test.d.ts.map +1 -0
  14. package/dist/codegen/cli.test.js +54 -0
  15. package/dist/codegen/cli.test.js.map +1 -0
  16. package/dist/codegen/discoverCollections.d.ts +6 -0
  17. package/dist/codegen/discoverCollections.d.ts.map +1 -0
  18. package/dist/codegen/discoverCollections.js +111 -0
  19. package/dist/codegen/discoverCollections.js.map +1 -0
  20. package/dist/codegen/emitSdk.d.ts +12 -0
  21. package/dist/codegen/emitSdk.d.ts.map +1 -0
  22. package/dist/codegen/emitSdk.js +94 -0
  23. package/dist/codegen/emitSdk.js.map +1 -0
  24. package/dist/codegen/emitTypes.d.ts +6 -0
  25. package/dist/codegen/emitTypes.d.ts.map +1 -0
  26. package/dist/codegen/emitTypes.js +43 -0
  27. package/dist/codegen/emitTypes.js.map +1 -0
  28. package/dist/codegen/generate.d.ts +5 -0
  29. package/dist/codegen/generate.d.ts.map +1 -0
  30. package/dist/codegen/generate.js +47 -0
  31. package/dist/codegen/generate.js.map +1 -0
  32. package/dist/codegen/generate.test.d.ts +2 -0
  33. package/dist/codegen/generate.test.d.ts.map +1 -0
  34. package/dist/codegen/generate.test.js +192 -0
  35. package/dist/codegen/generate.test.js.map +1 -0
  36. package/dist/codegen/hookNames.d.ts +17 -0
  37. package/dist/codegen/hookNames.d.ts.map +1 -0
  38. package/dist/codegen/hookNames.js +27 -0
  39. package/dist/codegen/hookNames.js.map +1 -0
  40. package/dist/codegen/loadSpec.d.ts +3 -0
  41. package/dist/codegen/loadSpec.d.ts.map +1 -0
  42. package/dist/codegen/loadSpec.js +16 -0
  43. package/dist/codegen/loadSpec.js.map +1 -0
  44. package/dist/codegen/safeIdentifiers.d.ts +7 -0
  45. package/dist/codegen/safeIdentifiers.d.ts.map +1 -0
  46. package/dist/codegen/safeIdentifiers.js +15 -0
  47. package/dist/codegen/safeIdentifiers.js.map +1 -0
  48. package/dist/codegen/safeIdentifiers.test.d.ts +2 -0
  49. package/dist/codegen/safeIdentifiers.test.d.ts.map +1 -0
  50. package/dist/codegen/safeIdentifiers.test.js +25 -0
  51. package/dist/codegen/safeIdentifiers.test.js.map +1 -0
  52. package/dist/codegen/types.d.ts +69 -0
  53. package/dist/codegen/types.d.ts.map +1 -0
  54. package/dist/codegen/types.js +2 -0
  55. package/dist/codegen/types.js.map +1 -0
  56. package/dist/crypto/keyProviders.test.js +2 -2
  57. package/dist/crypto/keyProviders.test.js.map +1 -1
  58. package/dist/index.d.ts +1 -1
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/maxAttempts.d.ts +7 -0
  62. package/dist/maxAttempts.d.ts.map +1 -0
  63. package/dist/maxAttempts.js +15 -0
  64. package/dist/maxAttempts.js.map +1 -0
  65. package/dist/mutations/outbox.d.ts +5 -0
  66. package/dist/mutations/outbox.d.ts.map +1 -1
  67. package/dist/mutations/outbox.js +10 -2
  68. package/dist/mutations/outbox.js.map +1 -1
  69. package/dist/mutations/outbox.test.js +36 -0
  70. package/dist/mutations/outbox.test.js.map +1 -1
  71. package/dist/react/collectionHooks.d.ts +43 -0
  72. package/dist/react/collectionHooks.d.ts.map +1 -0
  73. package/dist/react/collectionHooks.js +51 -0
  74. package/dist/react/collectionHooks.js.map +1 -0
  75. package/dist/react/collectionHooks.test.d.ts +2 -0
  76. package/dist/react/collectionHooks.test.d.ts.map +1 -0
  77. package/dist/react/collectionHooks.test.js +150 -0
  78. package/dist/react/collectionHooks.test.js.map +1 -0
  79. package/dist/react/hooks.d.ts +4 -0
  80. package/dist/react/hooks.d.ts.map +1 -1
  81. package/dist/react/hooks.js +20 -3
  82. package/dist/react/hooks.js.map +1 -1
  83. package/dist/react/hooks.test.js +3 -4
  84. package/dist/react/hooks.test.js.map +1 -1
  85. package/dist/react/index.d.ts +1 -0
  86. package/dist/react/index.d.ts.map +1 -1
  87. package/dist/react/index.js +1 -0
  88. package/dist/react/index.js.map +1 -1
  89. package/dist/storage/idb.test.js +3 -1
  90. package/dist/storage/idb.test.js.map +1 -1
  91. package/dist/storage/schema.d.ts.map +1 -1
  92. package/dist/storage/schema.js +1 -0
  93. package/dist/storage/schema.js.map +1 -1
  94. package/dist/storage/types.d.ts +2 -0
  95. package/dist/storage/types.d.ts.map +1 -1
  96. package/dist/sync/replayCoordinator.d.ts.map +1 -1
  97. package/dist/sync/replayCoordinator.js +4 -2
  98. package/dist/sync/replayCoordinator.js.map +1 -1
  99. package/dist/sync/replayCoordinator.test.js +52 -1
  100. package/dist/sync/replayCoordinator.test.js.map +1 -1
  101. package/dist/sync/socketTransport.d.ts +9 -2
  102. package/dist/sync/socketTransport.d.ts.map +1 -1
  103. package/dist/sync/socketTransport.js +21 -3
  104. package/dist/sync/socketTransport.js.map +1 -1
  105. package/dist/sync/socketTransport.test.js +50 -2
  106. package/dist/sync/socketTransport.test.js.map +1 -1
  107. package/dist/sync/transport.d.ts +7 -1
  108. package/dist/sync/transport.d.ts.map +1 -1
  109. package/dist/sync/transport.js.map +1 -1
  110. package/dist/testing/fakeTransport.d.ts +3 -1
  111. package/dist/testing/fakeTransport.d.ts.map +1 -1
  112. package/dist/testing/fakeTransport.js +12 -0
  113. package/dist/testing/fakeTransport.js.map +1 -1
  114. package/dist/types.d.ts +17 -0
  115. package/dist/types.d.ts.map +1 -1
  116. package/package.json +7 -2
  117. package/src/client.test.ts +88 -1
  118. package/src/client.ts +74 -0
  119. package/src/codegen/cli.test.ts +61 -0
  120. package/src/codegen/cli.ts +52 -0
  121. package/src/codegen/discoverCollections.ts +159 -0
  122. package/src/codegen/emitSdk.ts +113 -0
  123. package/src/codegen/emitTypes.ts +46 -0
  124. package/src/codegen/fixtures/openapi.example.json +94 -0
  125. package/src/codegen/generate.test.ts +216 -0
  126. package/src/codegen/generate.ts +52 -0
  127. package/src/codegen/hookNames.ts +41 -0
  128. package/src/codegen/loadSpec.ts +18 -0
  129. package/src/codegen/safeIdentifiers.test.ts +32 -0
  130. package/src/codegen/safeIdentifiers.ts +17 -0
  131. package/src/codegen/types.ts +70 -0
  132. package/src/crypto/keyProviders.test.ts +2 -2
  133. package/src/index.ts +1 -0
  134. package/src/maxAttempts.ts +14 -0
  135. package/src/mutations/outbox.test.ts +39 -0
  136. package/src/mutations/outbox.ts +15 -2
  137. package/src/react/collectionHooks.test.tsx +189 -0
  138. package/src/react/collectionHooks.ts +103 -0
  139. package/src/react/hooks.test.tsx +3 -4
  140. package/src/react/hooks.ts +40 -9
  141. package/src/react/index.ts +1 -0
  142. package/src/storage/idb.test.ts +3 -1
  143. package/src/storage/schema.ts +1 -0
  144. package/src/storage/types.ts +2 -0
  145. package/src/sync/replayCoordinator.test.ts +61 -0
  146. package/src/sync/replayCoordinator.ts +4 -2
  147. package/src/sync/socketTransport.test.ts +53 -2
  148. package/src/sync/socketTransport.ts +29 -2
  149. package/src/sync/transport.ts +7 -0
  150. package/src/testing/fakeTransport.ts +15 -0
  151. package/src/types.ts +18 -0
@@ -0,0 +1,159 @@
1
+ import {refName, toPascalCase} from "./hookNames";
2
+ import type {DiscoveredCollection, OpenApiDocument, OpenApiSchema} from "./types";
3
+
4
+ const jsonContentSchema = (
5
+ content?: Record<string, {schema?: OpenApiSchema}>
6
+ ): OpenApiSchema | undefined => content?.["application/json"]?.schema;
7
+
8
+ const resolveSchema = (spec: OpenApiDocument, schema: OpenApiSchema | undefined): OpenApiSchema => {
9
+ if (!schema) {
10
+ return {properties: {}, type: "object"};
11
+ }
12
+ if (schema.$ref) {
13
+ const name = refName(schema.$ref);
14
+ const resolved = name ? spec.components?.schemas?.[name] : undefined;
15
+ if (resolved) {
16
+ return resolved;
17
+ }
18
+ }
19
+ return schema;
20
+ };
21
+
22
+ const listItemSchema = (
23
+ spec: OpenApiDocument,
24
+ operationSchema: OpenApiSchema | undefined
25
+ ): OpenApiSchema | undefined => {
26
+ if (!operationSchema) {
27
+ return undefined;
28
+ }
29
+ const resolved = resolveSchema(spec, operationSchema);
30
+ const data = resolved.properties?.data;
31
+ if (!data) {
32
+ return undefined;
33
+ }
34
+ const resolvedData = resolveSchema(spec, data);
35
+ return resolvedData.items;
36
+ };
37
+
38
+ const fallbackEntityName = (collection: string): string => {
39
+ const pascal = toPascalCase(collection);
40
+ if (pascal.endsWith("s") && pascal.length > 1) {
41
+ return pascal.slice(0, -1);
42
+ }
43
+ return pascal;
44
+ };
45
+
46
+ const findCollectionPath = ({
47
+ collection,
48
+ spec,
49
+ }: {
50
+ collection: string;
51
+ spec: OpenApiDocument;
52
+ }): string | undefined => {
53
+ const candidates = [`/${collection}`, `/${collection}/`];
54
+ for (const path of candidates) {
55
+ if (spec.paths?.[path]) {
56
+ return path;
57
+ }
58
+ }
59
+ return undefined;
60
+ };
61
+
62
+ const fromExtension = (
63
+ spec: OpenApiDocument,
64
+ path: string,
65
+ collection: string
66
+ ): DiscoveredCollection => {
67
+ const item = spec.paths?.[path];
68
+ const entitySchemaRaw = listItemSchema(
69
+ spec,
70
+ jsonContentSchema(item?.get?.responses?.["200"]?.content)
71
+ );
72
+ if (!entitySchemaRaw) {
73
+ throw new Error(
74
+ `List operation GET ${path} has no JSON 200 data.items schema for collection "${collection}"`
75
+ );
76
+ }
77
+ const entityName = refName(entitySchemaRaw.$ref) ?? fallbackEntityName(collection);
78
+ const createSchemaRaw = jsonContentSchema(item?.post?.requestBody?.content);
79
+ const collectionPath = path.endsWith("/") ? path.slice(0, -1) : path;
80
+ const exactIdPath = `${collectionPath}/{id}`;
81
+ const pathNames = Object.keys(spec.paths ?? {});
82
+ const idPath = pathNames.includes(exactIdPath)
83
+ ? exactIdPath
84
+ : pathNames.find((candidate) => {
85
+ if (!candidate.startsWith(`${collectionPath}/`)) {
86
+ return false;
87
+ }
88
+ return /^\{[^/]+\}$/.test(candidate.slice(collectionPath.length + 1));
89
+ });
90
+ const patchOp = idPath ? spec.paths?.[idPath]?.patch : undefined;
91
+ const updateSchemaRaw = jsonContentSchema(patchOp?.requestBody?.content);
92
+ return {
93
+ collection,
94
+ createName: refName(createSchemaRaw?.$ref) ?? `Create${entityName}Body`,
95
+ createSchema: resolveSchema(spec, createSchemaRaw),
96
+ entityName,
97
+ entitySchema: resolveSchema(spec, entitySchemaRaw),
98
+ updateName: refName(updateSchemaRaw?.$ref) ?? `Update${entityName}Body`,
99
+ updateSchema: resolveSchema(spec, updateSchemaRaw),
100
+ };
101
+ };
102
+
103
+ const fromCollectionFlag = ({
104
+ collection,
105
+ spec,
106
+ }: {
107
+ collection: string;
108
+ spec: OpenApiDocument;
109
+ }): DiscoveredCollection => {
110
+ const path = findCollectionPath({collection, spec});
111
+ if (!path) {
112
+ throw new Error(
113
+ `No OpenAPI path for collection "${collection}" (tried /${collection} and /${collection}/). ` +
114
+ "Add x-terreno-sync to the list operation, or pass a collection whose list path exists."
115
+ );
116
+ }
117
+ return fromExtension(spec, path, collection);
118
+ };
119
+
120
+ export const discoverCollections = ({
121
+ spec,
122
+ collections,
123
+ }: {
124
+ spec: OpenApiDocument;
125
+ collections?: string[];
126
+ }): DiscoveredCollection[] => {
127
+ const fromSpec: DiscoveredCollection[] = [];
128
+ const allow = collections && collections.length > 0 ? new Set(collections) : undefined;
129
+ let sawExtension = false;
130
+ for (const [path, item] of Object.entries(spec.paths ?? {})) {
131
+ const extension = item.get?.["x-terreno-sync"];
132
+ if (!extension?.collection) {
133
+ continue;
134
+ }
135
+ sawExtension = true;
136
+ if (allow && !allow.has(extension.collection)) {
137
+ continue;
138
+ }
139
+ fromSpec.push(fromExtension(spec, path, extension.collection));
140
+ }
141
+
142
+ if (fromSpec.length === 0) {
143
+ if (collections && collections.length > 0 && !sawExtension) {
144
+ return collections.map((collection) => fromCollectionFlag({collection, spec}));
145
+ }
146
+ if (collections && collections.length > 0 && sawExtension) {
147
+ throw new Error(
148
+ `No synced collections matched --collections ${collections.join(",")}. ` +
149
+ "Check x-terreno-sync on list operations in the OpenAPI spec."
150
+ );
151
+ }
152
+ throw new Error(
153
+ "No synced collections found. Add x-terreno-sync to list operations " +
154
+ "(modelRouter sync: {...}) or pass --collections todos,notes."
155
+ );
156
+ }
157
+
158
+ return fromSpec;
159
+ };
@@ -0,0 +1,113 @@
1
+ import {emitInterface} from "./emitTypes";
2
+ import {friendlyHookNames} from "./hookNames";
3
+ import {assertTsIdentifier, emitTsString} from "./safeIdentifiers";
4
+ import type {CodegenConfigFile, DiscoveredCollection} from "./types";
5
+
6
+ const GENERATED_HEADER = `// GENERATED by @terreno/syncdb (terreno-syncdb-codegen). Do not edit.
7
+ // Friendly names (useTodos / useTodo / useCreateTodo / …) so this file can
8
+ // coexist with RTK openApiSdk.ts. Mutation triggers are synchronous
9
+ // ({mutationId, id}) — there is no .unwrap() or per-call isLoading.
10
+ `;
11
+
12
+ const retriesLiteral = (retries?: boolean | number): string => {
13
+ if (retries === undefined) {
14
+ return "";
15
+ }
16
+ if (retries === false) {
17
+ return ", retries: false";
18
+ }
19
+ if (retries === true) {
20
+ return ", retries: true";
21
+ }
22
+ if (typeof retries === "number" && Number.isFinite(retries)) {
23
+ return `, retries: ${retries}`;
24
+ }
25
+ throw new Error(`Invalid retries override: ${JSON.stringify(retries)}`);
26
+ };
27
+
28
+ export const emitSdk = ({
29
+ collections,
30
+ config,
31
+ }: {
32
+ collections: DiscoveredCollection[];
33
+ config?: CodegenConfigFile;
34
+ }): string => {
35
+ const sdkImportPath = config?.sdkImportPath ?? "@terreno/syncdb/react";
36
+ const typeBlocks: string[] = [];
37
+ const hookBlocks: string[] = [];
38
+ const names: string[] = [];
39
+
40
+ for (const collection of collections) {
41
+ const collectionName = assertTsIdentifier({
42
+ label: "collection",
43
+ value: collection.collection,
44
+ });
45
+ const entityName = assertTsIdentifier({
46
+ label: "entity schema name",
47
+ value: collection.entityName,
48
+ });
49
+ const createName = assertTsIdentifier({
50
+ label: "create body name",
51
+ value: collection.createName,
52
+ });
53
+ const updateName = assertTsIdentifier({
54
+ label: "update body name",
55
+ value: collection.updateName,
56
+ });
57
+ names.push(collectionName);
58
+ typeBlocks.push(emitInterface({name: entityName, schema: collection.entitySchema}));
59
+ typeBlocks.push(emitInterface({name: createName, schema: collection.createSchema}));
60
+ typeBlocks.push(emitInterface({name: updateName, schema: collection.updateSchema}));
61
+
62
+ const hooks = friendlyHookNames({
63
+ collection: collectionName,
64
+ entityName,
65
+ });
66
+ const list = assertTsIdentifier({label: "hook name", value: hooks.list});
67
+ const read = assertTsIdentifier({label: "hook name", value: hooks.read});
68
+ const create = assertTsIdentifier({label: "hook name", value: hooks.create});
69
+ const update = assertTsIdentifier({label: "hook name", value: hooks.update});
70
+ const remove = assertTsIdentifier({label: "hook name", value: hooks.remove});
71
+ const retries = retriesLiteral(collection.retries);
72
+ hookBlocks.push(`export const {
73
+ useListQuery: ${list},
74
+ useReadQuery: ${read},
75
+ useCreateMutation: ${create},
76
+ useUpdateMutation: ${update},
77
+ useDeleteMutation: ${remove},
78
+ } = createCollectionHooks<${entityName}, ${createName}, ${updateName}>({collection: ${emitTsString(collectionName)}${retries}});`);
79
+ }
80
+
81
+ const collectionsLiteral = names.map((name) => emitTsString(name)).join(", ");
82
+ return [
83
+ GENERATED_HEADER,
84
+ `import {createCollectionHooks} from ${emitTsString(sdkImportPath)};`,
85
+ "",
86
+ typeBlocks.join("\n\n"),
87
+ "",
88
+ "/** Collections with sync enabled on the backend; pass to createSyncDb. */",
89
+ `export const SYNC_COLLECTIONS = [${collectionsLiteral}] as const;`,
90
+ "",
91
+ hookBlocks.join("\n\n"),
92
+ "",
93
+ ].join("\n");
94
+ };
95
+
96
+ export const applyRetriesOverrides = ({
97
+ collections,
98
+ overrides,
99
+ }: {
100
+ collections: DiscoveredCollection[];
101
+ overrides?: Record<string, {retries?: boolean | number}>;
102
+ }): DiscoveredCollection[] => {
103
+ if (!overrides) {
104
+ return collections;
105
+ }
106
+ return collections.map((collection) => {
107
+ const retries = overrides[collection.collection]?.retries;
108
+ if (retries === undefined) {
109
+ return collection;
110
+ }
111
+ return {...collection, retries};
112
+ });
113
+ };
@@ -0,0 +1,46 @@
1
+ import {assertTsIdentifier, emitTsPropertyKey} from "./safeIdentifiers";
2
+ import type {OpenApiSchema} from "./types";
3
+
4
+ const tsTypeFromSchema = (schema: OpenApiSchema, indent: string): string => {
5
+ if (schema.enum && schema.enum.length > 0) {
6
+ return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
7
+ }
8
+ if (schema.type === "array") {
9
+ const itemType = schema.items ? tsTypeFromSchema(schema.items, indent) : "unknown";
10
+ return `${itemType}[]`;
11
+ }
12
+ if (schema.type === "object" || schema.properties) {
13
+ if (!schema.properties || Object.keys(schema.properties).length === 0) {
14
+ return "Record<string, unknown>";
15
+ }
16
+ return emitInterfaceBody(schema, indent);
17
+ }
18
+ if (schema.type === "integer" || schema.type === "number") {
19
+ return "number";
20
+ }
21
+ if (schema.type === "boolean") {
22
+ return "boolean";
23
+ }
24
+ if (schema.type === "string" || schema.type === "schemaobjectid") {
25
+ return "string";
26
+ }
27
+ return "unknown";
28
+ };
29
+
30
+ const emitInterfaceBody = (schema: OpenApiSchema, indent: string): string => {
31
+ const required = new Set(schema.required ?? []);
32
+ const lines = Object.entries(schema.properties ?? {}).map(([key, property]) => {
33
+ const optional = required.has(key) ? "" : "?";
34
+ const type = tsTypeFromSchema(property, `${indent} `);
35
+ return `${indent} ${emitTsPropertyKey(key)}${optional}: ${type};`;
36
+ });
37
+ return `{\n${lines.join("\n")}\n${indent}}`;
38
+ };
39
+
40
+ export const emitInterface = ({name, schema}: {name: string; schema: OpenApiSchema}): string => {
41
+ const typeName = assertTsIdentifier({label: "type name", value: name});
42
+ if (schema.type === "object" || schema.properties) {
43
+ return `export interface ${typeName} ${emitInterfaceBody(schema, "")}`;
44
+ }
45
+ return `export type ${typeName} = ${tsTypeFromSchema(schema, "")};`;
46
+ };
@@ -0,0 +1,94 @@
1
+ {
2
+ "openapi": "3.0.3",
3
+ "info": {"title": "Example", "version": "1.0.0"},
4
+ "paths": {
5
+ "/todos": {
6
+ "get": {
7
+ "x-terreno-sync": {"collection": "todos", "scope": "owner"},
8
+ "responses": {
9
+ "200": {
10
+ "content": {
11
+ "application/json": {
12
+ "schema": {
13
+ "type": "object",
14
+ "properties": {
15
+ "data": {
16
+ "type": "array",
17
+ "items": {"$ref": "#/components/schemas/Todo"}
18
+ }
19
+ }
20
+ }
21
+ }
22
+ }
23
+ }
24
+ }
25
+ },
26
+ "post": {
27
+ "requestBody": {
28
+ "content": {
29
+ "application/json": {
30
+ "schema": {"$ref": "#/components/schemas/CreateTodoBody"}
31
+ }
32
+ }
33
+ }
34
+ }
35
+ },
36
+ "/todos/{id}": {
37
+ "get": {},
38
+ "patch": {
39
+ "requestBody": {
40
+ "content": {
41
+ "application/json": {
42
+ "schema": {"$ref": "#/components/schemas/UpdateTodoBody"}
43
+ }
44
+ }
45
+ }
46
+ },
47
+ "delete": {}
48
+ },
49
+ "/health": {
50
+ "get": {
51
+ "responses": {
52
+ "200": {
53
+ "content": {
54
+ "application/json": {
55
+ "schema": {"type": "object"}
56
+ }
57
+ }
58
+ }
59
+ }
60
+ }
61
+ }
62
+ },
63
+ "components": {
64
+ "schemas": {
65
+ "Todo": {
66
+ "type": "object",
67
+ "required": ["_id", "title", "completed", "ownerId", "created", "updated"],
68
+ "properties": {
69
+ "_id": {"type": "string"},
70
+ "title": {"type": "string"},
71
+ "completed": {"type": "boolean"},
72
+ "ownerId": {"type": "string"},
73
+ "created": {"type": "string"},
74
+ "updated": {"type": "string"}
75
+ }
76
+ },
77
+ "CreateTodoBody": {
78
+ "type": "object",
79
+ "required": ["title"],
80
+ "properties": {
81
+ "title": {"type": "string"},
82
+ "completed": {"type": "boolean"}
83
+ }
84
+ },
85
+ "UpdateTodoBody": {
86
+ "type": "object",
87
+ "properties": {
88
+ "title": {"type": "string"},
89
+ "completed": {"type": "boolean"}
90
+ }
91
+ }
92
+ }
93
+ }
94
+ }
@@ -0,0 +1,216 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import {mkdtemp, readFile, rm} from "node:fs/promises";
3
+ import {tmpdir} from "node:os";
4
+ import {join} from "node:path";
5
+
6
+ import {discoverCollections} from "./discoverCollections";
7
+ import {emitSdk} from "./emitSdk";
8
+ import {emitInterface} from "./emitTypes";
9
+ import {generateSyncDbSdk} from "./generate";
10
+ import {friendlyHookNames} from "./hookNames";
11
+ import {loadSpec} from "./loadSpec";
12
+
13
+ const fixturePath = join(import.meta.dir, "fixtures", "openapi.example.json");
14
+
15
+ describe("friendlyHookNames", () => {
16
+ it("uses entity-centric names for todos", () => {
17
+ expect(friendlyHookNames({collection: "todos", entityName: "Todo"})).toEqual({
18
+ create: "useCreateTodo",
19
+ list: "useTodos",
20
+ read: "useTodo",
21
+ remove: "useDeleteTodo",
22
+ update: "useUpdateTodo",
23
+ });
24
+ });
25
+ });
26
+
27
+ describe("emitInterface", () => {
28
+ it("maps Mongoose ObjectId schemas to strings", () => {
29
+ expect(
30
+ emitInterface({
31
+ name: "Owned",
32
+ schema: {
33
+ properties: {ownerId: {type: "schemaobjectid"}},
34
+ required: ["ownerId"],
35
+ type: "object",
36
+ },
37
+ })
38
+ ).toContain("ownerId: string;");
39
+ });
40
+ });
41
+
42
+ describe("discoverCollections", () => {
43
+ it("reads x-terreno-sync from the fixture spec", async () => {
44
+ const spec = await loadSpec(fixturePath);
45
+ const discovered = discoverCollections({spec});
46
+ expect(discovered.map((entry) => entry.collection)).toEqual(["todos"]);
47
+ expect(discovered[0]?.entityName).toBe("Todo");
48
+ expect(discovered[0]?.createName).toBe("CreateTodoBody");
49
+ expect(discovered[0]?.updateName).toBe("UpdateTodoBody");
50
+ });
51
+
52
+ it("finds item routes when the collection path has a trailing slash", async () => {
53
+ const spec = await loadSpec(fixturePath);
54
+ const todoPath = spec.paths?.["/todos"];
55
+ const todoItemPath = spec.paths?.["/todos/{id}"];
56
+ spec.paths = {"/todos/": todoPath ?? {}};
57
+ spec.paths["/todos/{id}/complete"] = {patch: {}};
58
+ spec.paths["/todos/{id}"] = todoItemPath ?? {};
59
+
60
+ const [discovered] = discoverCollections({spec});
61
+
62
+ expect(discovered?.updateName).toBe("UpdateTodoBody");
63
+ expect(discovered?.updateSchema.properties?.title?.type).toBe("string");
64
+ });
65
+
66
+ it("filters with --collections", async () => {
67
+ const spec = await loadSpec(fixturePath);
68
+ expect(() => discoverCollections({collections: ["notes"], spec})).toThrow(/matched/);
69
+ });
70
+
71
+ it("errors when the spec has no extensions and no --collections", () => {
72
+ expect(() => discoverCollections({spec: {paths: {"/health": {get: {}}}}})).toThrow(
73
+ /No synced collections found/
74
+ );
75
+ });
76
+
77
+ it("reads list/create/patch schemas from /{name} when --collections is the fallback", async () => {
78
+ const spec = await loadSpec(fixturePath);
79
+ if (spec.paths?.["/todos"]?.get) {
80
+ delete spec.paths["/todos"].get["x-terreno-sync"];
81
+ }
82
+ const [discovered] = discoverCollections({collections: ["todos"], spec});
83
+ expect(discovered?.entityName).toBe("Todo");
84
+ expect(discovered?.createName).toBe("CreateTodoBody");
85
+ expect(discovered?.updateSchema.properties?.title?.type).toBe("string");
86
+ });
87
+
88
+ it("errors when --collections names a path that is missing", () => {
89
+ expect(() =>
90
+ discoverCollections({
91
+ collections: ["notes"],
92
+ spec: {paths: {"/health": {get: {}}}},
93
+ })
94
+ ).toThrow(/No OpenAPI path for collection "notes"/);
95
+ });
96
+
97
+ it("does not fail on a broken sibling collection when --collections allowlists a valid one", () => {
98
+ const spec = {
99
+ paths: {
100
+ "/notes": {
101
+ get: {
102
+ responses: {
103
+ "200": {
104
+ content: {
105
+ "application/json": {
106
+ schema: {
107
+ properties: {page: {type: "number"}},
108
+ type: "object",
109
+ },
110
+ },
111
+ },
112
+ },
113
+ },
114
+ "x-terreno-sync": {collection: "notes", scope: "owner"},
115
+ },
116
+ },
117
+ "/todos": {
118
+ get: {
119
+ responses: {
120
+ "200": {
121
+ content: {
122
+ "application/json": {
123
+ schema: {
124
+ properties: {
125
+ data: {
126
+ items: {
127
+ properties: {title: {type: "string"}},
128
+ type: "object",
129
+ },
130
+ type: "array",
131
+ },
132
+ },
133
+ type: "object",
134
+ },
135
+ },
136
+ },
137
+ },
138
+ },
139
+ "x-terreno-sync": {collection: "todos", scope: "owner"},
140
+ },
141
+ },
142
+ },
143
+ };
144
+ expect(() => discoverCollections({spec})).toThrow(/data.items schema/);
145
+ const discovered = discoverCollections({collections: ["todos"], spec});
146
+ expect(discovered).toHaveLength(1);
147
+ expect(discovered[0]?.collection).toBe("todos");
148
+ });
149
+
150
+ it("does not path-fallback --collections when the spec already has x-terreno-sync", async () => {
151
+ const spec = await loadSpec(fixturePath);
152
+ expect(() => discoverCollections({collections: ["notes"], spec})).toThrow(/matched/);
153
+ });
154
+ });
155
+
156
+ describe("generateSyncDbSdk", () => {
157
+ it("emits SYNC_COLLECTIONS and friendly hooks", async () => {
158
+ const dir = await mkdtemp(join(tmpdir(), "syncdb-codegen-"));
159
+ const out = join(dir, "syncDbSdk.ts");
160
+ try {
161
+ const source = await generateSyncDbSdk({
162
+ format: false,
163
+ out,
164
+ schema: fixturePath,
165
+ });
166
+ expect(source).toContain('export const SYNC_COLLECTIONS = ["todos"] as const;');
167
+ expect(source).toContain("useListQuery: useTodos");
168
+ expect(source).toContain("useReadQuery: useTodo");
169
+ expect(source).toContain("useCreateMutation: useCreateTodo");
170
+ expect(source).toContain("useUpdateMutation: useUpdateTodo");
171
+ expect(source).toContain("useDeleteMutation: useDeleteTodo");
172
+ expect(source).toContain("export interface Todo");
173
+ expect(source).toContain("title?: string;");
174
+ expect(await readFile(out, "utf8")).toBe(source);
175
+ } finally {
176
+ await rm(dir, {force: true, recursive: true});
177
+ }
178
+ });
179
+
180
+ it("applies retries: false from config overrides", async () => {
181
+ const dir = await mkdtemp(join(tmpdir(), "syncdb-codegen-"));
182
+ const out = join(dir, "syncDbSdk.ts");
183
+ try {
184
+ const source = await generateSyncDbSdk({
185
+ config: {overrides: {todos: {retries: false}}},
186
+ format: false,
187
+ out,
188
+ schema: fixturePath,
189
+ });
190
+ expect(source).toContain(
191
+ 'createCollectionHooks<Todo, CreateTodoBody, UpdateTodoBody>({collection: "todos", retries: false})'
192
+ );
193
+ } finally {
194
+ await rm(dir, {force: true, recursive: true});
195
+ }
196
+ });
197
+
198
+ it("rejects collection names that are not TypeScript identifiers", async () => {
199
+ const spec = await loadSpec(fixturePath);
200
+ const discovered = discoverCollections({spec});
201
+ const first = discovered[0];
202
+ if (!first) {
203
+ throw new Error("expected todos fixture collection");
204
+ }
205
+ expect(() =>
206
+ emitSdk({
207
+ collections: [
208
+ {
209
+ ...first,
210
+ collection: 'todos"; process.exit(1); //',
211
+ },
212
+ ],
213
+ })
214
+ ).toThrow(/not a TypeScript identifier/);
215
+ });
216
+ });
@@ -0,0 +1,52 @@
1
+ import {mkdir, readFile, writeFile} from "node:fs/promises";
2
+ import {dirname} from "node:path";
3
+
4
+ import {discoverCollections} from "./discoverCollections";
5
+ import {applyRetriesOverrides, emitSdk} from "./emitSdk";
6
+ import {loadSpec} from "./loadSpec";
7
+ import type {CodegenConfigFile, GenerateArgs} from "./types";
8
+
9
+ const formatWithBiome = async (filePath: string): Promise<void> => {
10
+ const proc = Bun.spawn(["bunx", "biome", "check", "--write", filePath], {
11
+ stderr: "pipe",
12
+ stdout: "pipe",
13
+ });
14
+ await proc.exited;
15
+ };
16
+
17
+ export const generateSyncDbSdk = async (args: GenerateArgs): Promise<string> => {
18
+ const spec = await loadSpec(args.schema);
19
+ const discovered = discoverCollections({collections: args.collections, spec});
20
+ const withOverrides = applyRetriesOverrides({
21
+ collections: discovered,
22
+ overrides: args.config?.overrides,
23
+ });
24
+ const source = emitSdk({collections: withOverrides, config: args.config});
25
+ await mkdir(dirname(args.out), {recursive: true});
26
+ await writeFile(args.out, source, "utf8");
27
+ if (args.format) {
28
+ await formatWithBiome(args.out);
29
+ return await readFile(args.out, "utf8");
30
+ }
31
+ return source;
32
+ };
33
+
34
+ export const parseCollectionsFlag = (value?: string): string[] | undefined => {
35
+ if (!value) {
36
+ return undefined;
37
+ }
38
+ const parsed = value
39
+ .split(",")
40
+ .map((part) => part.trim())
41
+ .filter(Boolean);
42
+ return parsed.length > 0 ? parsed : undefined;
43
+ };
44
+
45
+ export const loadConfigFile = async (path?: string): Promise<CodegenConfigFile | undefined> => {
46
+ if (!path) {
47
+ return undefined;
48
+ }
49
+ const {readFile} = await import("node:fs/promises");
50
+ const raw = await readFile(path, "utf8");
51
+ return JSON.parse(raw) as CodegenConfigFile;
52
+ };