@onyx.dev/onyx-database 0.2.0 → 0.3.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.
package/dist/index.d.cts CHANGED
@@ -1014,6 +1014,66 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
1014
1014
  * @param documentId ID of the document to delete.
1015
1015
  */
1016
1016
  deleteDocument(documentId: string): Promise<unknown>;
1017
+ /**
1018
+ * Fetch the current schema for the configured database.
1019
+ *
1020
+ * @example
1021
+ * ```ts
1022
+ * const schema = await db.getSchema();
1023
+ * const userOnly = await db.getSchema({ tables: ['User'] });
1024
+ * ```
1025
+ */
1026
+ getSchema(options?: {
1027
+ tables?: string | string[];
1028
+ }): Promise<SchemaRevision>;
1029
+ /**
1030
+ * Retrieve the schema revision history for the configured database.
1031
+ */
1032
+ getSchemaHistory(): Promise<SchemaHistoryEntry[]>;
1033
+ /**
1034
+ * Update the schema for the configured database.
1035
+ *
1036
+ * @example
1037
+ * ```ts
1038
+ * await db.updateSchema({
1039
+ * revisionDescription: 'Add profile table',
1040
+ * entities: [
1041
+ * {
1042
+ * name: 'Profile',
1043
+ * identifier: { name: 'id', generator: 'UUID' },
1044
+ * attributes: [
1045
+ * { name: 'displayName', type: 'String', isNullable: false }
1046
+ * ]
1047
+ * }
1048
+ * ]
1049
+ * }, { publish: true });
1050
+ * ```
1051
+ */
1052
+ updateSchema(schema: SchemaUpsertRequest, options?: {
1053
+ publish?: boolean;
1054
+ }): Promise<SchemaRevision>;
1055
+ /**
1056
+ * Validate a schema definition without applying it to the database.
1057
+ */
1058
+ validateSchema(schema: SchemaUpsertRequest): Promise<SchemaValidationResult>;
1059
+ /**
1060
+ * List stored secrets for the configured database.
1061
+ */
1062
+ listSecrets(): Promise<SecretsListResponse>;
1063
+ /**
1064
+ * Fetch a decrypted secret value by key.
1065
+ */
1066
+ getSecret(key: string): Promise<SecretRecord>;
1067
+ /**
1068
+ * Create or update a secret.
1069
+ */
1070
+ putSecret(key: string, input: SecretSaveRequest): Promise<SecretMetadata>;
1071
+ /**
1072
+ * Delete a secret by key.
1073
+ */
1074
+ deleteSecret(key: string): Promise<{
1075
+ key: string;
1076
+ }>;
1017
1077
  /**
1018
1078
  * Cancels active streams; safe to call multiple times.
1019
1079
  * @example
@@ -1053,6 +1113,83 @@ interface OnyxFacade {
1053
1113
  */
1054
1114
  clearCacheConfig(): void;
1055
1115
  }
