monorise 1.15.0-dev.0 → 1.15.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.
@@ -1,20 +1,20 @@
1
- import { Entity as Entity$2, EntitySchemaMap, createEntityConfig, WhereConditions, ApiKeyPolicies, ApiKeyRoutePermission, CompiledApiKeyPolicy } from '../base/index';
1
+ import { Entity as Entity$2, EntitySchemaMap, createEntityConfig, SearchSettings, ResolvedSearchConfig, WhereConditions } from '../base/index';
2
2
  import * as hono from 'hono';
3
- import { Hono, MiddlewareHandler } from 'hono';
3
+ import { Hono } from 'hono';
4
4
  import * as _aws_sdk_client_dynamodb from '@aws-sdk/client-dynamodb';
5
5
  import { DynamoDB, TransactWriteItemsInput, AttributeValue, TransactWriteItem, UpdateItemCommandInput, DynamoDBClient } from '@aws-sdk/client-dynamodb';
6
6
  import * as hono_utils_http_status from 'hono/utils/http-status';
7
7
  import * as hono_utils_types from 'hono/utils/types';
8
8
  import { createFactory } from 'hono/factory';
9
+ import httpStatus4 from 'http-status';
9
10
  import { unmarshall, marshall } from '@aws-sdk/util-dynamodb';
10
- import { AsyncLocalStorage } from 'async_hooks';
11
11
  import { EventBridgeClient } from '@aws-sdk/client-eventbridge';
12
12
  import { AthenaClient } from '@aws-sdk/client-athena';
13
13
  import { FirehoseClient } from '@aws-sdk/client-firehose';
14
14
  import { LambdaClient } from '@aws-sdk/client-lambda';
15
15
  import { S3Client } from '@aws-sdk/client-s3';
16
16
  import * as hono_aws_lambda from 'hono/aws-lambda';
17
- import { SQSEvent, SQSBatchItemFailure, DynamoDBBatchItemFailure, APIGatewayProxyWebsocketEventV2, APIGatewayProxyResultV2, DynamoDBStreamEvent } from 'aws-lambda';
17
+ import { SQSEvent, SQSBatchItemFailure, DynamoDBBatchItemFailure, Context, APIGatewayProxyWebsocketEventV2, APIGatewayProxyResultV2, DynamoDBStreamEvent } from 'aws-lambda';
18
18
  import { _Record } from '@aws-sdk/client-dynamodb-streams';
19
19
 
20
20
  type EventDetail = {
@@ -291,6 +291,65 @@ declare class MutualRepository extends Repository {
291
291
  }): Promise<void>;
292
292
  }
293
293
 
