@sanity-labs/client-fake-for-test 0.29.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +130 -1
- package/dist/index.cjs +661 -23
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +89 -0
- package/dist/index.d.ts +89 -0
- package/dist/index.js +661 -23
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { parse, evaluate } from "groq-js";
|
|
2
1
|
import { ClientError, ServerError } from "@sanity/client";
|
|
2
|
+
import { parse, evaluate, GroqSyntaxError } from "groq-js";
|
|
3
3
|
import { createHash, createPublicKey, verify } from "node:crypto";
|
|
4
4
|
const ERR_PREFIX = "[client-fake-for-test]";
|
|
5
5
|
function fakeError(message) {
|
|
@@ -260,7 +260,22 @@ const RESOURCE_CAPABILITIES = {
|
|
|
260
260
|
refusedActions: {},
|
|
261
261
|
access: { type: "dashboard", id: (id) => id }
|
|
262
262
|
}
|
|
263
|
+
}, ORGANIZATION_STORE_CAPABILITIES = {
|
|
264
|
+
label: (id) => `organization store "${id}"`,
|
|
265
|
+
dataBase: (id) => `/organization-stores/${id}`,
|
|
266
|
+
matchBase: () => {
|
|
267
|
+
},
|
|
268
|
+
lookupAtBase: !1,
|
|
269
|
+
identity: "global",
|
|
270
|
+
acl: notMounted,
|
|
271
|
+
history: notMounted,
|
|
272
|
+
actions: notMounted,
|
|
273
|
+
refusedActions: {},
|
|
274
|
+
access: { type: "organization", id: (id) => id }
|
|
263
275
|
};
|
|
276
|
+
function storeCapabilitiesOf(type) {
|
|
277
|
+
return type === "organization-store" ? ORGANIZATION_STORE_CAPABILITIES : capabilitiesOf(type);
|
|
278
|
+
}
|
|
264
279
|
function capabilitiesOf(type) {
|
|
265
280
|
const row = Object.hasOwn(RESOURCE_CAPABILITIES, type) ? RESOURCE_CAPABILITIES[type] : void 0;
|
|
266
281
|
if (row === void 0)
|
|
@@ -452,6 +467,316 @@ function badRequest(request, description) {
|
|
|
452
467
|
body: { error: { description, type: "httpBadRequest" } }
|
|
453
468
|
});
|
|
454
469
|
}
|
|
470
|
+
const FUNCTION_INVOKE_PATH = /^\/functions\/([^/]+)\/invoke\/?$/, FUNCTION_TYPES = /* @__PURE__ */ new Set([
|
|
471
|
+
"sanity.function.pubsub",
|
|
472
|
+
"sanity.function.document",
|
|
473
|
+
"sanity.function.queue",
|
|
474
|
+
"sanity.function.durable",
|
|
475
|
+
"sanity.function.schedule",
|
|
476
|
+
"sanity.function.media-library-asset",
|
|
477
|
+
"sanity.function.sync-tag-invalidate"
|
|
478
|
+
]), FUNCTION_ID_MIN_LENGTH = 10, INVOKE_PERMISSIONS = {
|
|
479
|
+
project: [
|
|
480
|
+
"sanity.project.functions.invoke",
|
|
481
|
+
"sanity.project.blueprints.deploy",
|
|
482
|
+
"sanity.project.deployStudio"
|
|
483
|
+
],
|
|
484
|
+
organization: [
|
|
485
|
+
"sanity.organization.functions.invoke",
|
|
486
|
+
"sanity.blueprints.deploy",
|
|
487
|
+
"sanity.organization.tokens.create"
|
|
488
|
+
]
|
|
489
|
+
}, MB_6 = 6291456, LAMBDA_ASYNC_LIMIT = 256 * 1024, CL_EVENTING_HINT = "Invoke the function by issuing a relevant Content Lake mutation operation instead.", STATUS_MESSAGES = {
|
|
490
|
+
400: "Bad Request",
|
|
491
|
+
401: "Unauthorized",
|
|
492
|
+
403: "Forbidden",
|
|
493
|
+
404: "Not Found",
|
|
494
|
+
413: "Payload Too Large"
|
|
495
|
+
};
|
|
496
|
+
function registerFunction(registry, args) {
|
|
497
|
+
const { fn, site } = args;
|
|
498
|
+
if (typeof fn.id != "string" || fn.id.length < FUNCTION_ID_MIN_LENGTH)
|
|
499
|
+
throw fakeError(
|
|
500
|
+
`${site}: function id ${JSON.stringify(fn.id)} is shorter than ${FUNCTION_ID_MIN_LENGTH} characters; the Functions API's ids are at least that long.`
|
|
501
|
+
);
|
|
502
|
+
if (!FUNCTION_TYPES.has(fn.type))
|
|
503
|
+
throw fakeError(
|
|
504
|
+
`${site}: function "${fn.id}" has type ${JSON.stringify(fn.type)}; expected one of ${[...FUNCTION_TYPES].join(", ")}.`
|
|
505
|
+
);
|
|
506
|
+
if (fn.resourceType !== "project" && fn.resourceType !== "organization")
|
|
507
|
+
throw fakeError(
|
|
508
|
+
`${site}: function "${fn.id}" has resourceType ${JSON.stringify(fn.resourceType)}; expected "project" or "organization".`
|
|
509
|
+
);
|
|
510
|
+
const clash = [...registry.functions.values()].find(
|
|
511
|
+
(other) => other.id !== fn.id && other.blueprintStackId === fn.blueprintStackId && other.name === fn.name
|
|
512
|
+
);
|
|
513
|
+
if (clash !== void 0)
|
|
514
|
+
throw fakeError(
|
|
515
|
+
`${site}: functions "${clash.id}" and "${fn.id}" are both named "${fn.name}" in Blueprint stack ${fn.blueprintStackId}; a name is unique within its stack.`
|
|
516
|
+
);
|
|
517
|
+
registry.functions.set(fn.id, { ...fn });
|
|
518
|
+
}
|
|
519
|
+
function unregisterFunction(registry, id) {
|
|
520
|
+
if (!registry.functions.delete(id))
|
|
521
|
+
throw fakeError(
|
|
522
|
+
`removeFunction(): no function has id "${id}". Deployed ids: ${[...registry.functions.keys()].map((known) => `"${known}"`).join(", ") || "none"}.`
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
function refusal(request, args) {
|
|
526
|
+
const { statusCode } = args;
|
|
527
|
+
return new PlatformHttpError({
|
|
528
|
+
...request,
|
|
529
|
+
statusCode,
|
|
530
|
+
statusMessage: STATUS_MESSAGES[statusCode],
|
|
531
|
+
body: { error: args.error, message: args.message, details: { errors: args.errors ?? [] } }
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
function invalidInput(request, issues) {
|
|
535
|
+
return new PlatformHttpError({
|
|
536
|
+
...request,
|
|
537
|
+
statusCode: 400,
|
|
538
|
+
statusMessage: "Bad Request",
|
|
539
|
+
body: {
|
|
540
|
+
details: { errors: [{ message: issues.map((issue) => issue.pretty).join(`
|
|
541
|
+
`) }] },
|
|
542
|
+
error: "INVALID_INPUT",
|
|
543
|
+
message: `Validation error: ${issues.map((issue) => issue.summary).join("; ")}`
|
|
544
|
+
}
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
function prettyPath(path) {
|
|
548
|
+
return path.map((key, index) => /^[A-Za-z_$][\w$]*$/.test(key) ? index === 0 ? key : `.${key}` : `[${JSON.stringify(key)}]`).join("");
|
|
549
|
+
}
|
|
550
|
+
function issueAt(path, message) {
|
|
551
|
+
return path.length === 0 ? { summary: message, pretty: `\u2716 ${message}` } : {
|
|
552
|
+
summary: `${message} at "${path.join(".")}"`,
|
|
553
|
+
pretty: `\u2716 ${message}
|
|
554
|
+
\u2192 at ${prettyPath(path)}`
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
function tooShort(args) {
|
|
558
|
+
const { key, min, value } = args;
|
|
559
|
+
if (!(value.length >= min))
|
|
560
|
+
return issueAt([key], `Too small: expected string to have >=${min} characters`);
|
|
561
|
+
}
|
|
562
|
+
function typeName(value) {
|
|
563
|
+
return value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
|
|
564
|
+
}
|
|
565
|
+
function isRecord(value) {
|
|
566
|
+
return typeName(value) === "object";
|
|
567
|
+
}
|
|
568
|
+
function bodyIssue(body) {
|
|
569
|
+
const parts = [[[], body]];
|
|
570
|
+
isRecord(body) && (parts.push([["event"], body.event]), isRecord(body.event) && parts.push([["event", "data"], body.event.data]));
|
|
571
|
+
const failed = parts.find(([, value2]) => !isRecord(value2));
|
|
572
|
+
if (failed === void 0) return;
|
|
573
|
+
const [path, value] = failed;
|
|
574
|
+
return issueAt(path, `Invalid input: expected object, received ${typeName(value)}`);
|
|
575
|
+
}
|
|
576
|
+
function parseQuery$1(request) {
|
|
577
|
+
const queryStart = request.url.indexOf("?"), query = new URLSearchParams(queryStart === -1 ? "" : request.url.slice(queryStart + 1)), repeated = ["blueprintStackId", "sync"].find((key) => query.getAll(key).length > 1);
|
|
578
|
+
if (repeated !== void 0)
|
|
579
|
+
throw fakeError(
|
|
580
|
+
`request(): ${request.path} got "${repeated}" more than once; Hono reads a repeated query key as an array, whose validation answer the fake does not model. Pass it once.`
|
|
581
|
+
);
|
|
582
|
+
const blueprintStackId = query.get("blueprintStackId") ?? void 0, sync = query.get("sync") ?? "false", issues = [
|
|
583
|
+
blueprintStackId === void 0 ? void 0 : tooShort({ key: "blueprintStackId", min: 10, value: blueprintStackId }),
|
|
584
|
+
sync === "true" || sync === "false" ? void 0 : {
|
|
585
|
+
summary: 'Invalid input: expected "true" at "sync" or Invalid input: expected "false" at "sync"',
|
|
586
|
+
pretty: `\u2716 Invalid input
|
|
587
|
+
\u2192 at sync`
|
|
588
|
+
}
|
|
589
|
+
].filter((issue) => issue !== void 0);
|
|
590
|
+
return issues.length > 0 ? issues : { blueprintStackId, sync: sync === "true" };
|
|
591
|
+
}
|
|
592
|
+
function decodeSegment$1(segment) {
|
|
593
|
+
try {
|
|
594
|
+
return decodeURIComponent(segment);
|
|
595
|
+
} catch {
|
|
596
|
+
return segment;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
function lowercaseHeaders(headers) {
|
|
600
|
+
return new Map(Object.entries(headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]));
|
|
601
|
+
}
|
|
602
|
+
function cannotInvoke(fn, sync) {
|
|
603
|
+
switch (fn.type) {
|
|
604
|
+
case "sanity.function.document":
|
|
605
|
+
case "sanity.function.media-library-asset":
|
|
606
|
+
case "sanity.function.sync-tag-invalidate":
|
|
607
|
+
return `Content Lake evented functions like ${fn.type} cannot be directly invoked. ${CL_EVENTING_HINT}`;
|
|
608
|
+
case "sanity.function.schedule":
|
|
609
|
+
return `${fn.type} functions cannot be directly invoked.`;
|
|
610
|
+
case "sanity.function.queue":
|
|
611
|
+
case "sanity.function.durable":
|
|
612
|
+
return sync ? `${fn.type} functions cannot be synchronously invoked.` : void 0;
|
|
613
|
+
case "sanity.function.pubsub":
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
function inScope(organizationId, args) {
|
|
618
|
+
const { fn, scope } = args;
|
|
619
|
+
return fn.resourceType === scope.type && fn.resourceId === scope.id ? !0 : scope.type === "organization" && fn.resourceType === "project" && organizationId !== void 0 && organizationId === scope.id;
|
|
620
|
+
}
|
|
621
|
+
function admitScope(ctx, args) {
|
|
622
|
+
const { request, headers } = args, type = headers.get("x-sanity-scope-type"), id = headers.get("x-sanity-scope-id");
|
|
623
|
+
if (!type || !id)
|
|
624
|
+
throw refusal(request, {
|
|
625
|
+
statusCode: 400,
|
|
626
|
+
error: "MISSING_SCOPE",
|
|
627
|
+
message: "X-Sanity-Scope-Type and X-Sanity-Scope-Id headers are required"
|
|
628
|
+
});
|
|
629
|
+
if (type !== "project" && type !== "organization")
|
|
630
|
+
throw refusal(request, {
|
|
631
|
+
statusCode: 400,
|
|
632
|
+
error: "INVALID_SCOPE_TYPE",
|
|
633
|
+
message: "Only organization and project scopes are currently supported"
|
|
634
|
+
});
|
|
635
|
+
if (ctx.projectApiDown())
|
|
636
|
+
throw new PlatformServerError({
|
|
637
|
+
...request,
|
|
638
|
+
statusCode: 500,
|
|
639
|
+
statusMessage: "Internal Server Error",
|
|
640
|
+
body: {
|
|
641
|
+
error: "ACCESS_ERROR",
|
|
642
|
+
message: "Failed to validate project access",
|
|
643
|
+
details: { errors: [] }
|
|
644
|
+
}
|
|
645
|
+
});
|
|
646
|
+
const required = INVOKE_PERMISSIONS[type], held = ctx.actorAccess()?.[accessKey(type, id)]?.permissions ?? [];
|
|
647
|
+
if (!required.some((permission) => held.includes(permission)))
|
|
648
|
+
throw refusal(request, {
|
|
649
|
+
statusCode: 403,
|
|
650
|
+
error: "FORBIDDEN",
|
|
651
|
+
message: `You do not have invoke access to ${type} ${id}`,
|
|
652
|
+
errors: { required: [...required] }
|
|
653
|
+
});
|
|
654
|
+
return { type, id };
|
|
655
|
+
}
|
|
656
|
+
function validate(request, parts) {
|
|
657
|
+
const query = parseQuery$1(request);
|
|
658
|
+
if (Array.isArray(query)) throw invalidInput(request, query);
|
|
659
|
+
const issue = [
|
|
660
|
+
tooShort({ key: "functionId", min: 3, value: parts.segment }),
|
|
661
|
+
tooShort({
|
|
662
|
+
key: "x-sanity-scope-id",
|
|
663
|
+
min: 8,
|
|
664
|
+
value: parts.headers.get("x-sanity-scope-id")
|
|
665
|
+
}),
|
|
666
|
+
bodyIssue(parts.body)
|
|
667
|
+
].find((found) => found !== void 0);
|
|
668
|
+
if (issue !== void 0) throw invalidInput(request, [issue]);
|
|
669
|
+
const { event } = parts.body;
|
|
670
|
+
return { ...query, data: event.data };
|
|
671
|
+
}
|
|
672
|
+
function findFunction(registry, args) {
|
|
673
|
+
const { request, segment, blueprintStackId } = args;
|
|
674
|
+
if (blueprintStackId === void 0) {
|
|
675
|
+
if (segment.length < FUNCTION_ID_MIN_LENGTH)
|
|
676
|
+
throw refusal(request, {
|
|
677
|
+
statusCode: 400,
|
|
678
|
+
error: "BAD_REQUEST",
|
|
679
|
+
message: "Invalid functionId"
|
|
680
|
+
});
|
|
681
|
+
return registry.functions.get(segment);
|
|
682
|
+
}
|
|
683
|
+
const byName = [...registry.functions.values()].find(
|
|
684
|
+
(fn) => fn.blueprintStackId === blueprintStackId && fn.name === segment
|
|
685
|
+
);
|
|
686
|
+
if (byName === void 0)
|
|
687
|
+
throw refusal(request, {
|
|
688
|
+
statusCode: 404,
|
|
689
|
+
error: "FUNCTION_NOT_FOUND",
|
|
690
|
+
message: `Function "${segment}" was not found in Blueprint Stack ${blueprintStackId}`
|
|
691
|
+
});
|
|
692
|
+
return byName;
|
|
693
|
+
}
|
|
694
|
+
function refuseOversized(request, args) {
|
|
695
|
+
const size = Buffer.byteLength(
|
|
696
|
+
JSON.stringify({ data: args.data, invokedBySanityUserId: args.userId, lineage: "" }),
|
|
697
|
+
"utf8"
|
|
698
|
+
);
|
|
699
|
+
if (!args.sync && size >= LAMBDA_ASYNC_LIMIT)
|
|
700
|
+
throw refusal(request, {
|
|
701
|
+
statusCode: 413,
|
|
702
|
+
error: "CONTENT_TOO_LARGE",
|
|
703
|
+
message: `Invoke payload must be smaller than ${LAMBDA_ASYNC_LIMIT} bytes for asynchronous invocations; current size=${size} bytes. Reduce payload size or set sync=true (not recommended due to blocking network request).`
|
|
704
|
+
});
|
|
705
|
+
if (args.sync && size > MB_6)
|
|
706
|
+
throw refusal(request, {
|
|
707
|
+
statusCode: 413,
|
|
708
|
+
error: "CONTENT_TOO_LARGE",
|
|
709
|
+
message: `Invoke payload must be smaller than ${MB_6} bytes for synchronous invocations; current size=${size} bytes.`
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
function serveFunctionInvoke(ctx, invoke) {
|
|
713
|
+
const { request, ...parts } = invoke, pathVersion = `v${ctx.apiVersion}`;
|
|
714
|
+
if (!/^v\d{4}-\d{2}-\d{2}$/.test(pathVersion) && pathVersion !== "vX")
|
|
715
|
+
throw refusal(request, {
|
|
716
|
+
statusCode: 400,
|
|
717
|
+
error: "BAD_REQUEST",
|
|
718
|
+
message: "Invalid API version in path",
|
|
719
|
+
errors: { version: pathVersion }
|
|
720
|
+
});
|
|
721
|
+
if (ctx.internalToken())
|
|
722
|
+
throw refusal(request, {
|
|
723
|
+
statusCode: 401,
|
|
724
|
+
error: "INVALID_TOKEN",
|
|
725
|
+
message: "Missing required claim: guid"
|
|
726
|
+
});
|
|
727
|
+
const headers = lowercaseHeaders(parts.headers), scope = admitScope(ctx, { request, headers });
|
|
728
|
+
if (parts.body === void 0)
|
|
729
|
+
throw fakeError(
|
|
730
|
+
`request(): POST ${request.path} without a body. The Functions API answers it with a 500 once its pre-flight checks pass, which the fake does not model. Send \`body: { event: { data: {} } }\`.`
|
|
731
|
+
);
|
|
732
|
+
if (typeof parts.body != "object" || parts.body === null)
|
|
733
|
+
throw fakeError(
|
|
734
|
+
`request(): POST ${request.path} with a ${typeof parts.body} body; @sanity/client sends it without a JSON content type, which the fake does not model. Send an object.`
|
|
735
|
+
);
|
|
736
|
+
if (Buffer.byteLength(JSON.stringify(parts.body), "utf8") > MB_6)
|
|
737
|
+
throw refusal(request, {
|
|
738
|
+
statusCode: 413,
|
|
739
|
+
error: "CONTENT_TOO_LARGE",
|
|
740
|
+
message: `Request must be smaller than ${MB_6} bytes for the Invoke Function operation`
|
|
741
|
+
});
|
|
742
|
+
const segment = decodeSegment$1(request.path.match(FUNCTION_INVOKE_PATH)[1]), { blueprintStackId, sync, data } = validate(request, {
|
|
743
|
+
segment,
|
|
744
|
+
headers,
|
|
745
|
+
body: parts.body
|
|
746
|
+
}), fn = findFunction(ctx.registry, { request, segment, blueprintStackId });
|
|
747
|
+
if (fn === void 0 || !inScope(ctx.organizationId, { fn, scope }))
|
|
748
|
+
throw refusal(request, {
|
|
749
|
+
statusCode: 404,
|
|
750
|
+
error: "FUNCTION_NOT_FOUND",
|
|
751
|
+
message: "function not found"
|
|
752
|
+
});
|
|
753
|
+
const notInvokable = cannotInvoke(fn, sync);
|
|
754
|
+
if (notInvokable !== void 0)
|
|
755
|
+
throw refusal(request, {
|
|
756
|
+
statusCode: 400,
|
|
757
|
+
error: "INVOKE_NOT_SUPPORTED",
|
|
758
|
+
message: notInvokable
|
|
759
|
+
});
|
|
760
|
+
if (headers.has("x-sanity-lineage"))
|
|
761
|
+
throw fakeError(
|
|
762
|
+
`request(): POST ${request.path} with an x-sanity-lineage header; the Functions API's recursion limit is not modelled. Omit the header.`
|
|
763
|
+
);
|
|
764
|
+
const userId = ctx.actorUser().id;
|
|
765
|
+
if (refuseOversized(request, { data, userId, sync }), sync)
|
|
766
|
+
throw fakeError(
|
|
767
|
+
`request(): POST ${request.path}?sync=true passed every check the Functions API makes, but synchronous invocation (the function's return value) is not modelled. Invoke asynchronously: omit \`sync\` or pass \`sync: "false"\`.`
|
|
768
|
+
);
|
|
769
|
+
ctx.registry.invocations.push({
|
|
770
|
+
functionId: fn.id,
|
|
771
|
+
name: fn.name,
|
|
772
|
+
blueprintStackId: fn.blueprintStackId,
|
|
773
|
+
scopeType: scope.type,
|
|
774
|
+
scopeId: scope.id,
|
|
775
|
+
sync,
|
|
776
|
+
event: { data: structuredClone(data) },
|
|
777
|
+
invokedBy: { userId }
|
|
778
|
+
});
|
|
779
|
+
}
|
|
455
780
|
function createDocumentHistory() {
|
|
456
781
|
const transactions = [], revisions = /* @__PURE__ */ new Map(), keep = (doc) => revisions.set(`${doc._id} ${doc._rev}`, structuredClone(doc)), deleted = /* @__PURE__ */ new Map();
|
|
457
782
|
return {
|
|
@@ -1111,6 +1436,7 @@ function serveProject(args) {
|
|
|
1111
1436
|
function makeRequestImpl(ctx) {
|
|
1112
1437
|
const { getAccess, requestFor, useProjectHostname, listIdentities, organizationId, platform } = ctx;
|
|
1113
1438
|
return async (opts) => {
|
|
1439
|
+
if ((opts.method ?? "GET").toUpperCase() !== "GET") return servePost(ctx, opts);
|
|
1114
1440
|
const accessControl = getAccess(), path = opts.uri ?? opts.url;
|
|
1115
1441
|
if (path === "/users/me") {
|
|
1116
1442
|
const user = useProjectHostname ? accessControl.currentUser : accessControl.globalUser ?? accessControl.currentUser;
|
|
@@ -1139,6 +1465,18 @@ function makeRequestImpl(ctx) {
|
|
|
1139
1465
|
);
|
|
1140
1466
|
};
|
|
1141
1467
|
}
|
|
1468
|
+
function servePost(ctx, opts) {
|
|
1469
|
+
const request = ctx.requestFor(opts);
|
|
1470
|
+
if (request.method === "POST" && FUNCTION_INVOKE_PATH.test(request.path))
|
|
1471
|
+
return serveFunctionInvoke(ctx.functions, {
|
|
1472
|
+
request,
|
|
1473
|
+
body: opts.body,
|
|
1474
|
+
headers: opts.headers
|
|
1475
|
+
});
|
|
1476
|
+
throw fakeError(
|
|
1477
|
+
`request(): no handler for ${opts.method} "${opts.uri ?? opts.url}". The fake serves POST on "/functions/<idOrName>/invoke" (the Functions API) only. For any other endpoint, register a stub (client.stub("request", fn)) or intercept the HTTP call with a tool like MSW.`
|
|
1478
|
+
);
|
|
1479
|
+
}
|
|
1142
1480
|
class GuardDeniedError extends ClientError {
|
|
1143
1481
|
type = "guardDeniedError";
|
|
1144
1482
|
denials;
|
|
@@ -2143,6 +2481,107 @@ function internalTokenRefusal(request, check) {
|
|
|
2143
2481
|
}
|
|
2144
2482
|
});
|
|
2145
2483
|
}
|
|
2484
|
+
const IDENT = /[A-Za-z_][A-Za-z0-9_]*/y, SIMPLE_ESCAPES = /* @__PURE__ */ new Set(['"', "'", "\\", "/", "b", "f", "n", "r", "t"]), UNICODE_ESCAPE = /u([0-9A-Fa-f]{4})/y;
|
|
2485
|
+
function refuseUnsentParams(args) {
|
|
2486
|
+
const { request, query, params = {}, syntaxErrorAt } = args, { references, invalidStringAt } = scanQuery(query), errorAt = Math.min(syntaxErrorAt ?? 1 / 0, invalidStringAt ?? 1 / 0), unsent = references.find(
|
|
2487
|
+
(reference) => reference.index < errorAt && !isSent(params, reference.name)
|
|
2488
|
+
);
|
|
2489
|
+
if (unsent === void 0) return;
|
|
2490
|
+
const start = codePoints(query.slice(0, unsent.index));
|
|
2491
|
+
throw new PlatformHttpError({
|
|
2492
|
+
...request,
|
|
2493
|
+
statusCode: 400,
|
|
2494
|
+
statusMessage: "Bad Request",
|
|
2495
|
+
body: {
|
|
2496
|
+
error: {
|
|
2497
|
+
description: `param $${unsent.name} referenced, but not provided`,
|
|
2498
|
+
end: start + unsent.name.length,
|
|
2499
|
+
query,
|
|
2500
|
+
...start !== 0 ? { start } : {},
|
|
2501
|
+
type: "queryParseError"
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
});
|
|
2505
|
+
}
|
|
2506
|
+
function isSent(params, name) {
|
|
2507
|
+
return Object.hasOwn(params, name) && params[name] !== void 0;
|
|
2508
|
+
}
|
|
2509
|
+
function scanQuery(query) {
|
|
2510
|
+
const references = [];
|
|
2511
|
+
let declaration, atStatementStart = !0, index = 0;
|
|
2512
|
+
for (; index < query.length; ) {
|
|
2513
|
+
const char = query[index];
|
|
2514
|
+
if (char === '"' || char === "'") {
|
|
2515
|
+
const end = stringEnd(query, index);
|
|
2516
|
+
if (end === void 0) return { references, invalidStringAt: index };
|
|
2517
|
+
index = end, atStatementStart = !1;
|
|
2518
|
+
continue;
|
|
2519
|
+
}
|
|
2520
|
+
if (query.startsWith("//", index)) {
|
|
2521
|
+
const newline = query.indexOf(`
|
|
2522
|
+
`, index);
|
|
2523
|
+
index = newline === -1 ? query.length : newline + 1;
|
|
2524
|
+
continue;
|
|
2525
|
+
}
|
|
2526
|
+
if (/\s/.test(char)) {
|
|
2527
|
+
index++;
|
|
2528
|
+
continue;
|
|
2529
|
+
}
|
|
2530
|
+
if (atStatementStart && isKeyword(query, index, "fn")) {
|
|
2531
|
+
declaration = { params: /* @__PURE__ */ new Set(), header: !0 }, atStatementStart = !1, index += 2;
|
|
2532
|
+
continue;
|
|
2533
|
+
}
|
|
2534
|
+
if (atStatementStart = !1, declaration?.header && char === ")" && (declaration.header = !1), declaration !== void 0 && char === ";") {
|
|
2535
|
+
declaration = void 0, atStatementStart = !0, index++;
|
|
2536
|
+
continue;
|
|
2537
|
+
}
|
|
2538
|
+
if (char === "$") {
|
|
2539
|
+
IDENT.lastIndex = index + 1;
|
|
2540
|
+
const name = IDENT.exec(query)?.[0];
|
|
2541
|
+
if (name !== void 0) {
|
|
2542
|
+
declaration?.header ? declaration.params.add(name) : declaration?.params.has(name) || references.push({ name, index }), index += 1 + name.length;
|
|
2543
|
+
continue;
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
index++;
|
|
2547
|
+
}
|
|
2548
|
+
return { references, invalidStringAt: void 0 };
|
|
2549
|
+
}
|
|
2550
|
+
function isKeyword(query, index, word) {
|
|
2551
|
+
return query.startsWith(word, index) && !/[A-Za-z0-9_]/.test(query[index + word.length] ?? "");
|
|
2552
|
+
}
|
|
2553
|
+
function stringEnd(query, index) {
|
|
2554
|
+
const quote = query[index];
|
|
2555
|
+
let at = index + 1;
|
|
2556
|
+
for (; at < query.length && query[at] !== quote; ) {
|
|
2557
|
+
if (query[at] !== "\\") {
|
|
2558
|
+
at++;
|
|
2559
|
+
continue;
|
|
2560
|
+
}
|
|
2561
|
+
const escaped = escapeLength(query, at + 1);
|
|
2562
|
+
if (escaped === void 0) return;
|
|
2563
|
+
at += 1 + escaped;
|
|
2564
|
+
}
|
|
2565
|
+
return at + 1;
|
|
2566
|
+
}
|
|
2567
|
+
function escapeLength(query, index) {
|
|
2568
|
+
const char = query[index];
|
|
2569
|
+
if (char === void 0) return 0;
|
|
2570
|
+
if (SIMPLE_ESCAPES.has(char)) return 1;
|
|
2571
|
+
const unit = unicodeEscape(query, index);
|
|
2572
|
+
if (unit === void 0 || unit >= 56320 && unit <= 57343) return;
|
|
2573
|
+
if (unit < 55296 || unit > 56319) return 5;
|
|
2574
|
+
const low = query[index + 5] === "\\" ? unicodeEscape(query, index + 6) : void 0;
|
|
2575
|
+
return low !== void 0 && low >= 56320 && low <= 57343 ? 11 : void 0;
|
|
2576
|
+
}
|
|
2577
|
+
function unicodeEscape(query, index) {
|
|
2578
|
+
UNICODE_ESCAPE.lastIndex = index;
|
|
2579
|
+
const hex = UNICODE_ESCAPE.exec(query)?.[1];
|
|
2580
|
+
return hex === void 0 ? void 0 : Number.parseInt(hex, 16);
|
|
2581
|
+
}
|
|
2582
|
+
function codePoints(text) {
|
|
2583
|
+
return [...text].length;
|
|
2584
|
+
}
|
|
2146
2585
|
const ISSUES_URL = "https://github.com/sanity-labs/client-fake-for-test/issues", SUPPORTED_SURFACE = [
|
|
2147
2586
|
"fetch",
|
|
2148
2587
|
"getDocument",
|
|
@@ -2305,6 +2744,42 @@ function wrapWithGuards(client, config) {
|
|
|
2305
2744
|
}
|
|
2306
2745
|
});
|
|
2307
2746
|
}
|
|
2747
|
+
const READ_ROUTE = /^\/workflows\/organizations\/([^/]+)\/(query|doc|listen)(?=\/|$)(.*)$/, STORE_ROUTE = /^\/organization-stores\/([^/]+)\/(query|mutate|doc|listen|export|references|actions|history)(?=\/|$)(.*)$/, SERVICE_ROUTE = /^\/workflows(?=\/|$)/;
|
|
2748
|
+
function matchWorkflowsStoreRoute(args) {
|
|
2749
|
+
const { path, apiVersion } = args, read = path.match(READ_ROUTE);
|
|
2750
|
+
if (read !== null) {
|
|
2751
|
+
if (apiVersion !== "X") return "unrouted";
|
|
2752
|
+
const [, organizationId, action, rest] = read;
|
|
2753
|
+
return { route: "read", organizationId: decodeURIComponent(organizationId), action, rest };
|
|
2754
|
+
}
|
|
2755
|
+
const store = path.match(STORE_ROUTE);
|
|
2756
|
+
if (store !== null) {
|
|
2757
|
+
if (apiVersion === "1") return "unrouted";
|
|
2758
|
+
const [, storeId, action, rest] = store;
|
|
2759
|
+
return { route: "store", storeId: decodeURIComponent(storeId), action, rest };
|
|
2760
|
+
}
|
|
2761
|
+
if (SERVICE_ROUTE.test(path)) return apiVersion === "X" ? "service" : "unrouted";
|
|
2762
|
+
}
|
|
2763
|
+
function noRouteMatched(request) {
|
|
2764
|
+
return new PlatformHttpError({
|
|
2765
|
+
...request,
|
|
2766
|
+
statusCode: 404,
|
|
2767
|
+
statusMessage: "Not Found",
|
|
2768
|
+
body: { message: "no Route matched with those values" }
|
|
2769
|
+
});
|
|
2770
|
+
}
|
|
2771
|
+
function storeNotFound(request, identifier) {
|
|
2772
|
+
return new PlatformHttpError({
|
|
2773
|
+
...request,
|
|
2774
|
+
statusCode: 404,
|
|
2775
|
+
statusMessage: "Not Found",
|
|
2776
|
+
body: {
|
|
2777
|
+
statusCode: 404,
|
|
2778
|
+
error: "Dataset not found",
|
|
2779
|
+
message: `Dataset for id "${identifier}" not found`
|
|
2780
|
+
}
|
|
2781
|
+
});
|
|
2782
|
+
}
|
|
2308
2783
|
const OPTIONS_ARG_POSITION = {
|
|
2309
2784
|
fetch: 2,
|
|
2310
2785
|
getDocument: 1,
|
|
@@ -2385,6 +2860,79 @@ const registryKey = (resource) => `${resource.type}:${resource.id}`, datasetReso
|
|
|
2385
2860
|
);
|
|
2386
2861
|
return validateResource(resource), resource;
|
|
2387
2862
|
};
|
|
2863
|
+
async function serveStoreAction(args) {
|
|
2864
|
+
const { client, history, action, rest, sent, opts } = args, search = new URL(sent.url).searchParams, tag = opts.tag !== void 0 ? { tag: opts.tag } : {};
|
|
2865
|
+
try {
|
|
2866
|
+
if (action === "doc") {
|
|
2867
|
+
if (sent.method !== "GET") throw notAllowed(sent);
|
|
2868
|
+
const ids = rest.slice(1).split(",").map(decodeURIComponent);
|
|
2869
|
+
if (rest === "" || ids.some((id) => id === ""))
|
|
2870
|
+
throw fakeError(`request(): "${sent.path}" names no document id; GET <store>/doc/<ids>.`);
|
|
2871
|
+
const found = await client.getDocuments(ids, tag), readable = new Set(found.flatMap((doc) => doc === null ? [] : [doc._id])), stored = new Set(
|
|
2872
|
+
client.store().all().map((doc) => doc._id)
|
|
2873
|
+
);
|
|
2874
|
+
return {
|
|
2875
|
+
documents: found.filter((doc) => doc !== null),
|
|
2876
|
+
omitted: ids.filter((id) => !readable.has(id)).map((id) => ({ id, reason: stored.has(id) ? "permission" : "existence" }))
|
|
2877
|
+
};
|
|
2878
|
+
}
|
|
2879
|
+
if (action === "query") {
|
|
2880
|
+
const { query, params } = storeQuery(sent, search, opts.body);
|
|
2881
|
+
return await client.fetch(query, params, {
|
|
2882
|
+
filterResponse: !1,
|
|
2883
|
+
returnQuery: search.get("returnQuery") !== "false",
|
|
2884
|
+
...tag
|
|
2885
|
+
});
|
|
2886
|
+
}
|
|
2887
|
+
if (sent.method !== "POST") throw notAllowed(sent);
|
|
2888
|
+
const body = opts.body;
|
|
2889
|
+
if (!Array.isArray(body?.mutations))
|
|
2890
|
+
throw fakeError(`request(): POST "${sent.path}" needs a body \`{ mutations: [...] }\`.`);
|
|
2891
|
+
const committed = await client.mutate(body.mutations, {
|
|
2892
|
+
returnDocuments: !1,
|
|
2893
|
+
returnFirst: !1,
|
|
2894
|
+
...tag
|
|
2895
|
+
}), images = /* @__PURE__ */ new Map();
|
|
2896
|
+
if (search.get("returnDocuments") === "true") {
|
|
2897
|
+
const ids = committed.results.map((result) => result.id), record = history.transactions(ids, () => !0).find((txn) => txn.id === committed.transactionId);
|
|
2898
|
+
for (const mutation of record?.mutations ?? []) {
|
|
2899
|
+
const document = "create" in mutation ? mutation.create : "createOrReplace" in mutation ? mutation.createOrReplace : void 0;
|
|
2900
|
+
document !== void 0 && images.set(document._id, document);
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
return {
|
|
2904
|
+
transactionId: committed.transactionId,
|
|
2905
|
+
results: committed.results.map((result) => {
|
|
2906
|
+
const document = images.get(result.id) ?? (search.get("returnDocuments") === "true" ? client.store().get(result.id) : void 0);
|
|
2907
|
+
return document !== void 0 ? { ...result, document } : result;
|
|
2908
|
+
})
|
|
2909
|
+
};
|
|
2910
|
+
} catch (error) {
|
|
2911
|
+
throw (error instanceof ClientError || error instanceof ServerError) && Object.assign(error.response, { method: sent.method, url: sent.url }), error;
|
|
2912
|
+
}
|
|
2913
|
+
}
|
|
2914
|
+
function storeQuery(sent, search, body) {
|
|
2915
|
+
if (sent.method === "POST") {
|
|
2916
|
+
const posted = body;
|
|
2917
|
+
if (typeof posted?.query != "string")
|
|
2918
|
+
throw fakeError(`request(): POST "${sent.path}" needs a body \`{ query, params? }\`.`);
|
|
2919
|
+
return { query: posted.query, params: posted.params ?? {} };
|
|
2920
|
+
}
|
|
2921
|
+
const query = search.get("query");
|
|
2922
|
+
if (query === null) throw fakeError(`request(): GET "${sent.path}" needs a \`query\` parameter.`);
|
|
2923
|
+
const params = Object.fromEntries(
|
|
2924
|
+
[...search].filter(([name]) => name.startsWith("$")).map(([name, value]) => [name.slice(1), JSON.parse(value)])
|
|
2925
|
+
);
|
|
2926
|
+
return { query, params };
|
|
2927
|
+
}
|
|
2928
|
+
function notAllowed(sent) {
|
|
2929
|
+
return fakeError(`request(): ${sent.method} "${sent.path}" is not a method this route takes.`);
|
|
2930
|
+
}
|
|
2931
|
+
function clientResources(registry) {
|
|
2932
|
+
return [...registry.values()].filter(
|
|
2933
|
+
(entry) => entry.resource.type !== "organization-store"
|
|
2934
|
+
);
|
|
2935
|
+
}
|
|
2388
2936
|
function ensureEntry(registry, resource) {
|
|
2389
2937
|
const key = registryKey(resource);
|
|
2390
2938
|
let entry = registry.get(key);
|
|
@@ -2404,6 +2952,15 @@ function seedEntry(registry, resource, documents) {
|
|
|
2404
2952
|
const entry = ensureEntry(registry, resource);
|
|
2405
2953
|
entry.store.seed(documents), entry.exists = !0;
|
|
2406
2954
|
}
|
|
2955
|
+
function seedFunctions(functions) {
|
|
2956
|
+
const registry = { functions: /* @__PURE__ */ new Map(), invocations: [] };
|
|
2957
|
+
for (const fn of functions) {
|
|
2958
|
+
if (registry.functions.has(fn.id))
|
|
2959
|
+
throw fakeError(`createTestClient(): \`functions\` lists id "${fn.id}" twice.`);
|
|
2960
|
+
registerFunction(registry, { fn, site: "createTestClient()" });
|
|
2961
|
+
}
|
|
2962
|
+
return registry;
|
|
2963
|
+
}
|
|
2407
2964
|
function seedOrganizationStores(options) {
|
|
2408
2965
|
const seeded = Object.entries(options.organizationStores ?? {}), unserved = seeded.find(([, status]) => status !== "provisioning" && status !== "active");
|
|
2409
2966
|
if (unserved !== void 0)
|
|
@@ -2428,6 +2985,7 @@ function createTestClient(options = {}) {
|
|
|
2428
2985
|
organizationId: options.organizationId,
|
|
2429
2986
|
projectFeatures: options.projectFeatures ?? {},
|
|
2430
2987
|
organizationStores: seedOrganizationStores(options),
|
|
2988
|
+
functions: seedFunctions(options.functions ?? []),
|
|
2431
2989
|
log: [],
|
|
2432
2990
|
stubs: /* @__PURE__ */ new Map(),
|
|
2433
2991
|
calls: [],
|
|
@@ -2475,6 +3033,19 @@ function createTestClient(options = {}) {
|
|
|
2475
3033
|
configuredPerspective: options.perspective
|
|
2476
3034
|
});
|
|
2477
3035
|
}
|
|
3036
|
+
function parseQuery(request, query, params) {
|
|
3037
|
+
try {
|
|
3038
|
+
const tree = parse(query, params ? { params } : void 0);
|
|
3039
|
+
return refuseUnsentParams({ request, query, params }), tree;
|
|
3040
|
+
} catch (error) {
|
|
3041
|
+
throw refuseUnsentParams({
|
|
3042
|
+
request,
|
|
3043
|
+
query,
|
|
3044
|
+
params,
|
|
3045
|
+
...error instanceof GroqSyntaxError ? { syntaxErrorAt: error.position } : {}
|
|
3046
|
+
}), error;
|
|
3047
|
+
}
|
|
3048
|
+
}
|
|
2478
3049
|
function dedupeIds(results) {
|
|
2479
3050
|
const seen = /* @__PURE__ */ new Set(), out = [];
|
|
2480
3051
|
for (const r of results)
|
|
@@ -2539,7 +3110,7 @@ function makeHandle(handleArgs) {
|
|
|
2539
3110
|
apiVersion,
|
|
2540
3111
|
useCdn,
|
|
2541
3112
|
configuredPerspective
|
|
2542
|
-
} = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = resource ?? datasetResource(projectId, dataset), activeAccess = () => {
|
|
3113
|
+
} = handleArgs, { registry } = backend, hasProjectId = handleArgs.hasProjectId || useProjectHostname && resource === void 0 || resource?.type === "dataset", { projectId, dataset } = resource?.type === "dataset" ? datasetParts(resource.id) : handleArgs, target = handleArgs.internalStore?.resource ?? resource ?? datasetResource(projectId, dataset), activeAccess = () => {
|
|
2543
3114
|
if (token === void 0) return accessControl;
|
|
2544
3115
|
const verified = internalToken(backend, token), identity = verified !== void 0 && "identity" in verified ? verified.identity : backend.identities.get(token);
|
|
2545
3116
|
if (verified !== void 0 && "refused" in verified)
|
|
@@ -2548,7 +3119,7 @@ function makeHandle(handleArgs) {
|
|
|
2548
3119
|
throw fakeError(`no identity is registered for token "${token}" (was it removed?).`);
|
|
2549
3120
|
return {
|
|
2550
3121
|
// Per-project records apply only where the resource lives in a project.
|
|
2551
|
-
currentUser:
|
|
3122
|
+
currentUser: storeCapabilitiesOf(target.type).identity === "project" ? projectUserOf(identity, projectId) : identity.user,
|
|
2552
3123
|
...identity.globalUser !== void 0 ? { globalUser: identity.globalUser } : {},
|
|
2553
3124
|
...identity.robot ? { robot: !0 } : {},
|
|
2554
3125
|
grants: identity.grants,
|
|
@@ -2568,8 +3139,8 @@ function makeHandle(handleArgs) {
|
|
|
2568
3139
|
}, internal = () => token === void 0 ? void 0 : internalToken(backend, token), refuseInternalToken = (request) => {
|
|
2569
3140
|
const check = internal();
|
|
2570
3141
|
if (check === void 0) return;
|
|
2571
|
-
const
|
|
2572
|
-
if (
|
|
3142
|
+
const refusal2 = internalTokenRefusal(request, check);
|
|
3143
|
+
if (refusal2 !== void 0) throw refusal2;
|
|
2573
3144
|
}, withSession = (request) => async (opts) => {
|
|
2574
3145
|
const sent = rawRequest(opts);
|
|
2575
3146
|
if (internal() !== void 0 && servedByProjectApi(sent.path) && sent.path !== ORGANIZATION_STORES_PATH)
|
|
@@ -2578,7 +3149,50 @@ function makeHandle(handleArgs) {
|
|
|
2578
3149
|
);
|
|
2579
3150
|
if (refuseSession2(sent), backend.outages.has("project-api") && servedByProjectApi(sent.path))
|
|
2580
3151
|
throw projectApiDown(sent);
|
|
2581
|
-
|
|
3152
|
+
const routed = activeAccess()?.aclPath === (opts.uri ?? opts.url) ? void 0 : matchWorkflowsStoreRoute({ path: sent.path, apiVersion });
|
|
3153
|
+
return routed !== void 0 ? serveWorkflowsStore(routed, sent, opts) : request(opts);
|
|
3154
|
+
}, serveWorkflowsStore = (routed, sent, opts) => {
|
|
3155
|
+
if (routed === "unrouted") throw noRouteMatched(sent);
|
|
3156
|
+
if (routed === "service")
|
|
3157
|
+
throw fakeError(
|
|
3158
|
+
`request(): ${sent.method} "${sent.path}" goes to the Workflows service, which the fake does not serve. Mount a Workflows service double for it.`
|
|
3159
|
+
);
|
|
3160
|
+
const store2 = routed.route === "read" ? activeStoreOf(routed.organizationId) : [...backend.organizationStores.values()].find(
|
|
3161
|
+
(one) => one.id === routed.storeId && one.status === "active"
|
|
3162
|
+
);
|
|
3163
|
+
if (store2 === void 0)
|
|
3164
|
+
throw storeNotFound(
|
|
3165
|
+
sent,
|
|
3166
|
+
routed.route === "read" ? `org:${routed.organizationId}` : routed.storeId
|
|
3167
|
+
);
|
|
3168
|
+
const servedActions = routed.route === "read" ? ["query", "doc"] : ["query", "doc", "mutate"];
|
|
3169
|
+
if (!servedActions.includes(routed.action))
|
|
3170
|
+
throw fakeError(
|
|
3171
|
+
`request(): "${sent.path}" is ${routed.action} on the organization store; the fake serves ${servedActions.join(", ")} there.`
|
|
3172
|
+
);
|
|
3173
|
+
const onStore = makeHandle({
|
|
3174
|
+
...handleArgs,
|
|
3175
|
+
resource: void 0,
|
|
3176
|
+
// Both routes are on the global API host, whatever host the caller's other requests go to.
|
|
3177
|
+
useProjectHostname: !1,
|
|
3178
|
+
perspective: "raw",
|
|
3179
|
+
configuredPerspective: void 0,
|
|
3180
|
+
internalStore: {
|
|
3181
|
+
resource: { type: "organization-store", id: store2.id },
|
|
3182
|
+
store: { id: store2.id, organizationId: store2.organizationId }
|
|
3183
|
+
}
|
|
3184
|
+
});
|
|
3185
|
+
return serveStoreAction({
|
|
3186
|
+
client: onStore,
|
|
3187
|
+
history: ensureEntry(registry, { type: "organization-store", id: store2.id }).history,
|
|
3188
|
+
action: routed.action,
|
|
3189
|
+
rest: routed.rest,
|
|
3190
|
+
sent,
|
|
3191
|
+
opts
|
|
3192
|
+
});
|
|
3193
|
+
}, activeStoreOf = (organizationId) => {
|
|
3194
|
+
const store2 = backend.organizationStores.get(organizationId);
|
|
3195
|
+
return store2?.status === "active" ? store2 : void 0;
|
|
2582
3196
|
}, admitToLake = (request) => {
|
|
2583
3197
|
if (refuseSession2(request), missingKey !== void 0) {
|
|
2584
3198
|
const parts = datasetParts(target.id);
|
|
@@ -2587,8 +3201,8 @@ function makeHandle(handleArgs) {
|
|
|
2587
3201
|
refuseInternalToken(request);
|
|
2588
3202
|
const access = activeAccess();
|
|
2589
3203
|
if (access === void 0) return;
|
|
2590
|
-
const
|
|
2591
|
-
if (
|
|
3204
|
+
const refusal2 = refusedToken(request, access.grants);
|
|
3205
|
+
if (refusal2 !== void 0) throw refusal2;
|
|
2592
3206
|
}, baseUrls = apiBaseUrls({
|
|
2593
3207
|
apiHost,
|
|
2594
3208
|
apiVersion,
|
|
@@ -2641,7 +3255,7 @@ function makeHandle(handleArgs) {
|
|
|
2641
3255
|
if (opts.query !== void 0 && "tag" in opts.query)
|
|
2642
3256
|
throw fakeError("request(): pass the request tag as `tag`, not in `query`.");
|
|
2643
3257
|
return platformRequest({
|
|
2644
|
-
method: "GET",
|
|
3258
|
+
method: opts.method?.toUpperCase() === "POST" ? "POST" : "GET",
|
|
2645
3259
|
uri: opts.uri ?? opts.url ?? "",
|
|
2646
3260
|
tag: opts.tag,
|
|
2647
3261
|
query: Object.entries(opts.query ?? {}).flatMap(
|
|
@@ -2658,7 +3272,7 @@ function makeHandle(handleArgs) {
|
|
|
2658
3272
|
...accessControl.access !== void 0 ? { access: accessControl.access } : {}
|
|
2659
3273
|
}
|
|
2660
3274
|
] : []
|
|
2661
|
-
], capabilities =
|
|
3275
|
+
], capabilities = storeCapabilitiesOf(target.type), targetLabel = capabilities.label(target.id), targetEntry = ensureEntry(registry, target), { store, history } = targetEntry, missingKey = (() => {
|
|
2662
3276
|
if (target.type !== "dataset") return;
|
|
2663
3277
|
const parts = datasetParts(target.id), key = `${parts.projectId}:${parts.dataset}`;
|
|
2664
3278
|
return backend.missingDatasets.has(key) ? key : void 0;
|
|
@@ -2697,6 +3311,7 @@ function makeHandle(handleArgs) {
|
|
|
2697
3311
|
projectId,
|
|
2698
3312
|
dataset,
|
|
2699
3313
|
...resource !== void 0 ? { resource } : {},
|
|
3314
|
+
...handleArgs.internalStore !== void 0 ? { organizationStore: { ...handleArgs.internalStore.store } } : {},
|
|
2700
3315
|
mutations,
|
|
2701
3316
|
...effectiveTag !== void 0 ? { tag: effectiveTag } : {}
|
|
2702
3317
|
});
|
|
@@ -2871,16 +3486,15 @@ function makeHandle(handleArgs) {
|
|
|
2871
3486
|
return applyPerspective(accessible, override ?? perspective);
|
|
2872
3487
|
}, client = {
|
|
2873
3488
|
fetch: async (query, params, opts) => {
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
)
|
|
2883
|
-
const start = Date.now(), tree = parse(query, params ? { params } : void 0), result = await (await evaluate(tree, {
|
|
3489
|
+
const request = queryRequest({
|
|
3490
|
+
query,
|
|
3491
|
+
params,
|
|
3492
|
+
tag: opts?.tag,
|
|
3493
|
+
perspective: opts?.perspective,
|
|
3494
|
+
returnQuery: opts?.filterResponse === !1 && opts.returnQuery !== !1
|
|
3495
|
+
});
|
|
3496
|
+
admitToLake(request);
|
|
3497
|
+
const start = Date.now(), tree = parseQuery(request, query, params), result = await (await evaluate(tree, {
|
|
2884
3498
|
dataset: await visibleDocs(opts?.perspective),
|
|
2885
3499
|
...params !== void 0 ? { params } : {}
|
|
2886
3500
|
})).get();
|
|
@@ -3078,6 +3692,7 @@ function makeHandle(handleArgs) {
|
|
|
3078
3692
|
makeRequestImpl({
|
|
3079
3693
|
getAccess: requireActiveAccess,
|
|
3080
3694
|
requestFor: rawRequest,
|
|
3695
|
+
projectId,
|
|
3081
3696
|
useProjectHostname: projectHosted,
|
|
3082
3697
|
organizationId: backend.organizationId,
|
|
3083
3698
|
listIdentities: members,
|
|
@@ -3105,7 +3720,19 @@ function makeHandle(handleArgs) {
|
|
|
3105
3720
|
identities: members,
|
|
3106
3721
|
// A dataset stands for its project, and every project exists in
|
|
3107
3722
|
// the fake, so a dataset handle still counts as before.
|
|
3108
|
-
resources: () =>
|
|
3723
|
+
resources: () => clientResources(registry).filter((e) => e.exists || e.resource.type === "dataset").map((e) => e.resource)
|
|
3724
|
+
},
|
|
3725
|
+
functions: {
|
|
3726
|
+
apiVersion,
|
|
3727
|
+
organizationId: backend.organizationId,
|
|
3728
|
+
registry: backend.functions,
|
|
3729
|
+
internalToken: () => internal() !== void 0,
|
|
3730
|
+
projectApiDown: () => backend.outages.has("project-api"),
|
|
3731
|
+
actorUser: () => {
|
|
3732
|
+
const access = requireActiveAccess();
|
|
3733
|
+
return access.globalUser ?? access.currentUser;
|
|
3734
|
+
},
|
|
3735
|
+
actorAccess: () => requireActiveAccess().access
|
|
3109
3736
|
}
|
|
3110
3737
|
})
|
|
3111
3738
|
)
|
|
@@ -3158,7 +3785,7 @@ function makeHandle(handleArgs) {
|
|
|
3158
3785
|
backend.concurrentEdits.set(editKey, (backend.concurrentEdits.get(editKey) ?? 0) + count);
|
|
3159
3786
|
},
|
|
3160
3787
|
datasets: () => [...registry.values()].filter((entry) => entry.resource.type === "dataset").map((entry) => datasetParts(entry.resource.id)),
|
|
3161
|
-
resources: () =>
|
|
3788
|
+
resources: () => clientResources(registry).map((entry) => ({ ...entry.resource })),
|
|
3162
3789
|
stub: (name, handler) => {
|
|
3163
3790
|
backend.stubs.set(name, handler);
|
|
3164
3791
|
},
|
|
@@ -3178,6 +3805,17 @@ function makeHandle(handleArgs) {
|
|
|
3178
3805
|
backend.outages.add(component);
|
|
3179
3806
|
},
|
|
3180
3807
|
completeOrganizationStoreProvisioning: (organizationId) => completeProvisioning(backend.organizationStores, organizationId),
|
|
3808
|
+
organizationStore: (organizationId) => {
|
|
3809
|
+
const organizationStore = backend.organizationStores.get(organizationId);
|
|
3810
|
+
if (organizationStore === void 0)
|
|
3811
|
+
throw fakeError(
|
|
3812
|
+
`organizationStore(): organization "${organizationId}" has no store. Seed createTestClient({ organizationStores }), or look it up with GET /internal/organization-stores first.`
|
|
3813
|
+
);
|
|
3814
|
+
return ensureEntry(registry, { type: "organization-store", id: organizationStore.id }).store;
|
|
3815
|
+
},
|
|
3816
|
+
addFunction: (fn) => registerFunction(backend.functions, { fn, site: "addFunction()" }),
|
|
3817
|
+
removeFunction: (id) => unregisterFunction(backend.functions, id),
|
|
3818
|
+
functionInvocations: () => structuredClone(backend.functions.invocations),
|
|
3181
3819
|
mutations: () => backend.log.flatMap((entry) => entry.mutations),
|
|
3182
3820
|
transactions: () => [...backend.log],
|
|
3183
3821
|
clearLog: () => {
|
|
@@ -3205,7 +3843,7 @@ function makeHandle(handleArgs) {
|
|
|
3205
3843
|
"error" in outcome ? rec.error = outcome.error : rec.result = outcome.result;
|
|
3206
3844
|
};
|
|
3207
3845
|
},
|
|
3208
|
-
recorded: RECORDED_METHODS
|
|
3846
|
+
recorded: handleArgs.internalStore === void 0 ? RECORDED_METHODS : /* @__PURE__ */ new Set()
|
|
3209
3847
|
});
|
|
3210
3848
|
}
|
|
3211
3849
|
export {
|