1116
+ interface SecretMetadata {
1117
+ key: string;
1118
+ purpose?: string;
1119
+ updatedAt: Date;
1120
+ }
1121
+ interface SecretRecord extends SecretMetadata {
1122
+ value: string;
1123
+ }
1124
+ interface SecretsListResponse {
1125
+ records: SecretMetadata[];
1126
+ meta: {
1127
+ totalRecords: number;
1128
+ };
1129
+ }
1130
+ interface SecretSaveRequest {
1131
+ purpose?: string;
1132
+ value?: string;
1133
+ }
1134
+ type SchemaDataType = 'String' | 'Boolean' | 'Char' | 'Byte' | 'Short' | 'Int' | 'Float' | 'Double' | 'Long' | 'Timestamp' | 'EmbeddedObject' | 'EmbeddedList';
1135
+ type SchemaIdentifierGenerator = 'None' | 'Sequence' | 'UUID';
1136
+ interface SchemaIdentifier {
1137
+ name: string;
1138
+ generator?: SchemaIdentifierGenerator;
1139
+ type?: SchemaDataType | string;
1140
+ }
1141
+ interface SchemaAttribute {
1142
+ name: string;
1143
+ type: SchemaDataType | string;
1144
+ isNullable?: boolean;
1145
+ }
1146
+ type SchemaIndexType = 'DEFAULT' | 'LUCENE' | string;
1147
+ interface SchemaIndex {
1148
+ name: string;
1149
+ type?: SchemaIndexType;
1150
+ minimumScore?: number;
1151
+ }
1152
+ interface SchemaResolver {
1153
+ name: string;
1154
+ resolver: string;
1155
+ }
1156
+ type SchemaTriggerEvent = 'PreInsert' | 'PostInsert' | 'PrePersist' | 'PostPersist' | 'PreUpdate' | 'PostUpdate' | 'PreDelete' | 'PostDelete' | string;
1157
+ interface SchemaTrigger {
1158
+ name: string;
1159
+ event: SchemaTriggerEvent;
1160
+ trigger: string;
1161
+ }
1162
+ interface SchemaEntity {
1163
+ name: string;
1164
+ identifier?: SchemaIdentifier;
1165
+ partition?: string;
1166
+ attributes?: SchemaAttribute[];
1167
+ indexes?: SchemaIndex[];
1168
+ resolvers?: SchemaResolver[];
1169
+ triggers?: SchemaTrigger[];
1170
+ }
1171
+ interface SchemaRevisionMetadata {
1172
+ revisionId?: string;
1173
+ createdAt?: Date;
1174
+ publishedAt?: Date;
1175
+ }
1176
+ interface SchemaRevision {
1177
+ databaseId: string;
1178
+ revisionDescription?: string;
1179
+ entities: SchemaEntity[];
1180
+ meta?: SchemaRevisionMetadata;
1181
+ }
1182
+ type SchemaHistoryEntry = SchemaRevision;
1183
+ type SchemaUpsertRequest = Omit<SchemaRevision, 'databaseId' | 'meta'> & {
1184
+ databaseId?: string;
1185
+ };
1186
+ interface SchemaValidationResult {
1187
+ valid?: boolean;
1188
+ schema?: SchemaRevision;
1189
+ errors?: Array<{
1190
+ message: string;
1191
+ }>;
1192
+ }
1056
1193
 
1057
1194
  /** -------------------------
1058
1195
  * Facade export
@@ -1187,4 +1324,4 @@ declare const percentile: (attribute: string, p: number) => string;
1187
1324
  declare const sdkName = "@onyx.dev/onyx-database";
1188
1325
  declare const sdkVersion = "0.1.0";
1189
1326
 
1190
- export { type FetchImpl, type FetchResponse, type ICascadeBuilder, type ICascadeRelationshipBuilder, type IConditionBuilder, type IOnyxDatabase, type IQueryBuilder, type ISaveBuilder, type LogicalOperator, type OnyxConfig, type OnyxDocument, type OnyxFacade, type QueryCondition, type QueryCriteria, type QueryCriteriaOperator, type QueryPage, QueryResults, type QueryResultsPromise, type SelectQuery, type Sort, type StreamAction, type UpdateQuery, asc, avg, between, contains, containsIgnoreCase, count, desc, eq, gt, gte, inOp, isNull, like, lower, lt, lte, matches, max, median, min, neq, notContains, notContainsIgnoreCase, notIn, notLike, notMatches, notNull, notStartsWith, onyx, percentile, replace, sdkName, sdkVersion, startsWith, std, substring, sum, upper, variance };
1327
+ export { type FetchImpl, type FetchResponse, type ICascadeBuilder, type ICascadeRelationshipBuilder, type IConditionBuilder, type IOnyxDatabase, type IQueryBuilder, type ISaveBuilder, type LogicalOperator, type OnyxConfig, type OnyxDocument, type OnyxFacade, type QueryCondition, type QueryCriteria, type QueryCriteriaOperator, type QueryPage, QueryResults, type QueryResultsPromise, type SchemaAttribute, type SchemaDataType, type SchemaEntity, type SchemaHistoryEntry, type SchemaIdentifier, type SchemaIdentifierGenerator, type SchemaIndex, type SchemaIndexType, type SchemaResolver, type SchemaRevision, type SchemaRevisionMetadata, type SchemaTrigger, type SchemaTriggerEvent, type SchemaUpsertRequest, type SchemaValidationResult, type SecretMetadata, type SecretRecord, type SecretSaveRequest, type SecretsListResponse, type SelectQuery, type Sort, type StreamAction, type UpdateQuery, asc, avg, between, contains, containsIgnoreCase, count, desc, eq, gt, gte, inOp, isNull, like, lower, lt, lte, matches, max, median, min, neq, notContains, notContainsIgnoreCase, notIn, notLike, notMatches, notNull, notStartsWith, onyx, percentile, replace, sdkName, sdkVersion, startsWith, std, substring, sum, upper, variance };
package/dist/index.d.ts CHANGED
@@ -1014,6 +1014,66 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
1014
1014
  * @param documentId ID of the document to delete.
1015
1015
  */