294
+ /**
295
+ * Word index for entities configured with `search`. Each word an entity is
296
+ * indexed by is a copy of the entity at PK `SEARCH#<type>`, SK
297
+ * `<word>#<entityId>`, with R1PK set to the entity so the replication
298
+ * processor keeps its data current and removes it with the entity.
299
+ */
300
+ declare class SearchRepository {
301
+ private readonly EntityConfig;
302
+ private readonly TABLE_NAME;
303
+ private readonly dynamodbClient;
304
+ private readonly entityRepository;
305
+ private readonly searchDefaults?;
306
+ private readyTypes;
307
+ constructor(EntityConfig: Record<Entity$2, ReturnType<typeof createEntityConfig>>, TABLE_NAME: string, dynamodbClient: DynamoDB, entityRepository: EntityRepository, searchDefaults?: SearchSettings | undefined);
308
+ /** The resolved `search` config, or undefined if the type isn't indexed. */
309
+ searchConfig(entityType: Entity$2): ResolvedSearchConfig | undefined;
310
+ indexedEntityTypes(): Entity$2[];
311
+ private rowKeys;
312
+ private searchRow;
313
+ /** Puts a row for each word in `add` and deletes the rows in `remove`. */
314
+ writeRows<T extends Entity$2>(entity: Entity$1<T>, add: string[], remove: string[]): Promise<void>;
315
+ /** The words an entity currently has rows for, read from the GSI. */
316
+ existingWords(entityType: Entity$2, entityId: string): Promise<string[]>;
317
+ getIndexState(entityType: Entity$2): Promise<{
318
+ state?: string;
319
+ configHash?: string;
320
+ } | undefined>;
321
+ markIndexBuilding(entityType: Entity$2, configHash: string): Promise<void>;
322
+ /**
323
+ * Marks the index ready, unless a newer reindex has taken over since: its
324
+ * config hash replaces this one when it starts.
325
+ */
326
+ markIndexReady(entityType: Entity$2, configHash: string): Promise<boolean>;
327
+ /** Whether the index was fully built for the current config. */
328
+ isIndexReady(entityType: Entity$2, config: ResolvedSearchConfig): Promise<boolean>;
329
+ /** Deletes the marker, so the next reindex rebuilds the type in full. */
330
+ clearIndexState(entityType: Entity$2): Promise<void>;
331
+ /**
332
+ * Brings one entity's rows in line with its current data and config. It
333
+ * runs alongside the stream, which may write a newer version of the same
334
+ * rows, so each write only goes through over an older copy.
335
+ */
336
+ reindexEntity(entityType: Entity$2, entityId: string, config: ResolvedSearchConfig): Promise<void>;
337
+ private lookUp;
338
+ /**
339
+ * Every entity matching `query`, newest first. Reads the rows of the
340
+ * query's longest word, or scans every entity while the index is still
341
+ * being built for the current config. Both give the same matches.
342
+ *
343
+ * There's no `totalCount`: counting every entity of the type would take
344
+ * the scan the index avoids. `filteredCount` is the number of matches.
345
+ */
346
+ searchEntities<T extends Entity$2>(entityType: T, query: string): Promise<{
347
+ items: Entity$1<T>[];
348
+ totalCount?: undefined;
349
+ filteredCount: number;
350
+ }>;
351
+ }
352
+
294
353
  declare class TaggedEntity<T extends Entity$2> extends Entity$1<T> {
295
354
  tagName: string;
296
355
  group?: string;
@@ -566,8 +625,22 @@ var Entity = class _Entity extends Item {
566
625
  };
567
626
  }
568
627
  };
