@lunora/server 1.0.0-alpha.101 → 1.0.0-alpha.103
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.mts +58 -18
- package/dist/index.d.ts +58 -18
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-TegvdZ1v.mjs → ACTION_CACHE_DEFAULT_TTL_MS-u1YNydNU.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs +1 -0
- package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BbnXQrHY.mjs +1 -0
- package/dist/packem_shared/{buildRlsReadRegistry-BMJeR-II.mjs → buildRlsReadRegistry-DrYtoBP_.mjs} +1 -1
- package/dist/packem_shared/httpAction-YRpmc049.mjs +5 -0
- package/dist/packem_shared/{mask-DiBA2jnw.mjs → mask-424UQYq0.mjs} +1 -1
- package/dist/packem_shared/{middleware-BU9adRMp.mjs → middleware-BvY85EHz.mjs} +1 -1
- package/dist/packem_shared/{rls-DHJNlHjU.mjs → rls-D2eRaOJj.mjs} +1 -1
- package/dist/packem_shared/{serveStorageObject-Cof46mpm.mjs → serveStorageObject-te5TWJIE.mjs} +1 -1
- package/dist/packem_shared/storageRules-za3ylMEQ.mjs +1 -0
- package/dist/packem_shared/wire-codec-BiYbPSuZ.mjs +1 -0
- package/dist/rls/testing.mjs +1 -1
- package/package.json +4 -4
- package/dist/packem_shared/DEFAULT_LIMIT-DC-M6faS.mjs +0 -1
- package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-Bs1tdJu1.mjs +0 -1
- package/dist/packem_shared/httpAction-CF2zTm9X.mjs +0 -5
- package/dist/packem_shared/storageRules-ClZXWHBt.mjs +0 -1
- package/dist/packem_shared/wire-codec-BOMWQpoF.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1612,14 +1612,23 @@ interface OrmLike {
|
|
|
1612
1612
|
declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
|
|
1613
1613
|
/** HTTP verbs the typed {@link httpRoute} builder can bind to. */
|
|
1614
1614
|
type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
|
|
1615
|
+
/** The `run*` trio, shared between {@link HttpActionCtx} itself and its `forShard(key)` view. */
|
|
1616
|
+
type HttpRunners = Pick<ActionCtx, "runAction" | "runMutation" | "runQuery">;
|
|
1615
1617
|
/**
|
|
1616
1618
|
* Context handed to an HTTP action handler. A narrower view of {@link ActionContext}:
|
|
1617
1619
|
* HTTP actions run in the worker (the "action runtime"), separate from the
|
|
1618
1620
|
* transactional store, so there is no direct `db` / `vectors` surface — reach the
|
|
1619
|
-
* data layer through `runQuery` / `runMutation` / `runAction`, which forward
|
|
1620
|
-
*
|
|
1621
|
+
* data layer through `runQuery` / `runMutation` / `runAction`, which forward an
|
|
1622
|
+
* RPC to a shard. `db`'s absence is principled: an HTTP handler is not
|
|
1621
1623
|
* transactional.
|
|
1622
1624
|
*
|
|
1625
|
+
* WHICH shard is the handler's to choose. A query/mutation ctx is already inside
|
|
1626
|
+
* the owning DO, so its `ctx.run*` has nowhere else to go; an HTTP action runs in
|
|
1627
|
+
* the worker, one hop away from every shard, so the bare `ctx.run*` targets the
|
|
1628
|
+
* DEFAULT shard and {@link HttpActionCtx.forShard} names any other. On a
|
|
1629
|
+
* `.shardBy(...)` app that distinction is the whole ballgame — the default shard
|
|
1630
|
+
* is the root DO, which holds none of a sharded table's rows.
|
|
1631
|
+
*
|
|
1623
1632
|
* `scheduler` and `storage` ARE present, because neither needs the shard — the
|
|
1624
1633
|
* scheduler talks to the scheduler DO, and R2 is a worker binding an HTTP
|
|
1625
1634
|
* handler can reach where an action does. Both are optional: each exists only
|
|
@@ -1636,6 +1645,19 @@ type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PU
|
|
|
1636
1645
|
* the helper even on the branches that never went near storage.
|
|
1637
1646
|
*/
|
|
1638
1647
|
type HttpActionCtx = {
|
|
1648
|
+
/**
|
|
1649
|
+
* The same `run*` trio bound to `shardKey`, mirroring
|
|
1650
|
+
* `createShardClient(...).forShard(key)`:
|
|
1651
|
+
*
|
|
1652
|
+
* ```ts
|
|
1653
|
+
* const rows = await ctx.forShard(channelId).runQuery(api.messages.list, { channelId });
|
|
1654
|
+
* ```
|
|
1655
|
+
*
|
|
1656
|
+
* Without it a webhook / REST route on a `.shardBy(...)` app could only reach
|
|
1657
|
+
* the default (root) shard, so it read an empty table and wrote to the wrong
|
|
1658
|
+
* DO — silently, with no way to say otherwise.
|
|
1659
|
+
*/
|
|
1660
|
+
readonly forShard: (shardKey: string) => HttpRunners;
|
|
1639
1661
|
readonly scheduler?: ActionCtx["scheduler"];
|
|
1640
1662
|
readonly storage?: ActionCtx["storage"];
|
|
1641
1663
|
/**
|
|
@@ -1653,7 +1675,7 @@ type HttpActionCtx = {
|
|
|
1653
1675
|
* its absence made them silently no-op rather than fail.
|
|
1654
1676
|
*/
|
|
1655
1677
|
readonly waitUntil?: (promise: Promise<unknown>) => void;
|
|
1656
|
-
} & Pick<ActionCtx, "auth" | "cache" | "fetch"
|
|
1678
|
+
} & HttpRunners & Pick<ActionCtx, "auth" | "cache" | "fetch">;
|
|
1657
1679
|
/** A raw handler wrapped by {@link httpAction}. Receives the raw request, returns the raw response. */
|
|
1658
1680
|
type HttpActionHandler = (context: HttpActionCtx, request: Request) => Promise<Response> | Response;
|
|
1659
1681
|
/**
|
|
@@ -1730,7 +1752,8 @@ interface HttpStreamHandlerOptions<SearchParams extends ArgsValidator, Params ex
|
|
|
1730
1752
|
* builder, `.output(validator)` defaults to the `undefined` sentinel — while
|
|
1731
1753
|
* unset the handler is generic over its own return; once set the handler must
|
|
1732
1754
|
* return that type and the result is parsed through the validator before
|
|
1733
|
-
* serialization.
|
|
1755
|
+
* serialization. It binds `.stream()` the same way, per yielded chunk.
|
|
1756
|
+
* `[Output] extends [undefined]` is tuple-wrapped so a union
|
|
1734
1757
|
* `Output` doesn't distribute and the test is for the exact sentinel.
|
|
1735
1758
|
*
|
|
1736
1759
|
* The terminal `.handler()` yields a {@link LunoraRouteHandler} — mount it
|
|
@@ -1759,10 +1782,12 @@ interface HttpRouteBuilder<SearchParams extends ArgsValidator, Body extends Args
|
|
|
1759
1782
|
* iterator completion the route writes a final `event: complete` frame; on
|
|
1760
1783
|
* throw, an `event: error` frame is written with `{code, message}` before
|
|
1761
1784
|
* the stream closes. The chunks are JSON-encoded; `R` is inferred from the
|
|
1762
|
-
* handler's yielded type
|
|
1785
|
+
* handler's yielded type — unless `.output()` was declared, in which case each
|
|
1786
|
+
* chunk must be that type and is parsed through the validator before the frame
|
|
1787
|
+
* is written (a violation ends the stream with an `event: error` frame).
|
|
1763
1788
|
* @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
|
|
1764
1789
|
*/
|
|
1765
|
-
stream: <R>(handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => LunoraRouteHandler;
|
|
1790
|
+
stream: [Output] extends [undefined] ? <R>(handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => LunoraRouteHandler : (handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<Output, void, void> | AsyncIterable<Output>) => LunoraRouteHandler;
|
|
1766
1791
|
/**
|
|
1767
1792
|
* Attach a `Vary` header to the response so Cloudflare stores separate
|
|
1768
1793
|
* cached variants per distinct value of the listed request headers.
|
|
@@ -2400,16 +2425,20 @@ type RlsDatabase = DatabaseWriterLike;
|
|
|
2400
2425
|
*
|
|
2401
2426
|
* The `roles` CLAIM on the resolved identity ({@link readIdentityRoles}) is what
|
|
2402
2427
|
* the identity provider asserted about the caller. `ctx.auth.roles`, set by an
|
|
2403
|
-
* upstream middleware, is what a request-time mapping derived
|
|
2404
|
-
* `@lunora/cloudflare-access`'s `accessRoles()` is the shipped example: the
|
|
2405
|
-
* Access envelope carries `groups`, never `roles`, and that middleware's entire
|
|
2406
|
-
* job is to map verified groups onto role labels here.
|
|
2428
|
+
* upstream middleware, is what a request-time mapping derived.
|
|
2407
2429
|
*
|
|
2408
2430
|
* Reading only the claim silently drops the second, which does not fail loudly —
|
|
2409
2431
|
* a role-gated ALLOW branch stops firing and users lose access, and a role-gated
|
|
2410
|
-
* DENY branch stops firing and rows LEAK.
|
|
2432
|
+
* DENY branch stops firing and rows LEAK. A middleware declares its own context
|
|
2411
2433
|
* type, so there is no compile-time signal either way.
|
|
2412
2434
|
*
|
|
2435
|
+
* The middleware source reaches THIS path only. A live shape runs no procedure,
|
|
2436
|
+
* so `composeShapeReadWhere` sees the claim and nothing else — which is why the
|
|
2437
|
+
* shipped Access mapping mints its roles onto the identity
|
|
2438
|
+
* (`createAccessResolver({ roles })`) instead of into `ctx.auth.roles`. Anything
|
|
2439
|
+
* deriving roles in middleware must accept that shapes will not see them; see
|
|
2440
|
+
* the KNOWN DIVERGENCE note in `./shape-read-base`.
|
|
2441
|
+
*
|
|
2413
2442
|
* What is deliberately absent is the same field on the TEST harness: see
|
|
2414
2443
|
* `TestIdentity` in `./testing`. A middleware setting `ctx.auth.roles` is a real
|
|
2415
2444
|
* request-path producer; a test setting it directly is a world with no producer
|
|
@@ -2492,10 +2521,13 @@ type MaskPolicies<Context = unknown> = Record<string, MaskColumns<Context>>;
|
|
|
2492
2521
|
* - `roles` registers the role→permission grants that back `ctx.auth.can(...)`
|
|
2493
2522
|
* inside a {@link MaskFn} — identical to `rls(policies, { roles })`. A role
|
|
2494
2523
|
* not listed grants no permissions (fails closed for unknown roles).
|
|
2495
|
-
* - `bypass` is a procedure-wide escape hatch: when it returns `true` the
|
|
2496
|
-
* mask is skipped (the caller sees raw values). Use it for a privileged
|
|
2524
|
+
* - `bypass` is a procedure-wide escape hatch: when it returns exactly `true` the
|
|
2525
|
+
* whole mask is skipped (the caller sees raw values). Use it for a privileged
|
|
2497
2526
|
* viewer — `bypass: ({ auth }) => auth.can("pii:view")`. Prefer this over
|
|
2498
2527
|
* branching every column when an entire class of caller should see clear data.
|
|
2528
|
+
* The verdict is compared to `true`, never evaluated for truthiness: returning
|
|
2529
|
+
* a claim (`auth.identity?.role`) rather than a decision is a DENIAL here, not
|
|
2530
|
+
* an unmasked read.
|
|
2499
2531
|
* - `indexFields` closes the bare-index-scan / rank / geo position oracle (see
|
|
2500
2532
|
* the `mask/middleware` module docblock's "Residual read-position oracles" section).
|
|
2501
2533
|
*/
|
|
@@ -3207,10 +3239,17 @@ interface RegisteredShape<Args extends ValidatorMap = ValidatorMap, Context = Qu
|
|
|
3207
3239
|
/** Declare a replication shape. See the module docs for runtime semantics. */
|
|
3208
3240
|
declare const defineShape: <Args extends ValidatorMap = ValidatorMap, Context = QueryCtx>(definition: ShapeDefinition<Args, Context>) => RegisteredShape<Args, Context>;
|
|
3209
3241
|
/**
|
|
3210
|
-
* Operations a storage rule can gate. `read` covers `download` / `getMetadata`
|
|
3211
|
-
* / `getSignedUrl` / `getUrl`; `write` covers `store` /
|
|
3212
|
-
* `delete`
|
|
3213
|
-
*
|
|
3242
|
+
* Operations a storage rule can gate. `read` covers `download` / `getMetadata` /
|
|
3243
|
+
* `head` / `getSignedUrl` / `getUrl`; `write` covers `store` /
|
|
3244
|
+
* `generateUploadUrl`; `delete` covers `delete` and the `deleteAfterCommit`
|
|
3245
|
+
* enqueue; `list` is a prefix listing.
|
|
3246
|
+
*
|
|
3247
|
+
* `list` governs `ctx.db.system.query("_storage")` — the object enumeration
|
|
3248
|
+
* reachable from a handler — plus the file browser / admin path. It governs
|
|
3249
|
+
* nothing on `ctx.storage`, which exposes no `list` (and `storageRules` drops
|
|
3250
|
+
* any). Note the enumeration is additionally narrowed by the bucket's `read`
|
|
3251
|
+
* rules, so a `read` prefix rule scopes what a handler can enumerate even with
|
|
3252
|
+
* no `list` rule declared.
|
|
3214
3253
|
*/
|
|
3215
3254
|
type StorageOperation = "delete" | "list" | "read" | "write";
|
|
3216
3255
|
/** A rule's decision. `true` allows, `false` denies, `undefined` opts this rule out. */
|
|
@@ -3295,8 +3334,9 @@ declare const defineStorageRule: <Context = unknown>(input: DefineStorageRuleInp
|
|
|
3295
3334
|
declare const defineStorageRules: <Context = unknown>(rules: ReadonlyArray<StorageRule<Context>>) => ReadonlyArray<StorageRule<Context>>;
|
|
3296
3335
|
interface StorageContextIn {
|
|
3297
3336
|
auth?: AuthLike;
|
|
3337
|
+
db?: unknown;
|
|
3298
3338
|
storage?: unknown;
|
|
3299
3339
|
}
|
|
3300
3340
|
declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
|
|
3301
3341
|
declare const VERSION = "0.0.0";
|
|
3302
|
-
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
|
3342
|
+
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
package/dist/index.d.ts
CHANGED
|
@@ -1612,14 +1612,23 @@ interface OrmLike {
|
|
|
1612
1612
|
declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
|
|
1613
1613
|
/** HTTP verbs the typed {@link httpRoute} builder can bind to. */
|
|
1614
1614
|
type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
|
|
1615
|
+
/** The `run*` trio, shared between {@link HttpActionCtx} itself and its `forShard(key)` view. */
|
|
1616
|
+
type HttpRunners = Pick<ActionCtx, "runAction" | "runMutation" | "runQuery">;
|
|
1615
1617
|
/**
|
|
1616
1618
|
* Context handed to an HTTP action handler. A narrower view of {@link ActionContext}:
|
|
1617
1619
|
* HTTP actions run in the worker (the "action runtime"), separate from the
|
|
1618
1620
|
* transactional store, so there is no direct `db` / `vectors` surface — reach the
|
|
1619
|
-
* data layer through `runQuery` / `runMutation` / `runAction`, which forward
|
|
1620
|
-
*
|
|
1621
|
+
* data layer through `runQuery` / `runMutation` / `runAction`, which forward an
|
|
1622
|
+
* RPC to a shard. `db`'s absence is principled: an HTTP handler is not
|
|
1621
1623
|
* transactional.
|
|
1622
1624
|
*
|
|
1625
|
+
* WHICH shard is the handler's to choose. A query/mutation ctx is already inside
|
|
1626
|
+
* the owning DO, so its `ctx.run*` has nowhere else to go; an HTTP action runs in
|
|
1627
|
+
* the worker, one hop away from every shard, so the bare `ctx.run*` targets the
|
|
1628
|
+
* DEFAULT shard and {@link HttpActionCtx.forShard} names any other. On a
|
|
1629
|
+
* `.shardBy(...)` app that distinction is the whole ballgame — the default shard
|
|
1630
|
+
* is the root DO, which holds none of a sharded table's rows.
|
|
1631
|
+
*
|
|
1623
1632
|
* `scheduler` and `storage` ARE present, because neither needs the shard — the
|
|
1624
1633
|
* scheduler talks to the scheduler DO, and R2 is a worker binding an HTTP
|
|
1625
1634
|
* handler can reach where an action does. Both are optional: each exists only
|
|
@@ -1636,6 +1645,19 @@ type HttpMethod = "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PU
|
|
|
1636
1645
|
* the helper even on the branches that never went near storage.
|
|
1637
1646
|
*/
|
|
1638
1647
|
type HttpActionCtx = {
|
|
1648
|
+
/**
|
|
1649
|
+
* The same `run*` trio bound to `shardKey`, mirroring
|
|
1650
|
+
* `createShardClient(...).forShard(key)`:
|
|
1651
|
+
*
|
|
1652
|
+
* ```ts
|
|
1653
|
+
* const rows = await ctx.forShard(channelId).runQuery(api.messages.list, { channelId });
|
|
1654
|
+
* ```
|
|
1655
|
+
*
|
|
1656
|
+
* Without it a webhook / REST route on a `.shardBy(...)` app could only reach
|
|
1657
|
+
* the default (root) shard, so it read an empty table and wrote to the wrong
|
|
1658
|
+
* DO — silently, with no way to say otherwise.
|
|
1659
|
+
*/
|
|
1660
|
+
readonly forShard: (shardKey: string) => HttpRunners;
|
|
1639
1661
|
readonly scheduler?: ActionCtx["scheduler"];
|
|
1640
1662
|
readonly storage?: ActionCtx["storage"];
|
|
1641
1663
|
/**
|
|
@@ -1653,7 +1675,7 @@ type HttpActionCtx = {
|
|
|
1653
1675
|
* its absence made them silently no-op rather than fail.
|
|
1654
1676
|
*/
|
|
1655
1677
|
readonly waitUntil?: (promise: Promise<unknown>) => void;
|
|
1656
|
-
} & Pick<ActionCtx, "auth" | "cache" | "fetch"
|
|
1678
|
+
} & HttpRunners & Pick<ActionCtx, "auth" | "cache" | "fetch">;
|
|
1657
1679
|
/** A raw handler wrapped by {@link httpAction}. Receives the raw request, returns the raw response. */
|
|
1658
1680
|
type HttpActionHandler = (context: HttpActionCtx, request: Request) => Promise<Response> | Response;
|
|
1659
1681
|
/**
|
|
@@ -1730,7 +1752,8 @@ interface HttpStreamHandlerOptions<SearchParams extends ArgsValidator, Params ex
|
|
|
1730
1752
|
* builder, `.output(validator)` defaults to the `undefined` sentinel — while
|
|
1731
1753
|
* unset the handler is generic over its own return; once set the handler must
|
|
1732
1754
|
* return that type and the result is parsed through the validator before
|
|
1733
|
-
* serialization.
|
|
1755
|
+
* serialization. It binds `.stream()` the same way, per yielded chunk.
|
|
1756
|
+
* `[Output] extends [undefined]` is tuple-wrapped so a union
|
|
1734
1757
|
* `Output` doesn't distribute and the test is for the exact sentinel.
|
|
1735
1758
|
*
|
|
1736
1759
|
* The terminal `.handler()` yields a {@link LunoraRouteHandler} — mount it
|
|
@@ -1759,10 +1782,12 @@ interface HttpRouteBuilder<SearchParams extends ArgsValidator, Body extends Args
|
|
|
1759
1782
|
* iterator completion the route writes a final `event: complete` frame; on
|
|
1760
1783
|
* throw, an `event: error` frame is written with `{code, message}` before
|
|
1761
1784
|
* the stream closes. The chunks are JSON-encoded; `R` is inferred from the
|
|
1762
|
-
* handler's yielded type
|
|
1785
|
+
* handler's yielded type — unless `.output()` was declared, in which case each
|
|
1786
|
+
* chunk must be that type and is parsed through the validator before the frame
|
|
1787
|
+
* is written (a violation ends the stream with an `event: error` frame).
|
|
1763
1788
|
* @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
|
|
1764
1789
|
*/
|
|
1765
|
-
stream: <R>(handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => LunoraRouteHandler;
|
|
1790
|
+
stream: [Output] extends [undefined] ? <R>(handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<R, void, void> | AsyncIterable<R>) => LunoraRouteHandler : (handler: (options: HttpStreamHandlerOptions<SearchParams, Params>) => AsyncGenerator<Output, void, void> | AsyncIterable<Output>) => LunoraRouteHandler;
|
|
1766
1791
|
/**
|
|
1767
1792
|
* Attach a `Vary` header to the response so Cloudflare stores separate
|
|
1768
1793
|
* cached variants per distinct value of the listed request headers.
|
|
@@ -2400,16 +2425,20 @@ type RlsDatabase = DatabaseWriterLike;
|
|
|
2400
2425
|
*
|
|
2401
2426
|
* The `roles` CLAIM on the resolved identity ({@link readIdentityRoles}) is what
|
|
2402
2427
|
* the identity provider asserted about the caller. `ctx.auth.roles`, set by an
|
|
2403
|
-
* upstream middleware, is what a request-time mapping derived
|
|
2404
|
-
* `@lunora/cloudflare-access`'s `accessRoles()` is the shipped example: the
|
|
2405
|
-
* Access envelope carries `groups`, never `roles`, and that middleware's entire
|
|
2406
|
-
* job is to map verified groups onto role labels here.
|
|
2428
|
+
* upstream middleware, is what a request-time mapping derived.
|
|
2407
2429
|
*
|
|
2408
2430
|
* Reading only the claim silently drops the second, which does not fail loudly —
|
|
2409
2431
|
* a role-gated ALLOW branch stops firing and users lose access, and a role-gated
|
|
2410
|
-
* DENY branch stops firing and rows LEAK.
|
|
2432
|
+
* DENY branch stops firing and rows LEAK. A middleware declares its own context
|
|
2411
2433
|
* type, so there is no compile-time signal either way.
|
|
2412
2434
|
*
|
|
2435
|
+
* The middleware source reaches THIS path only. A live shape runs no procedure,
|
|
2436
|
+
* so `composeShapeReadWhere` sees the claim and nothing else — which is why the
|
|
2437
|
+
* shipped Access mapping mints its roles onto the identity
|
|
2438
|
+
* (`createAccessResolver({ roles })`) instead of into `ctx.auth.roles`. Anything
|
|
2439
|
+
* deriving roles in middleware must accept that shapes will not see them; see
|
|
2440
|
+
* the KNOWN DIVERGENCE note in `./shape-read-base`.
|
|
2441
|
+
*
|
|
2413
2442
|
* What is deliberately absent is the same field on the TEST harness: see
|
|
2414
2443
|
* `TestIdentity` in `./testing`. A middleware setting `ctx.auth.roles` is a real
|
|
2415
2444
|
* request-path producer; a test setting it directly is a world with no producer
|
|
@@ -2492,10 +2521,13 @@ type MaskPolicies<Context = unknown> = Record<string, MaskColumns<Context>>;
|
|
|
2492
2521
|
* - `roles` registers the role→permission grants that back `ctx.auth.can(...)`
|
|
2493
2522
|
* inside a {@link MaskFn} — identical to `rls(policies, { roles })`. A role
|
|
2494
2523
|
* not listed grants no permissions (fails closed for unknown roles).
|
|
2495
|
-
* - `bypass` is a procedure-wide escape hatch: when it returns `true` the
|
|
2496
|
-
* mask is skipped (the caller sees raw values). Use it for a privileged
|
|
2524
|
+
* - `bypass` is a procedure-wide escape hatch: when it returns exactly `true` the
|
|
2525
|
+
* whole mask is skipped (the caller sees raw values). Use it for a privileged
|
|
2497
2526
|
* viewer — `bypass: ({ auth }) => auth.can("pii:view")`. Prefer this over
|
|
2498
2527
|
* branching every column when an entire class of caller should see clear data.
|
|
2528
|
+
* The verdict is compared to `true`, never evaluated for truthiness: returning
|
|
2529
|
+
* a claim (`auth.identity?.role`) rather than a decision is a DENIAL here, not
|
|
2530
|
+
* an unmasked read.
|
|
2499
2531
|
* - `indexFields` closes the bare-index-scan / rank / geo position oracle (see
|
|
2500
2532
|
* the `mask/middleware` module docblock's "Residual read-position oracles" section).
|
|
2501
2533
|
*/
|
|
@@ -3207,10 +3239,17 @@ interface RegisteredShape<Args extends ValidatorMap = ValidatorMap, Context = Qu
|
|
|
3207
3239
|
/** Declare a replication shape. See the module docs for runtime semantics. */
|
|
3208
3240
|
declare const defineShape: <Args extends ValidatorMap = ValidatorMap, Context = QueryCtx>(definition: ShapeDefinition<Args, Context>) => RegisteredShape<Args, Context>;
|
|
3209
3241
|
/**
|
|
3210
|
-
* Operations a storage rule can gate. `read` covers `download` / `getMetadata`
|
|
3211
|
-
* / `getSignedUrl` / `getUrl`; `write` covers `store` /
|
|
3212
|
-
* `delete`
|
|
3213
|
-
*
|
|
3242
|
+
* Operations a storage rule can gate. `read` covers `download` / `getMetadata` /
|
|
3243
|
+
* `head` / `getSignedUrl` / `getUrl`; `write` covers `store` /
|
|
3244
|
+
* `generateUploadUrl`; `delete` covers `delete` and the `deleteAfterCommit`
|
|
3245
|
+
* enqueue; `list` is a prefix listing.
|
|
3246
|
+
*
|
|
3247
|
+
* `list` governs `ctx.db.system.query("_storage")` — the object enumeration
|
|
3248
|
+
* reachable from a handler — plus the file browser / admin path. It governs
|
|
3249
|
+
* nothing on `ctx.storage`, which exposes no `list` (and `storageRules` drops
|
|
3250
|
+
* any). Note the enumeration is additionally narrowed by the bucket's `read`
|
|
3251
|
+
* rules, so a `read` prefix rule scopes what a handler can enumerate even with
|
|
3252
|
+
* no `list` rule declared.
|
|
3214
3253
|
*/
|
|
3215
3254
|
type StorageOperation = "delete" | "list" | "read" | "write";
|
|
3216
3255
|
/** A rule's decision. `true` allows, `false` denies, `undefined` opts this rule out. */
|
|
@@ -3295,8 +3334,9 @@ declare const defineStorageRule: <Context = unknown>(input: DefineStorageRuleInp
|
|
|
3295
3334
|
declare const defineStorageRules: <Context = unknown>(rules: ReadonlyArray<StorageRule<Context>>) => ReadonlyArray<StorageRule<Context>>;
|
|
3296
3335
|
interface StorageContextIn {
|
|
3297
3336
|
auth?: AuthLike;
|
|
3337
|
+
db?: unknown;
|
|
3298
3338
|
storage?: unknown;
|
|
3299
3339
|
}
|
|
3300
3340
|
declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
|
|
3301
3341
|
declare const VERSION = "0.0.0";
|
|
3302
|
-
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
|
3342
|
+
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-
|
|
1
|
+
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-u1YNydNU.mjs";import{initLunora as d}from"./packem_shared/initLunora-D5TSiy5j.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{flushDeferredDeletes as c,withDeferredDeletes as l}from"./packem_shared/flushDeferredDeletes-DEJXlhop.mjs";import{beginDeferredSchedules as u,withDeferredSchedules as S}from"./packem_shared/beginDeferredSchedules-gJlbW6h9.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as T,DOCUMENT_HISTORY_TABLE as g,defineDocumentHistory as A,documentHistoryExtension as D}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BbnXQrHY.mjs";import{LunoraEnvError as _,defineEnv as L,redactSecrets as C}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as y,bindTableFacade as b}from"./packem_shared/bindOrm-ChQydkdL.mjs";import{httpAction as P,httpRoute as F,httpRouter as O,isSafeHeaderValue as H}from"./packem_shared/httpAction-YRpmc049.mjs";import{serveStorageObject as U}from"./packem_shared/serveStorageObject-te5TWJIE.mjs";import{defineIdentity as v}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as B,onDisconnect as V,onShardInit as j}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Y,DEFAULT_MAX_LIMIT as J,clampLimit as K,defineListArgs as Q}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as q}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as G}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as $,d as ee,a as re,b as oe,e as te,f as ne,g as ie,h as fe,i as ae,j as se,k as de,m as me}from"./packem_shared/plugin-yKCbHnlj.mjs";import{PRESENCE_DEFAULT_TTL_MS as xe,PRESENCE_TABLE as ce,definePresence as le,presenceExtension as Ee}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-lsooaSaF.mjs";import{protectPublic as Se}from"./packem_shared/protectPublic-Csf6ObbJ.mjs";import{onQueryChange as Te}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Ae}from"./packem_shared/defineShape-BWgwFuMT.mjs";import{anyApi as Re}from"./types.mjs";import{LunoraError as Le}from"@lunora/errors";import{cronJobs as Ie}from"@lunora/scheduler";import{ValidationError as be,v as Me}from"@lunora/values";import{allowAll as Fe,deny as Oe,isDeny as He,toWhereInput as Ne}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ke}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{buildMaskRegistry as we}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{buildRlsReadRegistry as Ve,composeShapeReadWhere as je}from"./packem_shared/buildRlsReadRegistry-DrYtoBP_.mjs";import{createPolicyDsl as Ye,definePermission as Je,definePolicies as Ke,definePolicy as Qe,defineRole as Xe}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as ze,defineStorageRules as Ge}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as $e}from"./packem_shared/mask-424UQYq0.mjs";import{r as rr}from"./packem_shared/middleware-BvY85EHz.mjs";import{storageRules as tr}from"./packem_shared/storageRules-za3ylMEQ.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,Y as DEFAULT_LIMIT,J as DEFAULT_MAX_LIMIT,T as DOCUMENT_HISTORY_REDACTED_FIELDS,g as DOCUMENT_HISTORY_TABLE,_ as LunoraEnvError,Le as LunoraError,xe as PRESENCE_DEFAULT_TTL_MS,ce as PRESENCE_TABLE,e as VERSION,be as ValidationError,i as actionCacheExtension,Fe as allowAll,Re as anyApi,ke as asBucketStorage,u as beginDeferredSchedules,y as bindOrm,b as bindTableFacade,we as buildMaskRegistry,Ve as buildRlsReadRegistry,f as cacheKeyFor,K as clampLimit,$ as composePluginMiddleware,je as composeShapeReadWhere,Ye as createPolicyDsl,p as createSecrets,Ie as cronJobs,a as defineActionCache,ee as defineAggregateIndex,re as defineComponent,A as defineDocumentHistory,L as defineEnv,v as defineIdentity,Q as defineListArgs,q as defineMigration,G as defineMutator,Je as definePermission,oe as definePlugin,Ke as definePolicies,Qe as definePolicy,le as definePresence,te as defineRankIndex,Xe as defineRole,ne as defineSchema,ie as defineSchemaExtension,Ae as defineShape,ze as defineStorageRule,Ge as defineStorageRules,fe as defineTable,ae as defineVectorIndex,Oe as deny,D as documentHistoryExtension,c as flushDeferredDeletes,P as httpAction,F as httpRoute,O as httpRouter,se as indexFieldsFromSchema,d as initLunora,de as installPlugins,He as isDeny,H as isSafeHeaderValue,$e as mask,me as mergeSchemaExtension,B as onConnect,V as onDisconnect,Te as onQueryChange,j as onShardInit,Ee as presenceExtension,Se as protectPublic,C as redactSecrets,rr as rls,U as serveStorageObject,tr as storageRules,Ne as toWhereInput,Me as v,l as withDeferredDeletes,S as withDeferredSchedules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-BiYbPSuZ.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-D5TSiy5j.mjs";import{g as k,h as q,a as B}from"./plugin-yKCbHnlj.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{v as o,optionalInner as b}from"@lunora/values";const A=25,S=100,w=100,L=8,O=new Set(["id","storage","string"]),u=t=>{const n=b(t)??t;if(O.has(n.kind))return!0;const r=n._meta;if(n.kind==="literal")return typeof r?.value=="string";if(n.kind!=="union"||r?.members===void 0)return!1;const{members:s}=r;return s.some(e=>u(e))&&s.every(e=>e.kind==="null"||u(e))},_=(t,n)=>{const r=s=>o.optional(o.array(s).check(e=>e.length<=n,{message:`at most ${String(n)} values`}));return o.object({...u(t)?{contains:o.optional(o.string())}:{},eq:o.optional(t),gt:o.optional(t),gte:o.optional(t),in:r(t),isNull:o.optional(o.boolean()),lt:o.optional(t),lte:o.optional(t),ne:o.optional(t),notIn:r(t)})},B=(t,n,r)=>t===void 0||!Number.isFinite(t)?Math.min(n,r):Math.min(Math.max(1,Math.floor(t)),r),p=(t,n)=>t===void 0||!Number.isFinite(t)?n:Math.max(1,Math.floor(t)),E=new Set(["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"]),M=(t,n,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))return;const s=t,e={};let l=0;for(const a of E){if(!Object.hasOwn(s,a)||(l+=1,a==="contains"&&!r))continue;const c=s[a];if(Array.isArray(c)&&c.length>n)throw new y("BAD_REQUEST",`list filter: \`${a}\` accepts at most ${String(n)} values (got ${String(c.length)})`);e[a]=c}return l===0?void 0:e},I=(t,n,r,s)=>{const e={};for(const l of n){if(!Object.hasOwn(t,l))continue;const a=t[l],c=M(a,s,r.has(l));c!==void 0&&Object.keys(c).length===0||(e[l]=c??a)}return e},F=()=>t=>{const n=p(t.defaultLimit,A),r=p(t.maxLimit,S),s=p(t.maxInValues,w),e=p(t.maxOrderBy,L),l=new Set(Object.keys(t.filter)),a=new Set,c={};for(const[i,d]of Object.entries(t.filter))u(d)&&a.add(i),c[i]=o.optional(o.union(d,_(d,s)));const h=new Set(t.orderBy),g=t.orderBy.length===0?o.string().check(()=>!1,{message:"no sortable columns are declared for this endpoint"}):o.union(...t.orderBy.map(i=>o.literal(i)));return{args:{cursor:o.optional(o.union(o.string(),o.number(),o.null())),limit:o.optional(o.number()),orderBy:o.optional(o.array(o.object({direction:o.optional(o.union(o.literal("asc"),o.literal("desc"))),field:g}))),where:o.optional(o.object(c))},toQueryArgs:i=>{const d=i.orderBy?.filter(m=>h.has(m.field)).slice(0,e).map(m=>({[m.field]:m.direction??"asc"})),f=i.where===void 0?void 0:I(i.where,l,a,s);return{...i.cursor===void 0?{}:{cursor:typeof i.cursor=="number"?String(i.cursor):i.cursor},limit:B(i.limit,n,r),...d===void 0||d.length===0?{}:{orderBy:d},...f===void 0?{}:{where:f}}}}};export{A as DEFAULT_LIMIT,w as DEFAULT_MAX_IN_VALUES,S as DEFAULT_MAX_LIMIT,L as DEFAULT_MAX_ORDER_BY,B as clampLimit,F as defineListArgs,p as normalizeBound,I as sanitizeWhere};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-BiYbPSuZ.mjs";import{initLunora as x}from"./initLunora-D5TSiy5j.mjs";import{g as v,h as R,a as U}from"./plugin-yKCbHnlj.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
|
package/dist/packem_shared/{buildRlsReadRegistry-BMJeR-II.mjs → buildRlsReadRegistry-DrYtoBP_.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as d,d as f,e as u,f as h}from"./middleware-
|
|
1
|
+
import{i as d,d as f,e as u,f as h}from"./middleware-BvY85EHz.mjs";import{r as p}from"./policy-tag-V0lqFzgS.mjs";import{deny as g}from"./allowAll-DkRAgItV.mjs";const c=g(),b=s=>{const e=s?.rls?.tags;return e||p(s)},y=(s,e)=>{const o=d(e.roles),n=new Map,r=new Map;for(const t of e.policies){if(t.on!=="read")continue;const a=n.get(t.table)??new Set;if(a.has(t.when))continue;a.add(t.when),n.set(t.table,a);const i=r.get(t.table)??[];i.push(t),r.set(t.table,i)}for(const[t,a]of r){const i=s.get(t)??[];i.push({policies:a,rolePermissions:o}),s.set(t,i)}},l=s=>{const e=s.OR;return Array.isArray(e)&&e.length===0&&Object.keys(s).length===1},R=(s,e)=>!s||Object.keys(s).length===0?e:l(s)||Object.keys(e).length===0?s:{AND:[s,e]},m=(s,e)=>{const o=f(e.identity);return u(s.policies,{auth:{can:h(o,s.rolePermissions),identity:e.identity,roles:o,userId:e.userId},ctx:e.ctx})},T=(s,e)=>{const o=s.byTable.get(e.table);if(!o||o.length===0)return e.rlsRequired&&!e.tablePublic?c:void 0;const n=[];for(const r of o){const t=m(r,e);if(t===void 0)return;l(t)||n.push(t)}return n.length===0?c:n.length===1?n[0]:{OR:n}},W=s=>{const e=new Map,o=new Set;for(const n of s)for(const r of b(n))o.has(r)||(o.add(r),y(e,r));return{byTable:e}},A=(s,e)=>R(T(s,e),e.shapeWhere);export{W as buildRlsReadRegistry,A as composeShapeReadWhere};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{LunoraError as E,toErrorBody as O,isLunoraError as N}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as _}from"@lunora/values";import{Hono as q}from"hono";import{a as k}from"./apply-output-C5wZ5EAL.mjs";const V=e=>async r=>e(r.get("lunora"),r.req.raw),$=()=>{const e=new q;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},v=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},x=(e,r,o)=>{const n=v(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const d=n._meta?.inner;return a.map(i=>g(d?.kind??"string",i))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},S=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=x(t,r,n))}return R(e,o,"searchParams")},T=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const d=o[t];n[t]=d===void 0?void 0:g(v(a).kind,d)}return R(e,n,"params")},C=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return R(e,o,"body")},j=e=>{if(e instanceof _)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(N(e)){const{body:r,redacted:o,status:n}=O(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message},{status:n})}throw e},A=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},H=(e,r)=>async o=>{const n=A(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},d=Object.keys(e.params).length>0?T(e.params,o):{},i=Object.keys(e.body).length>0?await C(e.body,o):{},h=await r({body:i,ctx:t,params:d,searchParams:a}),s=e.output?k(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const f=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:f?c:void 0,status:204}):Response.json(s,{headers:f?c:void 0})}catch(t){return j(t)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,r)=>{const o=JSON.stringify(e);return`${r?`event: ${r}
|
|
2
|
+
`:""}data: ${o}
|
|
3
|
+
|
|
4
|
+
`},L=(e,r)=>(async o=>{const n=A(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},a=Object.keys(e.params).length>0?T(e.params,o):{}}catch(p){return j(p)}const d=o.get("lunora"),i=o.req.raw,h=new TextEncoder,s=new AbortController;if(i.signal.aborted)return s.abort(),new Response("",{headers:w});const c=()=>{s.abort()};i.signal.addEventListener("abort",c,{once:!0});const f=new ReadableStream({cancel(){i.signal.removeEventListener("abort",c),s.abort()},async start(p){try{const y=r({ctx:d,params:a,request:i,searchParams:t,signal:s.signal});for await(const m of y){if(s.signal.aborted)break;p.enqueue(h.encode(b(e.output?k(e.output,m):m)))}s.signal.aborted||p.enqueue(h.encode(b({},"complete")))}catch(y){const{body:m,redacted:P}=O(y,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});P&&console.error("[lunora] unhandled stream handler error:",y),s.signal.aborted||p.enqueue(h.encode(b({code:m.code,message:m.message},"error")))}finally{i.signal.removeEventListener("abort",c);try{p.close()}catch{}}}});return new Response(f,{headers:w})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>H(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>L(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),U={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},J=e=>!(e.includes("\r")||e.includes(`
|
|
5
|
+
`)||e.includes("\0"));export{V as httpAction,U as httpRoute,$ as httpRouter,J as isSafeHeaderValue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-BvY85EHz.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-ChQydkdL.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(e,i,a)=>{try{return e==="redact"?null:e==="hash"?i==null?i:typeof i=="bigint"?U(i.toString()):U(typeof i=="string"?i:JSON.stringify(i)):e(i,a)}catch{return null}},u=(e,i,a)=>{const d={...e};for(const[y,g]of Object.entries(i))y in d&&(d[y]=V(g,e[y],{...a,column:y,row:e}));return d},j=(e,i,a)=>({...e,page:e.page.map(d=>u(d,i,a))}),D=(e,i,a,d)=>{if(typeof e!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>w=>(typeof w=="string"&&y.add(w),g())});e(g());for(const w of y)if(w in i)throw new S("MASK_UNSUPPORTED",`${d}() filtering "${a}" by masked column "${w}" is not supported`)},X=(e,i,a,d)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>u(o,t,a)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},k=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=d?.[r]?.[o]?.[n];if(!c)return;const f=c.find(E=>E in s);if(f!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${f}" — use an index whose declared fields are all unmasked, or unmask the column`)},p=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield u(o,n,a)},collect:async()=>(await r.collect()).map(s=>u(s,n,a)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=u(s.document,n,a);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>p(r.filter(s=>o(u(s,n,a))),n,t),first:async()=>{const o=await r.first();return o?u(o,n,a):null},order:o=>p(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,a),take:async o=>(await r.take(o)).map(c=>u(c,n,a)),unique:async()=>{const o=await r.unique();return o?u(o,n,a):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),D(s,n,t,"withIndex"),p(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),p(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),p(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const f=await e.lookupById(r,n);return f?{row:f.row,tableName:i.has(f.tableName)?f.tableName:void 0}:{row:null,tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,c=await Promise.all(s.map(async f=>(await e.findFirst(f,{limit:1,where:{_id:r}}))?._id===r?f:void 0));return{row:t,tableName:c.find(f=>f!==void 0)}},P=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(c=>typeof c=="string"&&c in o);if(s!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},A=new Set;for(const r of i.values())for(const n of Object.keys(r))A.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,c]of Object.entries(r))K(s,c,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const c of Array.isArray(n)?n:[])R(c,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new S("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const c of Object.values(n))R(c,A,`${o}.${r}`,s)}},B=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{A.size===0||n===void 0||R(n,B(r),r,t)},F=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const c of Object.keys(s))if(t.has(c))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${c}" is not supported`)}}},$=(r,n,t)=>{if(!(A.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const c=s,f=`${r}.${o}`;R(c.where,A,f,t),F(f,c.orderBy,A,t),$(f,c.with,t)}},W=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),F(r,n?.orderBy,B(r),t),$(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=v(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},I={...e,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return h(r,o,"count"),t&&h(r,t.baseWhere,"count"),e.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await e.findFirst(r,l(n)),o=i.get(r);return t&&o?u(t,o,a):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,l(n)),o=i.get(r);return o?u(t,o,a):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,l(n)),o=i.get(r);return o?j(t,o,a):t},async get(r,n){const{row:t,tableName:o}=await O(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:u(t,s,a)},async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?u(t.row,o,a):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?p(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),k(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,a):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(f=>({...f,doc:u(f.doc,c,a)}))}:s})},q=I;if(A.size>0)for(const[r,n]of Object.entries(e))G(n)&&(q[r]=H(I,r));return I},b=(e,i={})=>{const a=new Map(Object.entries(e)),d=L(i.roles),y=async({ctx:w,next:l})=>{const k={auth:await z(w.auth??{},d),ctx:w};if(i.bypass?.(k)===!0)return l();const p=X(w.db,a,k,i.indexFields),O={db:p},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(p)),l({ctx:O})},g=new Map;for(const[w,l]of a)g.set(w,new Set(Object.keys(l)));return Q(y,{columns:g})};export{b as mask};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as W}from"@lunora/errors";import{i as P}from"./wire-codec-BOMWQpoF.mjs";import{bindTableFacade as U,bindOrm as T}from"./bindOrm-ChQydkdL.mjs";import{t as j}from"./policy-tag-V0lqFzgS.mjs";import{deny as $}from"./allowAll-DkRAgItV.mjs";const N=["every","is","isNot","none","some"],q=new Set(N),Y=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const t=Object.keys(r);return t.length>0&&t.every(i=>q.has(i))},M=(r,t,i)=>t?{[r]:i(t)}:{},D=500,A=(r,t,i)=>{const a=t??D;if(r>a)throw new W("BATCH_LIMIT_EXCEEDED",`${i}: batch of ${String(r)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},K=$(),z=Symbol.for("lunora.ctxdb.rls-unwrap"),H=r=>{const t=new Map;for(const i of r){const a=t.get(i.table)??[];a.push(i),t.set(i.table,a)}return t},G=(r,t)=>{const i=[];let a=!1;for(const l of r){if(l.on!=="read")continue;const f=l.when(t);if(f!==void 0){if(f===!0){a=!0;break}f!==!1&&i.push(f)}}if(!a)return i.length===0?K:i.length===1?i[0]:{OR:i}},Q=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],p=r=>{const t=typeof r;return t==="number"||t==="string"||t==="bigint"},X=(r,t)=>!("lt"in t&&(!p(r)||!p(t.lt)||r>=t.lt)||"lte"in t&&(!p(r)||!p(t.lte)||r>t.lte)||"gt"in t&&(!p(r)||!p(t.gt)||r<=t.gt)||"gte"in t&&(!p(r)||!p(t.gte)||r<t.gte)),J=(r,t)=>{if("in"in t){const i=t.in;if(!Array.isArray(i)||!i.includes(r))return!1}if("notIn"in t){const i=t.notIn;if(Array.isArray(i)&&i.includes(r))return!1}if("contains"in t){const i=t.contains;if(typeof r!="string"||typeof i!="string"||!r.includes(i))return!1}return!("isNull"in t&&t.isNull===!0!==(r==null))},Z=(r,t)=>"eq"in t&&r!==t.eq||"ne"in t&&r===t.ne?!1:J(r,t)&&X(r,t),x=(r,t,i,a)=>t==="AND"?Array.isArray(i)&&i.every(l=>a(r,l)):t==="OR"?Array.isArray(i)&&i.some(l=>a(r,l)):!a(r,i??{}),m=r=>r==="AND"||r==="OR"||r==="NOT",V=r=>P(r)&&Object.keys(r).every(t=>Q.includes(t)),v=r=>Object.keys(r).some(t=>{const i=r[t];return m(t)?t==="NOT"?v(i??{}):Array.isArray(i)&&i.some(a=>v(a??{})):Y(i)}),B=(r,t)=>{for(const i of Object.keys(t)){const a=t[i];if(m(i)){if(!x(r,i,a,B))return!1;continue}const l=r[i];if(V(a)){if(!Z(l,a))return!1;continue}if(l!==a)return!1}return!0},ee=(r,t,i)=>{const a=r.when({...t,row:i});if(a===void 0||a===!0)return!0;if(a===!1)return!1;if(v(a))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return B(i,a)},re=(r,t,i)=>{const a=r.when(t);if(a===void 0||a===!0)return i===void 0||ee(r,t,i);if(a===!1)return!1;if(v(a))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!B(t.row,a)?!1:i===void 0||B(i,a)},_=(r,t,i,a)=>{let l=!1;for(const f of r)if(f.on===t&&(l=!0,!re(f,i,a)))return!1;return l},te=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),ne=(r,t)=>t===void 0?!0:r==="restrictsCounts"?typeof t=="boolean":r==="relationBaseWhere"?typeof t=="function":P(t),se=r=>{const t=Object.keys(r);return t.length===0?!1:t.every(i=>te.has(i)&&ne(i,r[i]))},ie=r=>r===void 0?{}:P(r)&&se(r)?r:{where:r},w=(r,t)=>!t||Object.keys(t).length===0?r:!r||Object.keys(r).length===0?t:{AND:[t,r]},oe=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return!1;const t=r;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},ae=(r,t,i,a)=>{const l=new Map,f=e=>{const n=l.get(e);if(n)return n;const s=i.get(e);if(!s||s.length===0||!s.some(u=>u.on==="read")){const u={baseWhere:void 0,restricts:!1};return l.set(e,u),u}const c={baseWhere:G(s,a),restricts:!0};return l.set(e,c),c},d=e=>f(e).restricts?t:r,y=e=>f(e).baseWhere,O=async(e,n)=>{if(t.lookupById){const h=await t.lookupById(e,n);return h?{row:h.row,tableName:i.has(h.tableName)?h.tableName:void 0}:{row:null,tableName:void 0}}const s=await t.get(e,n);if(!s)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],c=n===void 0?[...i.keys()]:o,u=await Promise.all(c.map(async h=>(await t.findFirst(h,{limit:1,where:{_id:e}}))?._id===e?h:void 0));return{row:s,tableName:u.find(h=>h!==void 0)}},I=async(e,n)=>{const s=await O(e,n);return s.row&&s.tableName!==void 0?{row:s.row,tableName:s.tableName}:void 0},g=async(e,n,s,o,c)=>{const u=await I(e,c);if(!u)return s(r);const h=i.get(u.tableName);if(h){const R=o?o(u.row):void 0;if(!_(h,n,{...a,row:u.row},R))throw new W("FORBIDDEN",`${n} denied by policy`)}return s(t)},b=(e,n)=>{const{baseWhere:s,restricts:o}=f(e);if(o)throw new W("COUNT_RLS_UNSUPPORTED",`${n}() is not supported on "${e}" inside an RLS-restricted context`);return s},E=r.rankBefore,F=r.rankPageRows,k={...r,async count(e,n){const{baseWhere:s,restricts:o}=f(e),c=ie(n);return d(e).count(e,{...c,baseWhere:w(c.baseWhere,s),relationBaseWhere:y,restrictsCounts:(c.restrictsCounts??!1)||o})},delete:(e,n,s)=>g(e,"delete",o=>o.delete(e,n,s),void 0,n),async deleteAll(e,n){const s=Math.max(1,n?.chunkSize??D),{baseWhere:o}=f(e);let c=0;for(;;){const h=(await d(e).findMany(e,{baseWhere:o,limit:s,relationBaseWhere:y})).page.map(R=>String(R._id));if(h.length===0)break;for(const R of h)await g(R,"delete",S=>S.delete(R,void 0,n?.hard===void 0?void 0:{hard:n.hard})),c+=1;if(h.length<s)break}return{deleted:c}},async deleteMany(e,n,s){A(e.length,n?.limit,"deleteMany");for(const o of e)await g(o,"delete",c=>c.delete(o,s),void 0,s);return{deleted:e.length}},async deleteWhere(e,n,s){const{baseWhere:o}=f(e),u=(await d(e).findMany(e,{baseWhere:w(n,o),relationBaseWhere:y})).page.map(h=>String(h._id));return A(u.length,s?.limit,"deleteWhere"),k.deleteMany(u,s)},async findFirst(e,n){const{baseWhere:s}=f(e);return d(e).findFirst(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async findFirstOrThrow(e,n){const{baseWhere:s}=f(e);return d(e).findFirstOrThrow(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async findMany(e,n){const{baseWhere:s}=f(e);return d(e).findMany(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async get(e,n){const s=await O(e,n);if(!s.row)return null;if(s.tableName===void 0)return r.get(e,n);const{baseWhere:o,restricts:c}=f(s.tableName);if(!c)return r.get(e,n);if(!o)return s.row;const u=await t.findFirst(s.tableName,{baseWhere:o,limit:1,where:{_id:e}});return u?._id===e?u:null},async lookupById(e,n){const s=await O(e,n);if(!s.row)return null;if(s.tableName===void 0||!f(s.tableName).restricts)return await r.lookupById?.(e,n)??null;const{baseWhere:o}=f(s.tableName);if(!o)return{row:s.row,tableName:s.tableName};const c=await t.findFirst(s.tableName,{baseWhere:o,limit:1,where:{_id:e}});return c?._id===e?{row:c,tableName:s.tableName}:null},async insert(e,n){const s=i.get(e);if(s){if(!_(s,"insert",{...a,row:n}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insert(e,n)}return r.insert(e,n)},async insertMany(e,n,s){A(n.length,s?.limit,"insertMany");const o=i.get(e);if(o){for(const c of n)if(!_(o,"insert",{...a,row:c}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertMany(e,n,s)}return r.insertMany(e,n,s)},async insertManyUnsafe(e,n,s){A(n.length,s?.limit,"insertManyUnsafe");const o=i.get(e);if(o){for(const c of n)if(!_(o,"insert",{...a,row:c}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertManyUnsafe(e,n,s)}return r.insertManyUnsafe(e,n,s)},patch:(e,n,s)=>g(e,"update",o=>o.patch(e,n,s),o=>({...o,...n}),s),async patchMany(e,n,s){A(e.length,n?.limit,"patchMany");for(const o of e)await g(o.id,"update",c=>c.patch(o.id,o.patch,s),c=>({...c,...o.patch}),s);return{patched:e.length}},async patchWhere(e,n,s){const{baseWhere:o}=f(e),u=(await d(e).findMany(e,{baseWhere:w(n.where,o),relationBaseWhere:y})).page.map(h=>({id:String(h._id),patch:n.patch}));return A(u.length,s?.limit,"patchWhere"),k.patchMany(u,s)},query(e){const{baseWhere:n}=f(e),s=d(e).query(e);return n?s.filter(o=>B(o,n)):s},restore:(e,n)=>g(e,"update",async s=>{const o=s.restore??t.restore;if(!o)throw new W("BAD_REQUEST","restore is not supported by this writer");await o(e,n)},void 0,n),replace:(e,n,s)=>g(e,"update",o=>o.replace(e,n,s),o=>({...n,_creationTime:n._creationTime??o._creationTime,_id:o._id}),s),aggregate(e,n){const{baseWhere:s}=f(e);return d(e).aggregate(e,{...n,baseWhere:w(n.baseWhere,s),relationBaseWhere:y})},groupBy(e,n){const{baseWhere:s}=f(e);return d(e).groupBy(e,{...n,baseWhere:w(n.baseWhere,s),relationBaseWhere:y})},rank(e,n,s){const o=b(e,"rank");return d(e).rank(e,n,{...s,baseWhere:w(s.baseWhere,o)})},rankPage(e,n,s){const o=b(e,"rankPage");return d(e).rankPage(e,n,{...s,baseWhere:w(s?.baseWhere,o)})},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...M("rankBefore",E,e=>(n,s,o)=>(b(n,"rankBefore"),(d(n).rankBefore??e)(n,s,o))),...M("rankPageRows",F,e=>(n,s,o)=>{const c=b(n,"rankPageRows");return(d(n).rankPageRows??e)(n,s,{...o,baseWhere:w(o?.baseWhere,c)})})},L=k;if(i.size>0)for(const[e,n]of Object.entries(r))oe(n)&&(L[e]=U(k,e));return k},C=r=>typeof r=="string"?r:r.name,ce=r=>{const t=new Map;for(const i of r??[])t.set(i.name,new Set((i.permissions??[]).map(a=>C(a))));return t},fe=(r,t)=>{const i=new Set;for(const a of r)for(const l of t.get(a)??[])i.add(l);return a=>i.has(C(a))},le=["roles","role"],ue=r=>{for(const t of le){const i=r?.[t];if(typeof i=="string"){const a=i.split(",").map(l=>l.trim()).filter(l=>l.length>0);if(a.length>0)return a}if(Array.isArray(i)){const a=i.filter(l=>typeof l=="string"&&l.length>0);if(a.length>0)return a}}return[]},he=async(r,t)=>{const i=await r.getIdentity?.()??null,a=[...new Set([...ue(i),...r.roles??[]])];return{can:fe(a,t),identity:i,roles:a,userId:r.userId??null}},pe=(r,t={})=>{const i=H(r),a=ce(t.roles);return j(async({ctx:f,next:d})=>{const y={auth:await he(f.auth??{},a),ctx:f},O=f.db,I=O[z]??O,g=ae(O,I,i,y),b={db:g},{orm:E}=f;return E!==null&&typeof E=="object"&&(b.orm=T(g)),d({ctx:b})},[{policies:r,roles:t.roles??[]}])};export{he as a,oe as b,Y as c,ue as d,G as e,fe as f,_ as g,ce as i,B as m,M as o,C as p,pe as r};
|
|
1
|
+
import{LunoraError as W}from"@lunora/errors";import{i as P}from"./wire-codec-BiYbPSuZ.mjs";import{bindTableFacade as U,bindOrm as T}from"./bindOrm-ChQydkdL.mjs";import{t as j}from"./policy-tag-V0lqFzgS.mjs";import{deny as $}from"./allowAll-DkRAgItV.mjs";const N=["every","is","isNot","none","some"],q=new Set(N),Y=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const t=Object.keys(r);return t.length>0&&t.every(i=>q.has(i))},M=(r,t,i)=>t?{[r]:i(t)}:{},D=500,A=(r,t,i)=>{const a=t??D;if(r>a)throw new W("BATCH_LIMIT_EXCEEDED",`${i}: batch of ${String(r)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},K=$(),z=Symbol.for("lunora.ctxdb.rls-unwrap"),H=r=>{const t=new Map;for(const i of r){const a=t.get(i.table)??[];a.push(i),t.set(i.table,a)}return t},G=(r,t)=>{const i=[];let a=!1;for(const l of r){if(l.on!=="read")continue;const f=l.when(t);if(f!==void 0){if(f===!0){a=!0;break}f!==!1&&i.push(f)}}if(!a)return i.length===0?K:i.length===1?i[0]:{OR:i}},Q=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],p=r=>{const t=typeof r;return t==="number"||t==="string"||t==="bigint"},X=(r,t)=>!("lt"in t&&(!p(r)||!p(t.lt)||r>=t.lt)||"lte"in t&&(!p(r)||!p(t.lte)||r>t.lte)||"gt"in t&&(!p(r)||!p(t.gt)||r<=t.gt)||"gte"in t&&(!p(r)||!p(t.gte)||r<t.gte)),J=(r,t)=>{if("in"in t){const i=t.in;if(!Array.isArray(i)||!i.includes(r))return!1}if("notIn"in t){const i=t.notIn;if(Array.isArray(i)&&i.includes(r))return!1}if("contains"in t){const i=t.contains;if(typeof r!="string"||typeof i!="string"||!r.includes(i))return!1}return!("isNull"in t&&t.isNull===!0!==(r==null))},Z=(r,t)=>"eq"in t&&r!==t.eq||"ne"in t&&r===t.ne?!1:J(r,t)&&X(r,t),x=(r,t,i,a)=>t==="AND"?Array.isArray(i)&&i.every(l=>a(r,l)):t==="OR"?Array.isArray(i)&&i.some(l=>a(r,l)):!a(r,i??{}),m=r=>r==="AND"||r==="OR"||r==="NOT",V=r=>P(r)&&Object.keys(r).every(t=>Q.includes(t)),v=r=>Object.keys(r).some(t=>{const i=r[t];return m(t)?t==="NOT"?v(i??{}):Array.isArray(i)&&i.some(a=>v(a??{})):Y(i)}),B=(r,t)=>{for(const i of Object.keys(t)){const a=t[i];if(m(i)){if(!x(r,i,a,B))return!1;continue}const l=r[i];if(V(a)){if(!Z(l,a))return!1;continue}if(l!==a)return!1}return!0},ee=(r,t,i)=>{const a=r.when({...t,row:i});if(a===void 0||a===!0)return!0;if(a===!1)return!1;if(v(a))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return B(i,a)},re=(r,t,i)=>{const a=r.when(t);if(a===void 0||a===!0)return i===void 0||ee(r,t,i);if(a===!1)return!1;if(v(a))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!B(t.row,a)?!1:i===void 0||B(i,a)},_=(r,t,i,a)=>{let l=!1;for(const f of r)if(f.on===t&&(l=!0,!re(f,i,a)))return!1;return l},te=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),ne=(r,t)=>t===void 0?!0:r==="restrictsCounts"?typeof t=="boolean":r==="relationBaseWhere"?typeof t=="function":P(t),se=r=>{const t=Object.keys(r);return t.length===0?!1:t.every(i=>te.has(i)&&ne(i,r[i]))},ie=r=>r===void 0?{}:P(r)&&se(r)?r:{where:r},w=(r,t)=>!t||Object.keys(t).length===0?r:!r||Object.keys(r).length===0?t:{AND:[t,r]},oe=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return!1;const t=r;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},ae=(r,t,i,a)=>{const l=new Map,f=e=>{const n=l.get(e);if(n)return n;const s=i.get(e);if(!s||s.length===0||!s.some(u=>u.on==="read")){const u={baseWhere:void 0,restricts:!1};return l.set(e,u),u}const c={baseWhere:G(s,a),restricts:!0};return l.set(e,c),c},d=e=>f(e).restricts?t:r,y=e=>f(e).baseWhere,O=async(e,n)=>{if(t.lookupById){const h=await t.lookupById(e,n);return h?{row:h.row,tableName:i.has(h.tableName)?h.tableName:void 0}:{row:null,tableName:void 0}}const s=await t.get(e,n);if(!s)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],c=n===void 0?[...i.keys()]:o,u=await Promise.all(c.map(async h=>(await t.findFirst(h,{limit:1,where:{_id:e}}))?._id===e?h:void 0));return{row:s,tableName:u.find(h=>h!==void 0)}},I=async(e,n)=>{const s=await O(e,n);return s.row&&s.tableName!==void 0?{row:s.row,tableName:s.tableName}:void 0},g=async(e,n,s,o,c)=>{const u=await I(e,c);if(!u)return s(r);const h=i.get(u.tableName);if(h){const R=o?o(u.row):void 0;if(!_(h,n,{...a,row:u.row},R))throw new W("FORBIDDEN",`${n} denied by policy`)}return s(t)},b=(e,n)=>{const{baseWhere:s,restricts:o}=f(e);if(o)throw new W("COUNT_RLS_UNSUPPORTED",`${n}() is not supported on "${e}" inside an RLS-restricted context`);return s},E=r.rankBefore,F=r.rankPageRows,k={...r,async count(e,n){const{baseWhere:s,restricts:o}=f(e),c=ie(n);return d(e).count(e,{...c,baseWhere:w(c.baseWhere,s),relationBaseWhere:y,restrictsCounts:(c.restrictsCounts??!1)||o})},delete:(e,n,s)=>g(e,"delete",o=>o.delete(e,n,s),void 0,n),async deleteAll(e,n){const s=Math.max(1,n?.chunkSize??D),{baseWhere:o}=f(e);let c=0;for(;;){const h=(await d(e).findMany(e,{baseWhere:o,limit:s,relationBaseWhere:y})).page.map(R=>String(R._id));if(h.length===0)break;for(const R of h)await g(R,"delete",S=>S.delete(R,void 0,n?.hard===void 0?void 0:{hard:n.hard})),c+=1;if(h.length<s)break}return{deleted:c}},async deleteMany(e,n,s){A(e.length,n?.limit,"deleteMany");for(const o of e)await g(o,"delete",c=>c.delete(o,s),void 0,s);return{deleted:e.length}},async deleteWhere(e,n,s){const{baseWhere:o}=f(e),u=(await d(e).findMany(e,{baseWhere:w(n,o),relationBaseWhere:y})).page.map(h=>String(h._id));return A(u.length,s?.limit,"deleteWhere"),k.deleteMany(u,s)},async findFirst(e,n){const{baseWhere:s}=f(e);return d(e).findFirst(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async findFirstOrThrow(e,n){const{baseWhere:s}=f(e);return d(e).findFirstOrThrow(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async findMany(e,n){const{baseWhere:s}=f(e);return d(e).findMany(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async get(e,n){const s=await O(e,n);if(!s.row)return null;if(s.tableName===void 0)return r.get(e,n);const{baseWhere:o,restricts:c}=f(s.tableName);if(!c)return r.get(e,n);if(!o)return s.row;const u=await t.findFirst(s.tableName,{baseWhere:o,limit:1,where:{_id:e}});return u?._id===e?u:null},async lookupById(e,n){const s=await O(e,n);if(!s.row)return null;if(s.tableName===void 0||!f(s.tableName).restricts)return await r.lookupById?.(e,n)??null;const{baseWhere:o}=f(s.tableName);if(!o)return{row:s.row,tableName:s.tableName};const c=await t.findFirst(s.tableName,{baseWhere:o,limit:1,where:{_id:e}});return c?._id===e?{row:c,tableName:s.tableName}:null},async insert(e,n){const s=i.get(e);if(s){if(!_(s,"insert",{...a,row:n}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insert(e,n)}return r.insert(e,n)},async insertMany(e,n,s){A(n.length,s?.limit,"insertMany");const o=i.get(e);if(o){for(const c of n)if(!_(o,"insert",{...a,row:c}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertMany(e,n,s)}return r.insertMany(e,n,s)},async insertManyUnsafe(e,n,s){A(n.length,s?.limit,"insertManyUnsafe");const o=i.get(e);if(o){for(const c of n)if(!_(o,"insert",{...a,row:c}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertManyUnsafe(e,n,s)}return r.insertManyUnsafe(e,n,s)},patch:(e,n,s)=>g(e,"update",o=>o.patch(e,n,s),o=>({...o,...n}),s),async patchMany(e,n,s){A(e.length,n?.limit,"patchMany");for(const o of e)await g(o.id,"update",c=>c.patch(o.id,o.patch,s),c=>({...c,...o.patch}),s);return{patched:e.length}},async patchWhere(e,n,s){const{baseWhere:o}=f(e),u=(await d(e).findMany(e,{baseWhere:w(n.where,o),relationBaseWhere:y})).page.map(h=>({id:String(h._id),patch:n.patch}));return A(u.length,s?.limit,"patchWhere"),k.patchMany(u,s)},query(e){const{baseWhere:n}=f(e),s=d(e).query(e);return n?s.filter(o=>B(o,n)):s},restore:(e,n)=>g(e,"update",async s=>{const o=s.restore??t.restore;if(!o)throw new W("BAD_REQUEST","restore is not supported by this writer");await o(e,n)},void 0,n),replace:(e,n,s)=>g(e,"update",o=>o.replace(e,n,s),o=>({...n,_creationTime:n._creationTime??o._creationTime,_id:o._id}),s),aggregate(e,n){const{baseWhere:s}=f(e);return d(e).aggregate(e,{...n,baseWhere:w(n.baseWhere,s),relationBaseWhere:y})},groupBy(e,n){const{baseWhere:s}=f(e);return d(e).groupBy(e,{...n,baseWhere:w(n.baseWhere,s),relationBaseWhere:y})},rank(e,n,s){const o=b(e,"rank");return d(e).rank(e,n,{...s,baseWhere:w(s.baseWhere,o)})},rankPage(e,n,s){const o=b(e,"rankPage");return d(e).rankPage(e,n,{...s,baseWhere:w(s?.baseWhere,o)})},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...M("rankBefore",E,e=>(n,s,o)=>(b(n,"rankBefore"),(d(n).rankBefore??e)(n,s,o))),...M("rankPageRows",F,e=>(n,s,o)=>{const c=b(n,"rankPageRows");return(d(n).rankPageRows??e)(n,s,{...o,baseWhere:w(o?.baseWhere,c)})})},L=k;if(i.size>0)for(const[e,n]of Object.entries(r))oe(n)&&(L[e]=U(k,e));return k},C=r=>typeof r=="string"?r:r.name,ce=r=>{const t=new Map;for(const i of r??[])t.set(i.name,new Set((i.permissions??[]).map(a=>C(a))));return t},fe=(r,t)=>{const i=new Set;for(const a of r)for(const l of t.get(a)??[])i.add(l);return a=>i.has(C(a))},le=["roles","role"],ue=r=>{for(const t of le){const i=r?.[t];if(typeof i=="string"){const a=i.split(",").map(l=>l.trim()).filter(l=>l.length>0);if(a.length>0)return a}if(Array.isArray(i)){const a=i.filter(l=>typeof l=="string"&&l.length>0);if(a.length>0)return a}}return[]},he=async(r,t)=>{const i=await r.getIdentity?.()??null,a=[...new Set([...ue(i),...r.roles??[]])];return{can:fe(a,t),identity:i,roles:a,userId:r.userId??null}},pe=(r,t={})=>{const i=H(r),a=ce(t.roles);return j(async({ctx:f,next:d})=>{const y={auth:await he(f.auth??{},a),ctx:f},O=f.db,I=O[z]??O,g=ae(O,I,i,y),b={db:g},{orm:E}=f;return E!==null&&typeof E=="object"&&(b.orm=T(g)),d({ctx:b})},[{policies:r,roles:t.roles??[]}])};export{he as a,oe as b,Y as c,ue as d,G as e,fe as f,_ as g,ce as i,B as m,M as o,C as p,pe as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as t,g as m,i as p,b as l,m as d,p as n,d as c,f as h,a as u,r as v}from"./middleware-
|
|
1
|
+
import{e as t,g as m,i as p,b as l,m as d,p as n,d as c,f as h,a as u,r as v}from"./middleware-BvY85EHz.mjs";import"./wire-codec-BiYbPSuZ.mjs";import"./bindOrm-ChQydkdL.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,m as evaluateWrite,p as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,n as permissionName,c as readIdentityRoles,h as resolveCan,u as resolvePolicyAuth,v as rls};
|
package/dist/packem_shared/{serveStorageObject-Cof46mpm.mjs → serveStorageObject-te5TWJIE.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isSafeHeaderValue as l}from"./httpAction-
|
|
1
|
+
import{isSafeHeaderValue as l}from"./httpAction-YRpmc049.mjs";const h=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,f=(t,e)=>{if(t===null)return{kind:"full"};const n=h.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let o,r;if(s===""){const i=Number(a);if(i===0)return{kind:"unsatisfiable"};o=Math.max(0,e-i),r=e-1}else o=Number(s),r=a===""?e-1:Math.min(Number(a),e-1);return o>r||o>=e?{kind:"unsatisfiable"}:{end:r,kind:"partial",start:o}},m=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),p=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&l(n)?n:"application/octet-stream",a={"accept-ranges":"bytes","cache-control":e,"content-type":s,etag:g(t.etag),"x-content-type-options":"nosniff"};return m.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},w=t=>f(t,0).kind==="full",u=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...p(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},b=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},y=async(t,e,n,s,a="no-store")=>{if(!await b(s,e,n))return new Response("Forbidden",{status:403});const o=n.headers.get("range");if(w(o))return u(t,e,a);const r=await t.storage.head(e);if(!r)return new Response("Not Found",{status:404});const i=f(o,r.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(r.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(r.etag)},status:416});if(i.kind==="full")return u(t,e,a);const c=i.end-i.start+1,d=await t.storage.download(e,{range:{length:c,offset:i.start}});return d?new Response(d.body,{headers:{...p(r,a),"content-length":String(c),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(r.size)}`},status:206}):new Response("Not Found",{status:404})};export{y as serveStorageObject};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-BvY85EHz.mjs";const N=(e,t,o)=>{const a=s=>o.isAllowed("list",s,t)&&o.isAllowed("read",s,t),{get:r,query:b}=e,l={...e},w=s=>s.filter(n=>typeof n.key=="string"&&a(n.key));return typeof r=="function"&&(l.get=async(s,n)=>(s==="_storage"&&o.assertAllowed("read",n,t),r(s,n))),typeof b=="function"&&(l.query=s=>{const n=b(s),{collect:p}=n;return s!=="_storage"||typeof p!="function"?n:{...n,collect:async()=>w(await p())}}),l},S=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},D=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",D],["getUrl","read"],["head","read"],["store","write"]],M=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},P=(e,t)=>{const o=e.bucketName??"default",{bucket:a}=e;for(const r of new Set(t))if(!(r===o||typeof a=="function"&&M(a,r)))throw new A("INTERNAL",`storageRules: rule for bucket "${r}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${r}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},C=(e,t={})=>{const o=U(t.roles);return async({ctx:a,next:r})=>{const b=await $(a.auth??{},o),l=(c,u,d)=>{const h=e.filter(i=>i.on===c&&i.bucket===d);if(h.length===0)return!0;const f={auth:b,ctx:a,key:u};return h.some(i=>S(i.prefix,u)&&i.when(f)===!0)},w=(c,u,d)=>{if(!l(c,u,d))throw new A("FORBIDDEN",`storage ${c} on "${u}" in bucket "${d}" denied by access rule`)},s=c=>{const u=c.bucketName??"default",d={bucketName:u};for(const[f,i]of E){const k=c[f];typeof k=="function"&&(d[f]=(...y)=>{const R=typeof y[0]=="string"?y[0]:"",v=typeof i=="function"?i(y):i;return w(v,R,u),k(...y)})}const{bucket:h}=c;return typeof h=="function"&&(d.bucket=f=>s(h(f))),d},n=a.storage;if(n===void 0)return r();P(n,e.map(c=>c.bucket));const p={storage:s(n)},g=a.db,m=g?.system;return g!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...g,system:N(m,n.bucketName??"default",{assertAllowed:w,isAllowed:l})}),r({ctx:p})}};export{C as storageRules};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const w=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},p=e=>{const t=atob(e),a=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)a[o]=t.codePointAt(o)??0;return a},i="$lunora.wire$";const m="__proto__",g={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},A={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},b=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const a=typeof e;if(a==="bigint")return[i,"bigint",e.toString()];if(a==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(a!=="object")return e;if(e instanceof Date)return[i,"date",b(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const c of Object.keys(r)){if(r[c]===void 0)continue;const u=b(r[c],t+1);c===m?Object.defineProperty(n,c,{configurable:!0,enumerable:!0,value:u,writable:!0}):n[c]=u}const s=[i,"error",r.name,r.message,n];return r.cause!==void 0&&s.push(b(r.cause,t+1)),s}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[b(r,t+1),b(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>b(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",w(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",w(s)]:[i,"bytes",w(s),n]}if(Array.isArray(e)){const r=e.map(n=>b(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!l(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,f={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const s=b(n,t+1);r===m?Object.defineProperty(f,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):f[r]=s}return f},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":{const r=y(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3],s=(Object.hasOwn(A,r)?A[r]:void 0)??Error,c=new s(n);c.name!==r&&Object.defineProperty(c,"name",{configurable:!0,value:r,writable:!0});const u=y(e[4],t+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(u))d===m?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:u[d],writable:!0}):c[d]=u[d];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),c}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=p(r),s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const c=Object.hasOwn(g,s)?g[s]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(f=>y(f,t+1))}const a=e,o={};for(const f of Object.keys(a)){const r=y(a[f],t+1);f===m?Object.defineProperty(o,f,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[f]=r}return o};export{y as d,b as e,l as i};
|
package/dist/rls/testing.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as y,d as P,f as W,e as v,m as I,g as R}from"../packem_shared/middleware-
|
|
1
|
+
import{i as y,d as P,f as W,e as v,m as I,g as R}from"../packem_shared/middleware-BvY85EHz.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/server",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.103",
|
|
4
4
|
"description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"backend",
|
|
@@ -66,9 +66,9 @@
|
|
|
66
66
|
"access": "public"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
70
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
71
|
-
"@lunora/values": "1.0.0-alpha.
|
|
69
|
+
"@lunora/errors": "1.0.0-alpha.32",
|
|
70
|
+
"@lunora/scheduler": "1.0.0-alpha.52",
|
|
71
|
+
"@lunora/values": "1.0.0-alpha.40",
|
|
72
72
|
"drizzle-orm": "^0.45.2",
|
|
73
73
|
"hono": "^4.13.1"
|
|
74
74
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{v as o,optionalInner as b}from"@lunora/values";const g=25,A=100,O=100,S=8,w=new Set(["id","storage","string"]),p=t=>{const n=b(t)??t;if(w.has(n.kind))return!0;const r=n._meta;if(n.kind==="literal")return typeof r?.value=="string";if(n.kind!=="union"||r?.members===void 0)return!1;const{members:s}=r;return s.some(e=>p(e))&&s.every(e=>e.kind==="null"||p(e))},L=(t,n)=>{const r=s=>o.optional(o.array(s).check(e=>e.length<=n,{message:`at most ${String(n)} values`}));return o.object({...p(t)?{contains:o.optional(o.string())}:{},eq:o.optional(t),gt:o.optional(t),gte:o.optional(t),in:r(t),isNull:o.optional(o.boolean()),lt:o.optional(t),lte:o.optional(t),ne:o.optional(t),notIn:r(t)})},_=(t,n,r)=>t===void 0||!Number.isFinite(t)?Math.min(n,r):Math.min(Math.max(1,Math.floor(t)),r),u=(t,n)=>t===void 0||!Number.isFinite(t)?n:Math.max(1,Math.floor(t)),I=new Set(["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"]),M=(t,n,r)=>{if(typeof t!="object"||t===null||Array.isArray(t))return;const s=t,e={};let l=0;for(const a of I){if(!Object.hasOwn(s,a)||(l+=1,a==="contains"&&!r))continue;const c=s[a];e[a]=Array.isArray(c)?c.slice(0,n):c}return l===0?void 0:e},B=(t,n,r,s)=>{const e={};for(const l of n){if(!Object.hasOwn(t,l))continue;const a=t[l],c=M(a,s,r.has(l));c!==void 0&&Object.keys(c).length===0||(e[l]=c??a)}return e},T=()=>t=>{const n=u(t.defaultLimit,g),r=u(t.maxLimit,A),s=u(t.maxInValues,O),e=u(t.maxOrderBy,S),l=new Set(Object.keys(t.filter)),a=new Set,c={};for(const[i,d]of Object.entries(t.filter))p(d)&&a.add(i),c[i]=o.optional(o.union(d,L(d,s)));const h=new Set(t.orderBy),y=t.orderBy.length===0?o.string().check(()=>!1,{message:"no sortable columns are declared for this endpoint"}):o.union(...t.orderBy.map(i=>o.literal(i)));return{args:{cursor:o.optional(o.union(o.string(),o.number(),o.null())),limit:o.optional(o.number()),orderBy:o.optional(o.array(o.object({direction:o.optional(o.union(o.literal("asc"),o.literal("desc"))),field:y}))),where:o.optional(o.object(c))},toQueryArgs:i=>{const d=i.orderBy?.filter(m=>h.has(m.field)).slice(0,e).map(m=>({[m.field]:m.direction??"asc"})),f=i.where===void 0?void 0:B(i.where,l,a,s);return{...i.cursor===void 0?{}:{cursor:typeof i.cursor=="number"?String(i.cursor):i.cursor},limit:_(i.limit,n,r),...d===void 0||d.length===0?{}:{orderBy:d},...f===void 0?{}:{where:f}}}}};export{g as DEFAULT_LIMIT,O as DEFAULT_MAX_IN_VALUES,A as DEFAULT_MAX_LIMIT,S as DEFAULT_MAX_ORDER_BY,_ as clampLimit,T as defineListArgs,u as normalizeBound,B as sanitizeWhere};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{v as r}from"@lunora/values";import{d as A,e as h}from"./wire-codec-BOMWQpoF.mjs";import{initLunora as v}from"./initLunora-D5TSiy5j.mjs";import{g as x,h as R,a as U}from"./plugin-yKCbHnlj.mjs";const H=2160*60*60*1e3,q=64*1024,E=200,C=64,F=512,y=16,L=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],p="documentHistory",I="versions",l=`${p}_${I}`,P=x(p,{tables:{[I]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:j}=v.dataModel().create(),X=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):q,D=new Set([...B,...d.redact??[]]);let b=0;const M=()=>(b+=1,b),m=(e,t=0)=>{if(Array.isArray(e))return t>=y?void 0:e.map(o=>m(o,t+1));if(typeof e!="object"||e===null||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=y))return Object.fromEntries(Object.entries(e).filter(([o])=>!D.has(o)).map(([o,i])=>[o,m(i,t+1)]))},f=e=>{if(e===void 0)return;const t=JSON.stringify(h(m(e)));return new TextEncoder().encode(t).length>_?void 0:t},u=async(e,t)=>{const o=f(t.doc),i=f(t.previous),n=t.doc!==void 0&&o===void 0||t.previous!==void 0&&i===void 0;await e.db.insert(l,{documentId:t.documentId,op:t.op,recordedAt:Date.now(),seq:M(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},S=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>u(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),N=j.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:t})=>{const o=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):E,i=await t.db.query(l).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(o);return i.sort((n,a)=>{for(const c of L){const s=(a[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:A(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:A(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let a=0;a<C&&n<i;a+=1){const c=await t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(E,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(p,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:S}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,X as defineDocumentHistory,P as documentHistoryExtension};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{LunoraError as E,toErrorBody as O,isLunoraError as P}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as N}from"@lunora/values";import{Hono as _}from"hono";import{a as q}from"./apply-output-C5wZ5EAL.mjs";const V=e=>async r=>e(r.get("lunora"),r.req.raw),$=()=>{const e=new _;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},k=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},x=(e,r,o)=>{const n=k(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const d=n._meta?.inner;return a.map(i=>g(d?.kind??"string",i))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},v=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=x(t,r,n))}return R(e,o,"searchParams")},S=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const d=o[t];n[t]=d===void 0?void 0:g(k(a).kind,d)}return R(e,n,"params")},C=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return R(e,o,"body")},T=e=>{if(e instanceof N)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(P(e)){const{body:r,redacted:o,status:n}=O(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message},{status:n})}throw e},j=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},H=(e,r)=>async o=>{const n=j(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?v(e.searchParams,o):{},d=Object.keys(e.params).length>0?S(e.params,o):{},i=Object.keys(e.body).length>0?await C(e.body,o):{},h=await r({body:i,ctx:t,params:d,searchParams:a}),s=e.output?q(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const p=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:p?c:void 0,status:204}):Response.json(s,{headers:p?c:void 0})}catch(t){return T(t)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,r)=>{const o=JSON.stringify(e);return`${r?`event: ${r}
|
|
2
|
-
`:""}data: ${o}
|
|
3
|
-
|
|
4
|
-
`},L=(e,r)=>(async o=>{const n=j(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?v(e.searchParams,o):{},a=Object.keys(e.params).length>0?S(e.params,o):{}}catch(m){return T(m)}const d=o.get("lunora"),i=o.req.raw,h=new TextEncoder,s=new AbortController;if(i.signal.aborted)return s.abort(),new Response("",{headers:w});const c=()=>{s.abort()};i.signal.addEventListener("abort",c,{once:!0});const p=new ReadableStream({cancel(){i.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const f=r({ctx:d,params:a,request:i,searchParams:t,signal:s.signal});for await(const y of f){if(s.signal.aborted)break;m.enqueue(h.encode(b(y)))}s.signal.aborted||m.enqueue(h.encode(b({},"complete")))}catch(f){const{body:y,redacted:A}=O(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});A&&console.error("[lunora] unhandled stream handler error:",f),s.signal.aborted||m.enqueue(h.encode(b({code:y.code,message:y.message},"error")))}finally{i.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(p,{headers:w})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>H(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>L(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),U={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},J=e=>!(e.includes("\r")||e.includes(`
|
|
5
|
-
`)||e.includes("\0"));export{V as httpAction,U as httpRoute,$ as httpRouter,J as isSafeHeaderValue};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{i as y,a as R}from"./middleware-BU9adRMp.mjs";const U=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},v=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},N=[["delete","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",v],["getUrl","read"],["head","read"],["store","write"]],$=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},A=(e,t)=>{const o=e.bucketName??"default",{bucket:c}=e;for(const s of new Set(t))if(!(s===o||typeof c=="function"&&$(c,s)))throw new b("INTERNAL",`storageRules: rule for bucket "${s}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${s}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},S=(e,t={})=>{const o=y(t.roles);return async({ctx:c,next:s})=>{const g=await R(c.auth??{},o),w=(n,a,i)=>{const d=e.filter(r=>r.on===n&&r.bucket===i);if(d.length===0)return;const u={auth:g,ctx:c,key:a};if(!d.some(r=>U(r.prefix,a)&&r.when(u)===!0))throw new b("FORBIDDEN",`storage ${n} on "${a}" in bucket "${i}" denied by access rule`)},p=n=>{const a=n.bucketName??"default",i={bucketName:a};for(const[u,l]of N){const r=n[u];typeof r=="function"&&(i[u]=(...f)=>{const k=typeof f[0]=="string"?f[0]:"",m=typeof l=="function"?l(f):l;return w(m,k,a),r(...f)})}const{bucket:d}=n;return typeof d=="function"&&(i.bucket=u=>p(d(u))),i},h=c.storage;return h===void 0?s():(A(h,e.map(n=>n.bucket)),s({ctx:{storage:p(h)}}))}};export{S as storageRules};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const d=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},p=e=>{const t=atob(e),a=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)a[o]=t.codePointAt(o)??0;return a},i="$lunora.wire$";const w="__proto__",g={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},A={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},u=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const a=typeof e;if(a==="bigint")return[i,"bigint",e.toString()];if(a==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(a!=="object")return e;if(e instanceof Date)return[i,"date",u(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const s of Object.keys(r))r[s]!==void 0&&(n[s]=u(r[s],t+1));const c=[i,"error",r.name,r.message,n];return r.cause!==void 0&&c.push(u(r.cause,t+1)),c}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[u(r,t+1),u(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>u(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",d(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,c=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",d(c)]:[i,"bytes",d(c),n]}if(Array.isArray(e)){const r=e.map(n=>u(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!l(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,f={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const c=u(n,t+1);r===w?Object.defineProperty(f,r,{configurable:!0,enumerable:!0,value:c,writable:!0}):f[r]=c}return f},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":{const r=y(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3],c=(Object.hasOwn(A,r)?A[r]:void 0)??Error,s=new c(n);s.name!==r&&Object.defineProperty(s,"name",{configurable:!0,value:r,writable:!0});const b=y(e[4],t+1);if(b===null||typeof b!="object"||Array.isArray(b))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(b))m===w?Object.defineProperty(s,m,{configurable:!0,enumerable:!0,value:b[m],writable:!0}):s[m]=b[m];return e.length>5&&Object.defineProperty(s,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),s}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=p(r),c=e[3]??"Uint8Array";if(c==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const s=Object.hasOwn(g,c)?g[c]:void 0;return s?new s(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(f=>y(f,t+1))}const a=e,o={};for(const f of Object.keys(a)){const r=y(a[f],t+1);f===w?Object.defineProperty(o,f,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[f]=r}return o};export{y as d,u as e,l as i};
|