1016
1016
  deleteDocument(documentId: string): Promise<unknown>;
1017
+ /**
1018
+ * Fetch the current schema for the configured database.
1019
+ *
1020
+ * @example
1021
+ * ```ts
1022
+ * const schema = await db.getSchema();
1023
+ * const userOnly = await db.getSchema({ tables: ['User'] });
1024
+ * ```
1025
+ */
1026
+ getSchema(options?: {
1027
+ tables?: string | string[];
1028
+ }): Promise<SchemaRevision>;
1029
+ /**
1030
+ * Retrieve the schema revision history for the configured database.
1031
+ */
1032
+ getSchemaHistory(): Promise<SchemaHistoryEntry[]>;
1033
+ /**
1034
+ * Update the schema for the configured database.
1035
+ *
1036
+ * @example
1037
+ * ```ts
1038
+ * await db.updateSchema({
1039
+ * revisionDescription: 'Add profile table',
1040
+ * entities: [
1041
+ * {
1042
+ * name: 'Profile',
1043
+ * identifier: { name: 'id', generator: 'UUID' },
1044
+ * attributes: [
1045
+ * { name: 'displayName', type: 'String', isNullable: false }
1046
+ * ]
1047
+ * }
1048
+ * ]
1049
+ * }, { publish: true });
1050
+ * ```
1051
+ */
1052
+ updateSchema(schema: SchemaUpsertRequest, options?: {
1053
+ publish?: boolean;
1054
+ }): Promise<SchemaRevision>;
1055
+ /**
1056
+ * Validate a schema definition without applying it to the database.
1057
+ */
1058
+ validateSchema(schema: SchemaUpsertRequest): Promise<SchemaValidationResult>;
1059
+ /**
1060
+ * List stored secrets for the configured database.
1061
+ */
1062
+ listSecrets(): Promise<SecretsListResponse>;
1063
+ /**
1064
+ * Fetch a decrypted secret value by key.
1065
+ */
1066
+ getSecret(key: string): Promise<SecretRecord>;
1067
+ /**
1068
+ * Create or update a secret.
1069
+ */
1070
+ putSecret(key: string, input: SecretSaveRequest): Promise<SecretMetadata>;
1071
+ /**
1072
+ * Delete a secret by key.
1073
+ */
1074
+ deleteSecret(key: string): Promise<{
1075
+ key: string;
1076
+ }>;
1017
1077
  /**
1018
1078
  * Cancels active streams; safe to call multiple times.
1019
1079
  * @example
@@ -1053,6 +1113,83 @@ interface OnyxFacade {
1053
1113
  */
1054
1114
  clearCacheConfig(): void;
1055
1115
  }