569
- new AsyncLocalStorage();
570
- createFactory();
628
+ var factory = createFactory();
629
+ var API_KEYS = process.env.API_KEYS ? JSON.parse(process.env.API_KEYS) : [];
630
+ factory.createMiddleware((c, next) => __async(null, null, function* () {
631
+ const xApiKey = c.req.header("x-api-key");
632
+ if (c.req.url.match(/^\/core\/public\//)) {
633
+ return yield next();
634
+ }
635
+ if (!xApiKey || Array.isArray(xApiKey) || !API_KEYS.includes(xApiKey)) {
636
+ c.status(httpStatus4.UNAUTHORIZED);
637
+ return c.json({
638
+ status: httpStatus4.UNAUTHORIZED,
639
+ message: httpStatus4["401_MESSAGE"]
640
+ });
641
+ }
642
+ return yield next();
643
+ }));
571
644
 
572
645
  // helpers/event.ts
573
646
  new EventBridgeClient();
@@ -4629,7 +4702,8 @@ declare class GetEntityController {
4629
4702
 
4630
4703
  declare class ListEntitiesController {
4631
4704
  private entityRepository;
4632
- constructor(entityRepository: EntityRepository);
4705
+ private searchRepository;
4706
+ constructor(entityRepository: EntityRepository, searchRepository: SearchRepository);
4633
4707
  controller: hono.MiddlewareHandler<any, string, {}, Response & hono.TypedResponse<{
4634
4708
  data: {
4635
4709
  [x: string]: hono_utils_types.JSONValue;
@@ -4974,8 +5048,7 @@ declare class DependencyContainer {
4974
5048
  EntityConfig: Record<Entity$2, ReturnType<typeof createEntityConfig>>;
4975
5049
  AllowedEntityTypes: Entity$2[];
4976
5050
  EmailAuthEnabledEntities: Entity$2[];
4977
- /** Policies from the file `apiKeys` points to in monorise.config.ts. */
4978
- ApiKeyPolicies?: ApiKeyPolicies;
5051
+ SearchDefaults?: SearchSettings;
4979
5052
  tableName?: string;
4980
5053
  };
4981
5054
  private _instanceCache;
@@ -4985,8 +5058,7 @@ declare class DependencyContainer {
4985
5058
  EntityConfig: Record<Entity$2, ReturnType<typeof createEntityConfig>>;
4986
5059
  AllowedEntityTypes: Entity$2[];
4987
5060
  EmailAuthEnabledEntities: Entity$2[];
4988
- /** Policies from the file `apiKeys` points to in monorise.config.ts. */
4989
- ApiKeyPolicies?: ApiKeyPolicies;
5061
+ SearchDefaults?: SearchSettings;
4990
5062
  tableName?: string;
4991
5063
  });
4992
5064
  createCachedInstance<T extends new (...args: any[]) => any>(ClassRef: T, ...args: ConstructorParameters<T>): InstanceType<T>;
@@ -4996,6 +5068,7 @@ declare class DependencyContainer {
4996
5068
  get dbUtils(): DbUtils;
4997
5069
  get eventUtils(): EventUtils;
4998
5070
  get entityRepository(): EntityRepository;
5071
+ get searchRepository(): SearchRepository;
4999
5072
  get mutualRepository(): MutualRepository;
5000
5073
  get entityServiceLifeCycle(): EntityServiceLifeCycle;
5001
5074
  get entityService(): EntityService;
@@ -5085,11 +5158,11 @@ declare const analyticsQueryHandler: () => <L extends hono_aws_lambda.LambdaEven
5085
5158
  multiValueHeaders?: undefined;
5086
5159
  })>;
5087
5160
 
5088
- declare const handler$9: (container: DependencyContainer) => (ev: SQSEvent) => Promise<{
5161
+ declare const handler$a: (container: DependencyContainer) => (ev: SQSEvent) => Promise<{
5089
5162
  batchItemFailures: SQSBatchItemFailure[];
5090
5163
  }>;
5091
5164
 
5092
- declare const handler$8: (config: Record<Entity$2, ReturnType<typeof createEntityConfig>>) => (event: {
5165
+ declare const handler$9: (config: Record<Entity$2, ReturnType<typeof createEntityConfig>>) => (event: {
5093
5166
  Records: _Record[];
5094
5167
  }) => Promise<{
5095
5168
  batchItemFailures: DynamoDBBatchItemFailure[];
@@ -5117,7 +5190,7 @@ declare function startBackfill(reconcile?: boolean): Promise<{
5117
5190
  exportTime: string | undefined;
5118
5191
  started: boolean;
5119
5192
  }>;
5120
- declare const handler$7: (config: Config) => (event: S3ExportEvent | BackfillLaunchEvent) => Promise<{
5193
+ declare const handler$8: (config: Config) => (event: S3ExportEvent | BackfillLaunchEvent) => Promise<{
5121
5194
  exportArn: string | undefined;
5122
5195
  exportTime: string | undefined;
5123
5196
  started: boolean;
@@ -5148,26 +5221,50 @@ type Dataset = {
5148
5221
  type Manifest = {
5149
5222
  datasets: Dataset[];
5150
5223
  };
5151
- declare const handler$6: (configuredManifest?: Manifest) => () => Promise<void>;
5224
+ declare const handler$7: (configuredManifest?: Manifest) => () => Promise<void>;
5152
5225
 
5153
- declare const handler$5: () => Promise<void>;
5226
+ declare const handler$6: () => Promise<void>;
5154
5227
 
5155
- declare const handler$4: () => Promise<void>;
5228
+ declare const handler$5: () => Promise<void>;
5156
5229
 
5157
- declare const handler$3: (container: DependencyContainer) => (ev: SQSEvent) => Promise<{
5230
+ declare const handler$4: (container: DependencyContainer) => (ev: SQSEvent) => Promise<{
5158
5231
  batchItemFailures: SQSBatchItemFailure[];
5159
5232
  }>;
5160
5233
 
5161
- declare const handler$2: (container: DependencyContainer) => (ev: SQSEvent) => Promise<{
5234
+ declare const handler$3: (container: DependencyContainer) => (ev: SQSEvent) => Promise<{
5162
5235
  batchItemFailures: SQSBatchItemFailure[];
5163
5236
  }>;
5164
5237
 
5165
- declare const handler$1: (container: DependencyContainer) => (event: {
5238
+ declare const handler$2: (container: DependencyContainer) => (event: {
5166
5239
  Records: _Record[];
5167
5240
  }) => Promise<{
5168
5241
  batchItemFailures: DynamoDBBatchItemFailure[];
5169
5242
  }>;
5170
5243
 
5244
+ type SearchReindexEvent = {
5245
+ action: 'start';
5246
+ force?: boolean;
5247
+ } | {
5248
+ action: 'reindex';
5249
+ entityType: Entity$2;
5250
+ configHash: string;
5251
+ lastKey?: string;
5252
+ failures?: number;
5253
+ };
5254
+ /**
5255
+ * Builds the search index for entities that existed before their `search`
5256
+ * config did, or before it changed. Search scans every entity until a type
5257
+ * is marked ready. Runs as one invocation per entity type, each handing the
5258
+ * rest of its type to a new invocation when it runs low on time. Rows are
5259
+ * only listed here: each entity is read again before its rows are written.
5260
+ *
5261
+ * A page that fails is retried by a new invocation from the same page. Once
5262
+ * it has failed MAX_FAILURES times in a row the invocation throws, so the
5263
+ * function's error alarm fires; the type keeps scanning until a forced start
5264
+ * or a config change rebuilds it.
5265
+ */
5266
+ declare const handler$1: (container: DependencyContainer, invoke?: (event: SearchReindexEvent) => Promise<void>, pause?: (ms: number) => Promise<unknown>) => (event: SearchReindexEvent, context?: Pick<Context, "getRemainingTimeInMillis">) => Promise<void>;
5267
+
5171
5268
  declare const handler: (container: DependencyContainer) => (ev: SQSEvent) => Promise<{
5172
5269
  batchItemFailures: SQSBatchItemFailure[];
5173
5270
  }>;
@@ -5213,59 +5310,16 @@ declare const transactional: {
5213
5310
  deleteMutual: <B extends Entity$2, T extends Entity$2>(byEntityType: B, entityType: T, byEntityId: string, entityId: string) => TransactionDeleteMutual<B, T>;
5214
5311
  };
5215
5312
 
5216
- /**
5217
- * `read` is get, by ID or unique field. `list` is listing the whole type,
5218
- * which also needs `read`.
5219
- */
5220
- type EntityAction = 'read' | 'list' | 'create' | 'update' | 'delete';
5221
- /**
5222
- * Declares the permission a custom route requires. Policies grant it by name
5223
- * in `routes`; `full` keys always pass. Works per route or on a group:
5224
- *
5225
- * @example
5226
- * ```ts
5227
- * app.post('/checkout', requires('checkout'), handler);
5228
- * app.use('/reports/*', requires('reports'));
5229
- * ```
5230
- */
5231
- declare const requires: (permission: ApiKeyRoutePermission) => MiddlewareHandler;
5232
-
5233
- type ApiKeyPrincipal = {
5234
- /** Name of the policy the request's key maps to, e.g. `'full'`. */
5235
- policy: string;
5236
- /** SHA-256 hex digest of the key. Safe to log or store; the key itself is not. */
5237
- fingerprint: string;
5238
- /** What the policy grants, per entity type and relationship direction. */
5239
- access: CompiledApiKeyPolicy;
5240
- /**
5241
- * Whether the policy allows an action on an entity type, and on every
5242
- * listed field when `fields` is given. `read` is get by ID; `list` is
5243
- * listing the whole type.
5244
- */
5245
- can(action: EntityAction, entityType: string, fields?: readonly string[]): boolean;
5246
- /** Whether the policy grants a custom route permission. */
5247
- has(permission: ApiKeyRoutePermission): boolean;
5248
- /**
5249
- * An entity, tag or relationship record with the fields the key cannot read
5250
- * removed from `data` (and `mutualData`). Accepts an `Entity` or its JSON.
5251
- */
5252
- mask<T extends object>(entityType: string, entity: T): Record<string, unknown>;
5253
- };
5254
- declare module 'hono' {
5255
- interface ContextVariableMap {
5256
- apiKey: ApiKeyPrincipal;
5257
- }
5258
- }
5259
-
5260
5313
  declare class CoreFactory {
5261
5314
  private config;
5262
5315
  setupCommonRoutes: ReturnType<typeof setupCommonRoutes>;
5263
- mutualProcessor: ReturnType<typeof handler$3>;
5264
- replicationProcessor: ReturnType<typeof handler$1>;
5265
- createEntityProcessor: ReturnType<typeof handler$9>;
5266
- analyticsProcessor: ReturnType<typeof handler$8>;
5267
- analyticsBackfillProcessor: ReturnType<typeof handler$7>;
5268
- prejoinProcessor: ReturnType<typeof handler$2>;
5316
+ mutualProcessor: ReturnType<typeof handler$4>;
5317
+ replicationProcessor: ReturnType<typeof handler$2>;
5318
+ searchReindexProcessor: ReturnType<typeof handler$1>;
5319
+ createEntityProcessor: ReturnType<typeof handler$a>;
5320
+ analyticsProcessor: ReturnType<typeof handler$9>;
5321
+ analyticsBackfillProcessor: ReturnType<typeof handler$8>;
5322
+ prejoinProcessor: ReturnType<typeof handler$3>;
5269
5323
  tagProcessor: ReturnType<typeof handler>;
5270
5324
  appHandler: ReturnType<typeof appHandler>;
5271
5325
  wsConnect: ReturnType<typeof connect>;
@@ -5277,8 +5331,8 @@ declare class CoreFactory {
5277
5331
  EntityConfig: Record<Entity$2, ReturnType<typeof createEntityConfig>>;
5278
5332
  AllowedEntityTypes: Entity$2[];
5279
5333
  EmailAuthEnabledEntities: Entity$2[];
5280
- ApiKeyPolicies?: ApiKeyPolicies;
5334
+ SearchDefaults?: SearchSettings;
5281
5335
  });
5282
5336
  }
5283
5337
 
5284
- export { type ApiKeyPrincipal, DependencyContainer, Entity$1 as Entity, type EntityAction, EntityRepository, EntityService, Mutual, MutualRepository, MutualService, PROJECTION_EXPRESSION, StandardError, StandardErrorCode, TagRepository, TransactionService, WebSocketRepository, handler$7 as analyticsBackfillProcessor, handler$6 as analyticsMaterializationProcessor, handler$5 as analyticsModelProcessor, handler$8 as analyticsProcessor, analyticsQueryHandler, handler$4 as analyticsViewProcessor, appHandler, handler$9 as createEntityProcessor, CoreFactory as default, handler$3 as mutualProcessor, handler$2 as prejoinProcessor, handler$1 as replicationProcessor, requires, setupCommonRoutes, startBackfill as startAnalyticsBackfill, handler as tagProcessor, transactional, broadcast as wsBroadcast, connect as wsConnect, $default as wsDefault, disconnect as wsDisconnect };
5338
+ export { DependencyContainer, Entity$1 as Entity, EntityRepository, EntityService, Mutual, MutualRepository, MutualService, PROJECTION_EXPRESSION, SearchRepository, StandardError, StandardErrorCode, TagRepository, TransactionService, WebSocketRepository, handler$8 as analyticsBackfillProcessor, handler$7 as analyticsMaterializationProcessor, handler$6 as analyticsModelProcessor, handler$9 as analyticsProcessor, analyticsQueryHandler, handler$5 as analyticsViewProcessor, appHandler, handler$a as createEntityProcessor, CoreFactory as default, handler$4 as mutualProcessor, handler$3 as prejoinProcessor, handler$2 as replicationProcessor, handler$1 as searchReindexProcessor, setupCommonRoutes, startBackfill as startAnalyticsBackfill, handler as tagProcessor, transactional, broadcast as wsBroadcast, connect as wsConnect, $default as wsDefault, disconnect as wsDisconnect };