1116
+ interface SecretMetadata {
1117
+ key: string;
1118
+ purpose?: string;
1119
+ updatedAt: Date;
1120
+ }
1121
+ interface SecretRecord extends SecretMetadata {
1122
+ value: string;
1123
+ }
1124
+ interface SecretsListResponse {
1125
+ records: SecretMetadata[];
1126
+ meta: {
1127
+ totalRecords: number;
1128
+ };
1129
+ }
1130
+ interface SecretSaveRequest {
1131
+ purpose?: string;
1132
+ value?: string;
1133
+ }
1134
+ type SchemaDataType = 'String' | 'Boolean' | 'Char' | 'Byte' | 'Short' | 'Int' | 'Float' | 'Double' | 'Long' | 'Timestamp' | 'EmbeddedObject' | 'EmbeddedList';
1135
+ type SchemaIdentifierGenerator = 'None' | 'Sequence' | 'UUID';
1136
+ interface SchemaIdentifier {
1137
+ name: string;
1138
+ generator?: SchemaIdentifierGenerator;
1139
+ type?: SchemaDataType | string;
1140
+ }
1141
+ interface SchemaAttribute {
1142
+ name: string;
1143
+ type: SchemaDataType | string;
1144
+ isNullable?: boolean;
1145
+ }
1146
+ type SchemaIndexType = 'DEFAULT' | 'LUCENE' | string;
1147
+ interface SchemaIndex {
1148
+ name: string;
1149
+ type?: SchemaIndexType;
1150
+ minimumScore?: number;
1151
+ }
1152
+ interface SchemaResolver {
1153
+ name: string;
1154
+ resolver: string;
1155
+ }
1156
+ type SchemaTriggerEvent = 'PreInsert' | 'PostInsert' | 'PrePersist' | 'PostPersist' | 'PreUpdate' | 'PostUpdate' | 'PreDelete' | 'PostDelete' | string;
1157
+ interface SchemaTrigger {
1158
+ name: string;
1159
+ event: SchemaTriggerEvent;
1160
+ trigger: string;
1161
+ }
1162
+ interface SchemaEntity {
1163
+ name: string;
1164
+ identifier?: SchemaIdentifier;
1165
+ partition?: string;
1166
+ attributes?: SchemaAttribute[];
1167
+ indexes?: SchemaIndex[];
1168
+ resolvers?: SchemaResolver[];
1169
+ triggers?: SchemaTrigger[];
1170
+ }
1171
+ interface SchemaRevisionMetadata {
1172
+ revisionId?: string;
1173
+ createdAt?: Date;
1174
+ publishedAt?: Date;
1175
+ }
1176
+ interface SchemaRevision {
1177
+ databaseId: string;
1178
+ revisionDescription?: string;
1179
+ entities: SchemaEntity[];
1180
+ meta?: SchemaRevisionMetadata;
1181
+ }
1182
+ type SchemaHistoryEntry = SchemaRevision;
1183
+ type SchemaUpsertRequest = Omit<SchemaRevision, 'databaseId' | 'meta'> & {
1184
+ databaseId?: string;
1185
+ };
1186
+ interface SchemaValidationResult {
1187
+ valid?: boolean;
1188
+ schema?: SchemaRevision;
1189
+ errors?: Array<{
1190
+ message: string;
1191
+ }>;
1192
+ }
1056
1193
 
1057
1194
  /** -------------------------
1058
1195
  * Facade export
@@ -1187,4 +1324,4 @@ declare const percentile: (attribute: string, p: number) => string;
1187
1324
  declare const sdkName = "@onyx.dev/onyx-database";
1188
1325
  declare const sdkVersion = "0.1.0";
1189
1326
 
1190
- export { type FetchImpl, type FetchResponse, type ICascadeBuilder, type ICascadeRelationshipBuilder, type IConditionBuilder, type IOnyxDatabase, type IQueryBuilder, type ISaveBuilder, type LogicalOperator, type OnyxConfig, type OnyxDocument, type OnyxFacade, type QueryCondition, type QueryCriteria, type QueryCriteriaOperator, type QueryPage, QueryResults, type QueryResultsPromise, type SelectQuery, type Sort, type StreamAction, type UpdateQuery, asc, avg, between, contains, containsIgnoreCase, count, desc, eq, gt, gte, inOp, isNull, like, lower, lt, lte, matches, max, median, min, neq, notContains, notContainsIgnoreCase, notIn, notLike, notMatches, notNull, notStartsWith, onyx, percentile, replace, sdkName, sdkVersion, startsWith, std, substring, sum, upper, variance };
1327
+ export { type FetchImpl, type FetchResponse, type ICascadeBuilder, type ICascadeRelationshipBuilder, type IConditionBuilder, type IOnyxDatabase, type IQueryBuilder, type ISaveBuilder, type LogicalOperator, type OnyxConfig, type OnyxDocument, type OnyxFacade, type QueryCondition, type QueryCriteria, type QueryCriteriaOperator, type QueryPage, QueryResults, type QueryResultsPromise, type SchemaAttribute, type SchemaDataType, type SchemaEntity, type SchemaHistoryEntry, type SchemaIdentifier, type SchemaIdentifierGenerator, type SchemaIndex, type SchemaIndexType, type SchemaResolver, type SchemaRevision, type SchemaRevisionMetadata, type SchemaTrigger, type SchemaTriggerEvent, type SchemaUpsertRequest, type SchemaValidationResult, type SecretMetadata, type SecretRecord, type SecretSaveRequest, type SecretsListResponse, type SelectQuery, type Sort, type StreamAction, type UpdateQuery, asc, avg, between, contains, containsIgnoreCase, count, desc, eq, gt, gte, inOp, isNull, like, lower, lt, lte, matches, max, median, min, neq, notContains, notContainsIgnoreCase, notIn, notLike, notMatches, notNull, notStartsWith, onyx, percentile, replace, sdkName, sdkVersion, startsWith, std, substring, sum, upper, variance };
package/dist/index.js CHANGED
@@ -340,7 +340,8 @@ var HttpClient = class {
340
340
  ...method === "DELETE" ? { Prefer: "return=representation" } : {},
341
341
  ...extraHeaders ?? {}
342
342
  });
343
- if (body == null) delete headers["Content-Type"];
343
+ const hasExplicitContentType = extraHeaders && "Content-Type" in extraHeaders || Object.prototype.hasOwnProperty.call(this.defaults, "Content-Type");
344
+ if (body == null && !hasExplicitContentType) delete headers["Content-Type"];
344
345
  if (this.requestLoggingEnabled) {
345
346
  console.log(`${method} ${url}`);
346
347
  if (body != null) {
@@ -957,6 +958,33 @@ function serializeDates(value) {
957
958
  }
958
959
  return value;
959
960
  }
961
+ function normalizeSecretMetadata(input) {
962
+ return { ...input, updatedAt: new Date(input.updatedAt) };
963
+ }
964
+ function normalizeSecretRecord(input) {
965
+ return { ...input, updatedAt: new Date(input.updatedAt) };
966
+ }
967
+ function normalizeDate(value) {
968
+ if (value == null) return void 0;
969
+ if (value instanceof Date) return value;
970
+ const ts = new Date(value);
971
+ return Number.isNaN(ts.getTime()) ? void 0 : ts;
972
+ }
973
+ function normalizeSchemaRevision(input, fallbackDatabaseId) {
974
+ const { meta, createdAt, publishedAt, revisionId, ...rest } = input;
975
+ const mergedMeta = {
976
+ revisionId: meta?.revisionId ?? revisionId,
977
+ createdAt: normalizeDate(meta?.createdAt ?? createdAt),
978
+ publishedAt: normalizeDate(meta?.publishedAt ?? publishedAt)
979
+ };
980
+ const cleanedMeta = mergedMeta.revisionId || mergedMeta.createdAt || mergedMeta.publishedAt ? mergedMeta : void 0;
981
+ return {
982
+ ...rest,
983
+ databaseId: input.databaseId ?? fallbackDatabaseId,
984
+ meta: cleanedMeta,
985
+ entities: input.entities ?? []
986
+ };
987
+ }
960
988
  var OnyxDatabaseImpl = class {
961
989
  cfgPromise;
962
990
  resolved = null;
@@ -1090,6 +1118,86 @@ var OnyxDatabaseImpl = class {
1090
1118
  )}`;
1091
1119
  return http.request("DELETE", path);
1092
1120
  }
1121
+ async getSchema(options) {
1122
+ const { http, databaseId } = await this.ensureClient();
1123
+ const params = new URLSearchParams();
1124
+ const tables = options?.tables;
1125
+ const tableList = Array.isArray(tables) ? tables : typeof tables === "string" ? tables.split(",") : [];
1126
+ const normalizedTables = tableList.map((t) => t.trim()).filter(Boolean);
1127
+ if (normalizedTables.length) {
1128
+ params.append("tables", normalizedTables.map(encodeURIComponent).join(","));
1129
+ }
1130
+ const path = `/schemas/${encodeURIComponent(databaseId)}${params.size ? `?${params.toString()}` : ""}`;
1131
+ const res = await http.request("GET", path);
1132
+ return normalizeSchemaRevision(res, databaseId);
1133
+ }
1134
+ async getSchemaHistory() {
1135
+ const { http, databaseId } = await this.ensureClient();
1136
+ const path = `/schemas/history/${encodeURIComponent(databaseId)}`;
1137
+ const res = await http.request("GET", path);
1138
+ return Array.isArray(res) ? res.map((entry) => normalizeSchemaRevision(entry, databaseId)) : [];
1139
+ }
1140
+ async updateSchema(schema, options) {
1141
+ const { http, databaseId } = await this.ensureClient();
1142
+ const params = new URLSearchParams();
1143
+ if (options?.publish) params.append("publish", "true");
1144
+ const path = `/schemas/${encodeURIComponent(databaseId)}${params.size ? `?${params.toString()}` : ""}`;
1145
+ const body = { ...schema, databaseId: schema.databaseId ?? databaseId };
1146
+ const res = await http.request("PUT", path, serializeDates(body));
1147
+ return normalizeSchemaRevision(res, databaseId);
1148
+ }
1149
+ async validateSchema(schema) {
1150
+ const { http, databaseId } = await this.ensureClient();
1151
+ const path = `/schemas/${encodeURIComponent(databaseId)}/validate`;
1152
+ const body = { ...schema, databaseId: schema.databaseId ?? databaseId };
1153
+ const res = await http.request("POST", path, serializeDates(body));
1154
+ const normalizedSchema = res.schema ? normalizeSchemaRevision(res.schema, databaseId) : void 0;
1155
+ return {
1156
+ ...res,
1157
+ valid: res.valid ?? true,
1158
+ schema: normalizedSchema
1159
+ };
1160
+ }
1161
+ async listSecrets() {
1162
+ const { http, databaseId } = await this.ensureClient();
1163
+ const path = `/database/${encodeURIComponent(databaseId)}/secret`;
1164
+ const response = await http.request(
1165
+ "GET",
1166
+ path,
1167
+ void 0,
1168
+ { "Content-Type": "application/json" }
1169
+ );
1170
+ const records = (response.records ?? []).map(normalizeSecretMetadata);
1171
+ return {
1172
+ ...response,
1173
+ records,
1174
+ meta: response.meta ?? { totalRecords: records.length }
1175
+ };
1176
+ }
1177
+ async getSecret(key) {
1178
+ const { http, databaseId } = await this.ensureClient();
1179
+ const path = `/database/${encodeURIComponent(databaseId)}/secret/${encodeURIComponent(key)}`;
1180
+ const record = await http.request("GET", path, void 0, {
1181
+ "Content-Type": "application/json"
1182
+ });
1183
+ return normalizeSecretRecord(record);
1184
+ }
1185
+ async putSecret(key, input) {
1186
+ const { http, databaseId } = await this.ensureClient();
1187
+ const path = `/database/${encodeURIComponent(databaseId)}/secret/${encodeURIComponent(key)}`;
1188
+ const response = await http.request("PUT", path, serializeDates(input));
1189
+ return normalizeSecretMetadata(response);
1190
+ }
1191
+ async deleteSecret(key) {
1192
+ const { http, databaseId } = await this.ensureClient();
1193
+ const path = `/database/${encodeURIComponent(databaseId)}/secret/${encodeURIComponent(key)}`;
1194
+ const response = await http.request(
1195
+ "DELETE",
1196
+ path
1197
+ );
1198
+ const deletedKey = response && typeof response === "object" && "key" in response ? response.key : void 0;
1199
+ return { key: deletedKey ?? key };
1200
+ }
1093
1201
  close() {
1094
1202
  for (const h of Array.from(this.streams)) {
1095
1203
  try {