@waffo/pancake-cli 0.0.0-stage → 0.0.1-rc.2
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/CHANGELOG.md +49 -0
- package/CONTRIBUTING.md +38 -0
- package/LICENSE +21 -0
- package/README.md +230 -2
- package/SECURITY.md +23 -0
- package/SKILL.md +110 -0
- package/dist/adapters/browser-login.js +210 -0
- package/dist/adapters/config.js +180 -0
- package/dist/adapters/files.js +222 -0
- package/dist/adapters/loopback-forward.js +33 -0
- package/dist/adapters/operations.js +89 -0
- package/dist/adapters/pancake/client.js +235 -0
- package/dist/adapters/pancake/conflict-error.js +18 -0
- package/dist/adapters/pancake/graphql-errors.js +41 -0
- package/dist/adapters/pancake/http-error-reason.js +12 -0
- package/dist/adapters/pancake/queries.js +9 -0
- package/dist/adapters/pancake/safe-reason.js +23 -0
- package/dist/adapters/system-process.js +12 -0
- package/dist/application/action-auth.js +7 -0
- package/dist/application/action-result.js +40 -0
- package/dist/application/api-actions.js +80 -0
- package/dist/application/api-reads.js +56 -0
- package/dist/application/auth-context.js +34 -0
- package/dist/application/auth.js +115 -0
- package/dist/application/confirmation.js +14 -0
- package/dist/application/diagnostics.js +48 -0
- package/dist/application/dispatch.js +109 -0
- package/dist/application/idempotency.js +8 -0
- package/dist/application/listen.js +147 -0
- package/dist/application/local.js +35 -0
- package/dist/application/product-verification.js +96 -0
- package/dist/application/products.js +70 -0
- package/dist/application/queries.js +26 -0
- package/dist/application/read-handlers.js +30 -0
- package/dist/application/read-operation.js +30 -0
- package/dist/application/webhooks.js +56 -0
- package/dist/application/write-operation.js +26 -0
- package/dist/cli/guidance.js +29 -0
- package/dist/cli/human-output.js +44 -0
- package/dist/cli/input.js +62 -0
- package/dist/cli/listen-output.js +10 -0
- package/dist/cli/login-prompt.js +66 -0
- package/dist/cli/output.js +43 -0
- package/dist/cli/run.js +128 -0
- package/dist/commands/action-definitions.js +100 -0
- package/dist/commands/action-previews.js +12 -0
- package/dist/commands/action-schemas.js +47 -0
- package/dist/commands/action-values.js +11 -0
- package/dist/commands/api-coverage.js +25 -0
- package/dist/commands/checkout-action-schema.js +25 -0
- package/dist/commands/discount-definitions.js +47 -0
- package/dist/commands/discount-preview.js +17 -0
- package/dist/commands/discount-schemas.js +39 -0
- package/dist/commands/discount-validation.js +17 -0
- package/dist/commands/listen-input.js +12 -0
- package/dist/commands/operation-impact.js +16 -0
- package/dist/commands/product-action-schemas.js +26 -0
- package/dist/commands/product-preview.js +5 -0
- package/dist/commands/read-definitions.js +92 -0
- package/dist/commands/read-query.js +49 -0
- package/dist/commands/read-schemas.js +17 -0
- package/dist/commands/registry.js +45 -0
- package/dist/commands/schemas.js +94 -0
- package/dist/commands/webhook-preview.js +3 -0
- package/dist/contracts/action-routes.js +7 -0
- package/dist/contracts/command.js +1 -0
- package/dist/contracts/errors.js +26 -0
- package/dist/contracts/impact.js +1 -0
- package/dist/contracts/listen.js +1 -0
- package/dist/contracts/loopback-target.js +14 -0
- package/dist/contracts/types.js +1 -0
- package/dist/index.js +20 -0
- package/docs/api-coverage.md +154 -0
- package/docs/usage.md +458 -0
- package/package.json +60 -4
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { storePreview, productActionPreview, groupPreview, checkoutPreview, subscriptionPreview, refundPreview, sessionPreview, recipientPreview, contentPreview } from "./action-previews.js";
|
|
2
|
+
import { discountActionSpecs } from "./discount-definitions.js";
|
|
3
|
+
import { contentScanSchema, groupSchemas, recipientSchemas, refundSchemas, sessionSchema, storeSchemas, subscriptionCancelSchema } from "./action-schemas.js";
|
|
4
|
+
import { checkoutSchema } from "./checkout-action-schema.js";
|
|
5
|
+
import { productPublishSchema, productStatusSchema, productUpdateSchema } from "./product-action-schemas.js";
|
|
6
|
+
const options = [
|
|
7
|
+
['--dry-run', 'Validate and preview offline without sending a request'],
|
|
8
|
+
['--idempotency-key <key>', 'Unique operation key; used keys are never automatically replayed'],
|
|
9
|
+
['--output <path>', 'Export the response to a new private file; required for checkout and session results'],
|
|
10
|
+
];
|
|
11
|
+
const docs = (path) => `https://docs.waffo.ai/api-reference/endpoints/${path}`;
|
|
12
|
+
const keyedResponse = (key) => (data) => {
|
|
13
|
+
const value = data[key];
|
|
14
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) && typeof value.id === 'string' && value.id !== '';
|
|
15
|
+
};
|
|
16
|
+
const hasStrings = (data, keys) => keys.every(key => typeof data[key] === 'string' && data[key] !== '');
|
|
17
|
+
function definition(id, description, schema, product = false, effect = 'write') {
|
|
18
|
+
return {
|
|
19
|
+
id, path: id.replace('.', ' '), description, schema, effect, file: true,
|
|
20
|
+
options: [...(product ? [['--type <type>', 'onetime or subscription (required)']] : []), ...options],
|
|
21
|
+
example: `pancake ${id.replace('.', ' ')}${product ? ' --type onetime' : ''} --file input.json --dry-run --json`,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export const actionSpecs = [
|
|
25
|
+
...discountActionSpecs,
|
|
26
|
+
...['create', 'update', 'delete'].map(action => ({
|
|
27
|
+
definition: definition(`stores.${action}`, `${action} a store; requires --yes${action === 'delete' ? '; soft-deletes the store and makes it inaccessible' : ''}`, storeSchemas[action]),
|
|
28
|
+
endpoint: `/v1/actions/store/${action}-store`, documentation: [docs(`stores/${action}-store`)],
|
|
29
|
+
authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: storePreview,
|
|
30
|
+
targetResourceId: (input) => action === 'create' ? undefined : input.id,
|
|
31
|
+
resultResourceId: (data) => data.store.id,
|
|
32
|
+
responseKey: 'store', validateResponse: keyedResponse('store'),
|
|
33
|
+
})),
|
|
34
|
+
...[
|
|
35
|
+
['update', 'update-product', productUpdateSchema, 'Update product content; prices replaces all currencies (omitted currencies are removed); existing purchases keep their version; taxIncluded is unsupported'],
|
|
36
|
+
['publish', 'publish-product', productPublishSchema, 'Publish a product TEST→PRODUCTION for the first time'],
|
|
37
|
+
['set-status', 'update-status', productStatusSchema, 'Set product checkout availability without canceling existing purchases'],
|
|
38
|
+
].map(([action, endpoint, schema, description]) => ({
|
|
39
|
+
definition: definition(`products.${action}`, `${description}; requires --yes`, schema, true),
|
|
40
|
+
endpoint: { onetime: `/v1/actions/onetime-product/${endpoint}`, subscription: `/v1/actions/subscription-product/${endpoint}` },
|
|
41
|
+
documentation: [docs(`onetime-products/${endpoint}`), docs(`subscription-products/${endpoint}`)],
|
|
42
|
+
authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: productActionPreview,
|
|
43
|
+
targetResourceId: (input) => input.id,
|
|
44
|
+
resultResourceId: (data) => data.product.id,
|
|
45
|
+
responseKey: 'product', validateResponse: keyedResponse('product'),
|
|
46
|
+
})),
|
|
47
|
+
...['create', 'update', 'delete', 'publish'].map(action => ({
|
|
48
|
+
definition: definition(`groups.${action}`, `${action} a subscription product group; requires --yes${action === 'delete' ? '; permanently deletes only the group' : ''}${action === 'publish' ? '; copies TEST→PRODUCTION using upsert' : ''}`, groupSchemas[action]),
|
|
49
|
+
endpoint: `/v1/actions/subscription-product-group/${action}-group`, documentation: [docs(`subscription-products/${action}-group`)],
|
|
50
|
+
authentication: 'merchant-session-or-rsa',
|
|
51
|
+
verification: action === 'delete' || action === 'publish' ? 'acknowledgement_only' : 'response_only', previewInput: groupPreview,
|
|
52
|
+
targetResourceId: (input) => action === 'create' ? undefined : input.id,
|
|
53
|
+
resultResourceId: (data, input) => action === 'delete' || action === 'publish' ? input.id : data.group.id,
|
|
54
|
+
...(action === 'create' || action === 'update' ? { responseKey: 'group', validateResponse: keyedResponse('group') } : {}),
|
|
55
|
+
})),
|
|
56
|
+
{
|
|
57
|
+
definition: definition('checkout.create', 'Create a checkout or plan-change session; requires --yes and --output for the private checkout link', checkoutSchema),
|
|
58
|
+
endpoint: '/v1/actions/checkout/create-session', documentation: [docs('orders/create-checkout-session')], sensitiveOutput: true,
|
|
59
|
+
authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: checkoutPreview,
|
|
60
|
+
targetResourceId: input => input.productId, resultResourceId: data => data.sessionId,
|
|
61
|
+
validateResponse: data => hasStrings(data, ['sessionId', 'checkoutUrl', 'expiresAt']),
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
definition: definition('subscriptions.cancel', 'Request subscription cancellation; timing follows its current state; requires --yes', subscriptionCancelSchema),
|
|
65
|
+
endpoint: '/v1/actions/subscription-order/cancel-order', documentation: [docs('subscriptions/cancel-subscription')],
|
|
66
|
+
authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: subscriptionPreview,
|
|
67
|
+
targetResourceId: input => input.orderId, resultResourceId: data => data.orderId,
|
|
68
|
+
validateResponse: data => hasStrings(data, ['orderId', 'status']) && ['canceling', 'canceled'].includes(data.status),
|
|
69
|
+
},
|
|
70
|
+
...['create', 'resubmit'].map(action => ({
|
|
71
|
+
definition: definition(`refunds.${action}`, `${action} a refund ticket; this does not confirm completed repayment; requires --yes`, refundSchemas[action]),
|
|
72
|
+
endpoint: `/v1/actions/refund-ticket/${action}-ticket`, documentation: [docs(`refunds/${action}-refund-ticket`)],
|
|
73
|
+
authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: refundPreview,
|
|
74
|
+
targetResourceId: (input) => (action === 'create' ? input.paymentId : input.ticketId),
|
|
75
|
+
resultResourceId: (data) => data.ticket.id,
|
|
76
|
+
responseKey: 'ticket', validateResponse: keyedResponse('ticket'),
|
|
77
|
+
})),
|
|
78
|
+
{
|
|
79
|
+
definition: definition('sessions.create', 'Issue a customer token using RSA login; requires --yes and --output', sessionSchema),
|
|
80
|
+
endpoint: '/v1/actions/auth/issue-session-token', documentation: [docs('auth/issue-session-token')], sensitiveOutput: true,
|
|
81
|
+
authentication: 'merchant-rsa', verification: 'response_only', previewInput: sessionPreview,
|
|
82
|
+
targetResourceId: input => input.productId, resultResourceId: () => undefined,
|
|
83
|
+
validateResponse: data => hasStrings(data, ['token', 'expiresAt']) && (data.portalUrl === undefined || hasStrings(data, ['portalUrl'])),
|
|
84
|
+
},
|
|
85
|
+
...['add', 'update', 'remove'].map(action => ({
|
|
86
|
+
definition: definition(`recipients.${action}`, `${action} a store notification recipient; requires --yes${action === 'remove' ? '; removing the last recipient silences merchant notifications' : ''}`, recipientSchemas[action]),
|
|
87
|
+
endpoint: `/v1/actions/store-notification-recipient/${action}-recipient`, documentation: [docs(`notification-recipients/${action}-recipient`)],
|
|
88
|
+
authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: recipientPreview,
|
|
89
|
+
targetResourceId: (input) => action === 'add' ? undefined : input.recipientId,
|
|
90
|
+
resultResourceId: (data) => action === 'remove' ? data.recipientId : data.recipient.id,
|
|
91
|
+
...(action === 'remove' ? { validateResponse: (data) => hasStrings(data, ['recipientId']) && data.removed === true } : { responseKey: 'recipient', validateResponse: keyedResponse('recipient') }),
|
|
92
|
+
})),
|
|
93
|
+
{
|
|
94
|
+
definition: definition('content.scan', 'Check prompt safety; requires --yes', contentScanSchema, false, 'read'),
|
|
95
|
+
endpoint: '/v1/actions/verification/scan-prompt', documentation: [docs('content-safety/scan-prompt')],
|
|
96
|
+
authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: contentPreview,
|
|
97
|
+
targetResourceId: () => undefined, resultResourceId: () => undefined,
|
|
98
|
+
validateResponse: data => hasStrings(data, ['action', 'reasonCode', 'requestId', 'semanticStatus']) && ['allow', 'review', 'block'].includes(data.action) && Array.isArray(data.matchedCategories) && data.matchedCategories.every(value => typeof value === 'string'),
|
|
99
|
+
},
|
|
100
|
+
];
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export function previewFields(input, visible) {
|
|
2
|
+
return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, visible.includes(key) ? value : '[redacted]']));
|
|
3
|
+
}
|
|
4
|
+
export const storePreview = (input) => previewFields(input, ['id', 'status']);
|
|
5
|
+
export const productActionPreview = (input) => previewFields(input, ['type', 'id', 'status', 'prices', 'billingPeriod']);
|
|
6
|
+
export const groupPreview = (input) => previewFields(input, ['id', 'storeId']);
|
|
7
|
+
export const checkoutPreview = (input) => previewFields(input, ['productId', 'currency', 'changeAmount', 'changeCreditAmount', 'originOrderId']);
|
|
8
|
+
export const subscriptionPreview = (input) => previewFields(input, ['orderId']);
|
|
9
|
+
export const refundPreview = (input) => previewFields(input, ['paymentId', 'ticketId', 'requestedAmount']);
|
|
10
|
+
export const sessionPreview = (input) => previewFields(input, ['storeId', 'productId']);
|
|
11
|
+
export const recipientPreview = (input) => previewFields(input, ['storeId', 'recipientId']);
|
|
12
|
+
export const contentPreview = (input) => previewFields(input, []);
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { objectSchema, storeId, string, uuid } from "./schemas.js";
|
|
2
|
+
import { currency, notificationFlags, orderId, positiveAmount, productId } from "./action-values.js";
|
|
3
|
+
const nullable = (schema) => ({ anyOf: [schema, { type: 'null' }] });
|
|
4
|
+
const storeName = { type: 'string', minLength: 1, maxLength: 48, allOf: [{ pattern: '\\S' }, { not: { pattern: '[\\u0000-\\u001f\\u007f]' } }] };
|
|
5
|
+
const checkoutTheme = objectSchema({
|
|
6
|
+
checkoutLogo: nullable({ type: 'string' }), checkoutColorPrimary: nullable({ type: 'string' }),
|
|
7
|
+
checkoutColorBackground: nullable({ type: 'string' }), checkoutColorCard: nullable({ type: 'string' }),
|
|
8
|
+
checkoutColorText: nullable({ type: 'string' }), checkoutBorderRadius: nullable({ type: 'string' }),
|
|
9
|
+
});
|
|
10
|
+
export const storeSchemas = {
|
|
11
|
+
create: objectSchema({ name: storeName }, ['name']),
|
|
12
|
+
update: objectSchema({
|
|
13
|
+
id: storeId, name: storeName, status: { enum: ['active', 'inactive', 'suspended'] }, logo: nullable({ type: 'string' }),
|
|
14
|
+
notificationSettings: nullable(objectSchema(Object.fromEntries(Object.keys({ ...notificationFlags, emailUpcomingCharge: true, emailTrialEnding: true }).map(key => [key, nullable({ type: 'boolean' })])))),
|
|
15
|
+
checkoutSettings: nullable(objectSchema({ defaultDarkMode: nullable({ type: 'boolean' }), light: nullable(checkoutTheme), dark: nullable(checkoutTheme) })),
|
|
16
|
+
}, ['id']),
|
|
17
|
+
delete: objectSchema({ id: storeId }, ['id']),
|
|
18
|
+
};
|
|
19
|
+
const groupFields = {
|
|
20
|
+
name: string, description: { type: 'string' },
|
|
21
|
+
rules: nullable(objectSchema({ sharedTrial: { type: 'boolean' }, selfServicePlanChange: { type: 'boolean' } })),
|
|
22
|
+
productIds: { type: 'array', items: productId },
|
|
23
|
+
};
|
|
24
|
+
export const groupSchemas = {
|
|
25
|
+
create: objectSchema({ storeId, ...groupFields }, ['storeId', 'name']),
|
|
26
|
+
update: objectSchema({ id: uuid, ...groupFields }, ['id']),
|
|
27
|
+
delete: objectSchema({ id: uuid }, ['id']),
|
|
28
|
+
publish: objectSchema({ id: uuid }, ['id']),
|
|
29
|
+
};
|
|
30
|
+
const refundFields = { reason: string, requestedAmount: objectSchema({ amount: positiveAmount, currency }, ['amount', 'currency']) };
|
|
31
|
+
export const refundSchemas = {
|
|
32
|
+
create: objectSchema({ paymentId: { type: 'string', pattern: '^PAY_[A-Za-z0-9]+$' }, ...refundFields, refundTicketMerchantExternalId: { type: 'string', maxLength: 128 } }, ['paymentId', 'reason', 'requestedAmount']),
|
|
33
|
+
resubmit: objectSchema({ ticketId: { type: 'string', pattern: '^TKT_[A-Za-z0-9]+$' }, ...refundFields }, ['ticketId', 'reason', 'requestedAmount']),
|
|
34
|
+
};
|
|
35
|
+
export const sessionSchema = {
|
|
36
|
+
...objectSchema({ storeId, productId, buyerIdentity: string, purpose: { const: 'portal' } }, ['buyerIdentity']),
|
|
37
|
+
anyOf: [{ required: ['storeId'] }, { required: ['productId'] }],
|
|
38
|
+
if: { required: ['purpose'], properties: { purpose: { const: 'portal' } } },
|
|
39
|
+
then: { required: ['storeId'], not: { required: ['productId'] } },
|
|
40
|
+
};
|
|
41
|
+
export const recipientSchemas = {
|
|
42
|
+
add: objectSchema({ storeId, email: string }, ['storeId', 'email']),
|
|
43
|
+
update: objectSchema({ storeId, recipientId: uuid, preferences: objectSchema(notificationFlags) }, ['storeId', 'recipientId', 'preferences']),
|
|
44
|
+
remove: objectSchema({ storeId, recipientId: uuid }, ['storeId', 'recipientId']),
|
|
45
|
+
};
|
|
46
|
+
export const subscriptionCancelSchema = objectSchema({ orderId }, ['orderId']);
|
|
47
|
+
export const contentScanSchema = objectSchema({ prompt: { type: 'string', minLength: 1, maxLength: 10000 }, locale: { enum: ['ja', 'en', 'zh'] }, semantic: { enum: ['off', 'shadow', 'enforce'] } }, ['prompt']);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const productId = { type: 'string', pattern: '^PROD_[A-Za-z0-9]+$' };
|
|
2
|
+
export const orderId = { type: 'string', pattern: '^ORD_[A-Za-z0-9]+$' };
|
|
3
|
+
export const amount = { type: 'string', pattern: '^\\d+(\\.\\d+)?$' };
|
|
4
|
+
export const positiveAmount = { ...amount, pattern: '^(?=.*[1-9])\\d+(\\.\\d+)?$' };
|
|
5
|
+
export const currency = { type: 'string', pattern: '^[A-Z]{3}$' };
|
|
6
|
+
export const taxCategory = { enum: ['digital_goods', 'saas', 'software', 'ebook', 'online_course', 'consulting', 'professional_service'] };
|
|
7
|
+
export const notificationFlags = Object.fromEntries([
|
|
8
|
+
'notifyNewOrders', 'notifyNewSubscriptions', 'notifySubscriptionCanceled', 'notifySubscriptionEnded',
|
|
9
|
+
'notifySubscriptionPastDue', 'notifySubscriptionRenewed', 'notifySubscriptionUncanceled',
|
|
10
|
+
'notifySubscriptionPlanChanged', 'notifyChargeback', 'notifyRefundSucceeded',
|
|
11
|
+
].map(key => [key, { type: 'boolean' }]));
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { productCreateEndpoint, webhookEndpoint } from "../contracts/action-routes.js";
|
|
2
|
+
import { actionSpecs } from "./action-definitions.js";
|
|
3
|
+
import { readSpecs } from "./read-definitions.js";
|
|
4
|
+
export function commandApi(id) {
|
|
5
|
+
if (id === 'listen')
|
|
6
|
+
return { method: 'POST', endpoints: ['/v1/graphql', ...['start', 'poll', 'ack', 'stop'].map(action => `/v1/actions/notification/cli-listen-${action}`)], authentication: 'merchant-session only', targetEnvironment: 'test by default; --live for prod', temporarySessionTtlSeconds: 90 };
|
|
7
|
+
const action = actionSpecs.find(spec => spec.definition.id === id);
|
|
8
|
+
if (action)
|
|
9
|
+
return { method: 'POST', endpoints: typeof action.endpoint === 'string' ? [action.endpoint] : Object.values(action.endpoint), authentication: action.authentication === 'merchant-rsa' ? 'merchant-rsa' : 'merchant-session or merchant-rsa; server route permissions apply',
|
|
10
|
+
confirmationRequired: true, privateOutputRequired: action.sensitiveOutput ?? false,
|
|
11
|
+
targetEnvironment: id.endsWith('.publish') ? 'prod' : 'credential-dependent-unverified',
|
|
12
|
+
verification: action.verification, documentation: action.documentation };
|
|
13
|
+
const read = readSpecs.find(spec => spec.definition.id === id);
|
|
14
|
+
if (read)
|
|
15
|
+
return { method: 'POST', endpoints: ['/v1/graphql'], authentication: 'merchant-session or merchant-rsa; server route permissions apply', privateOutputRequired: read.sensitiveOutput ?? false, documentation: read.documentation };
|
|
16
|
+
if (id === 'products.create')
|
|
17
|
+
return { method: 'POST', endpoints: [productCreateEndpoint('onetime'), productCreateEndpoint('subscription')], authentication: 'merchant-session or merchant-rsa; server route permissions apply', verification: 'read_back' };
|
|
18
|
+
if (['webhook.add', 'webhook.update', 'webhook.remove'].includes(id))
|
|
19
|
+
return { method: 'POST', endpoints: [webhookEndpoint(id.split('.')[1])], authentication: 'merchant-session or merchant-rsa; server route permissions apply', scope: 'test-webhook-resources-only', verification: id === 'webhook.remove' ? 'read_back' : 'conditional', ...(id === 'webhook.remove' ? {} : { verificationPolicy: { default: 'read_back', browserSecretWrite: 'response_only' } }) };
|
|
20
|
+
if (id === 'login')
|
|
21
|
+
return { method: 'POST', endpoints: ['/v1/actions/auth/cli-device-start', '/v1/actions/auth/cli-device-token', '/v1/actions/auth/cli-device-complete', '/v1/graphql'], authentication: 'browser device authorization then merchant-session; explicit merchant-rsa supported' };
|
|
22
|
+
if (['env', 'whoami', 'doctor', 'stores.list', 'products.get', 'webhook.list'].includes(id))
|
|
23
|
+
return { method: 'POST', endpoints: ['/v1/graphql'], authentication: 'merchant-session or merchant-rsa; server route permissions apply' };
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { objectSchema, string } from "./schemas.js";
|
|
2
|
+
import { amount, currency, orderId, productId, taxCategory } from "./action-values.js";
|
|
3
|
+
const paymentMethods = { type: 'array', items: { enum: ['card', 'applepay', 'googlepay', 'wechat'] } };
|
|
4
|
+
export const checkoutSchema = {
|
|
5
|
+
...objectSchema({
|
|
6
|
+
productId, currency,
|
|
7
|
+
priceSnapshot: objectSchema({ amount, taxIncluded: { type: 'boolean' }, taxCategory }, ['amount', 'taxCategory']),
|
|
8
|
+
withTrial: { type: 'boolean' }, buyerEmail: string,
|
|
9
|
+
billingDetail: objectSchema({
|
|
10
|
+
country: { type: 'string', pattern: '^[A-Z]{2}$' }, isBusiness: { type: 'boolean' },
|
|
11
|
+
postcode: { type: 'string' }, state: { type: 'string' }, businessName: { type: 'string' }, taxId: { type: 'string' },
|
|
12
|
+
}, ['country', 'isBusiness']),
|
|
13
|
+
successUrl: { type: 'string', format: 'https-url' }, expiresInSeconds: { type: 'number' },
|
|
14
|
+
darkMode: { type: 'boolean' }, metadata: { type: 'object', additionalProperties: true },
|
|
15
|
+
orderMerchantExternalId: { type: 'string', minLength: 1, maxLength: 128, pattern: '\\S' },
|
|
16
|
+
language: { enum: ['en', 'pt-BR', 'es-MX', 'id-ID', 'vi-VN', 'ru-RU', 'en-KE', 'es-PE', 'es-CO', 'es-CL', 'zh-Hant-TW', 'zh-Hant-HK', 'th-TH', 'ja-JP', 'en-NG', 'ko-KR', 'en-HK', 'zh-Hans-HK', 'pl-PL', 'tr-TR', 'zh-Hans', 'ms-MY'] },
|
|
17
|
+
includePaymentMethods: paymentMethods, excludePaymentMethods: paymentMethods,
|
|
18
|
+
originOrderId: orderId, changeTiming: { enum: ['immediate', 'next_period'] }, changeAmount: amount, changeCreditAmount: amount,
|
|
19
|
+
}, ['productId', 'currency']),
|
|
20
|
+
dependencies: { changeTiming: ['originOrderId'], changeAmount: ['originOrderId'], changeCreditAmount: ['originOrderId'] },
|
|
21
|
+
allOf: [
|
|
22
|
+
{ not: { required: ['includePaymentMethods', 'excludePaymentMethods'] } },
|
|
23
|
+
{ not: { required: ['changeAmount', 'changeCreditAmount'] } },
|
|
24
|
+
],
|
|
25
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { couponPreview, promotionCodePreview } from "./discount-preview.js";
|
|
2
|
+
import { couponId, couponListSchema, discountSchemas, promotionListSchema } from "./discount-schemas.js";
|
|
3
|
+
import { objectSchema } from "./schemas.js";
|
|
4
|
+
import { selection } from "./read-query.js";
|
|
5
|
+
const documentation = ['https://github.com/waffo-com/waffo-pancake-cli/blob/main/docs/usage.md#discounts'];
|
|
6
|
+
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
7
|
+
const entity = (value, prefix) => object(value) && typeof value.id === 'string' && new RegExp(`^${prefix}_[A-Za-z0-9]{22}$`).test(value.id) && typeof value.status === 'string' && (prefix === 'CPN' ? ['active', 'inactive', 'failed'] : ['active', 'inactive']).includes(value.status);
|
|
8
|
+
function publicEntity(value) {
|
|
9
|
+
const result = Object.fromEntries(['id', 'storeId', 'couponId', 'name', 'code', 'status', 'batchId'].filter(key => ['string', 'number', 'boolean'].includes(typeof value[key])).map(key => [key, value[key]]));
|
|
10
|
+
if (Array.isArray(value.promotionCodes))
|
|
11
|
+
result.promotionCodes = value.promotionCodes.map(item => publicEntity(item));
|
|
12
|
+
return result;
|
|
13
|
+
}
|
|
14
|
+
export const discountActionSpecs = Object.entries(discountSchemas).map(([id, schema]) => {
|
|
15
|
+
const [resource, action] = id.split('.');
|
|
16
|
+
const coupon = resource === 'coupons';
|
|
17
|
+
const batch = action === 'generate';
|
|
18
|
+
const key = coupon ? 'coupon' : 'promotionCode';
|
|
19
|
+
return {
|
|
20
|
+
definition: { id, path: id.replace('.', ' '), description: `${action} ${resource}; requires --yes${action === 'deactivate' ? '; permanent deactivation' : ''}${id === 'coupons.update' ? '; name only' : ''}`, effect: 'write', file: true, schema,
|
|
21
|
+
options: [['--dry-run', 'Validate and preview offline'], ['--idempotency-key <key>', 'Unique operation key; no automatic replay'], ['--output <path>', 'Export the complete response to a new private file']], example: `pancake ${id.replace('.', ' ')} --file input.json --dry-run --json` },
|
|
22
|
+
endpoint: `/v1/actions/${coupon ? 'coupon' : 'promotion-code'}/${action}-${coupon ? 'coupon' : batch ? 'promotion-codes' : 'promotion-code'}`,
|
|
23
|
+
documentation,
|
|
24
|
+
authentication: 'merchant-session-or-rsa', verification: 'response_only', previewInput: coupon ? couponPreview : promotionCodePreview,
|
|
25
|
+
targetResourceId: input => coupon ? action === 'create' ? undefined : input.id : action === 'deactivate' ? input.id : input.couponId,
|
|
26
|
+
resultResourceId: data => batch ? data.batchId : data[key].id,
|
|
27
|
+
...(batch ? {} : { responseKey: key }),
|
|
28
|
+
validateResponse: data => batch
|
|
29
|
+
? typeof data.batchId === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(data.batchId) && Array.isArray(data.promotionCodes) && data.promotionCodes.length > 0 && data.promotionCodes.length <= 500 && data.promotionCodes.every(value => entity(value, 'PMC') && typeof value.code === 'string')
|
|
30
|
+
: entity(data[key], coupon ? 'CPN' : 'PMC') && (!coupon || !object(data[key]) || data[key].promotionCodes === undefined || (Array.isArray(data[key].promotionCodes) && data[key].promotionCodes.every(value => entity(value, 'PMC') && typeof value.code === 'string'))) && (action === 'deactivate' ? data[key].status === 'inactive' : typeof data[key].code === 'string'),
|
|
31
|
+
projectResponse: data => batch ? { batchId: data.batchId, promotionCodes: data.promotionCodes.map(publicEntity) } : { [key]: publicEntity(data[key]) },
|
|
32
|
+
};
|
|
33
|
+
});
|
|
34
|
+
const fields = (...names) => Object.fromEntries(names.map(name => [name, name]));
|
|
35
|
+
const couponFields = { ...fields('id', 'storeId', 'name', 'code', 'status', 'redeemable', 'notRedeemableReason', 'discountType', 'percentOff', 'duration', 'durationInPeriods', 'productIds', 'maxRedemptions', 'redeemBy', 'timesRedeemed', 'promotionCodesCount', 'createdAt', 'updatedAt'), amountOff: 'amountOff { amount currency display }' };
|
|
36
|
+
const promotionFields = { ...fields('id', 'couponId', 'code', 'status', 'batchId', 'timesRedeemed', 'createdAt'), restrictions: 'restrictions { perCustomerLimit maxRedemptions expiresAt minimumAmount { amount currency display } }' };
|
|
37
|
+
const preview = ['--dry-run', 'Validate and preview offline'];
|
|
38
|
+
const fieldOption = ['--fields <names>', 'Comma-separated documented resource fields'];
|
|
39
|
+
export const discountReadSpecs = [
|
|
40
|
+
...[['coupons', 'coupons', 'storeId', 'CouponFilter', couponListSchema, couponFields], ['promotion-codes', 'promotionCodes', 'couponId', 'PromotionCodeFilter', promotionListSchema, promotionFields]].map(([id, root, scope, filter, schema, resourceFields]) => ({
|
|
41
|
+
scalarListFields: id === 'coupons' ? ['productIds'] : [],
|
|
42
|
+
definition: { id: `${id}.list`, path: `${id} list`, effect: 'read', description: `Read one page of ${id}; customer emails are omitted`, file: true, schema, options: [['--limit <number>', 'Page size, 1–100 (default 20)'], ['--offset <number>', 'Zero-based offset'], fieldOption, preview], example: `pancake ${id} list --file input.json --json` }, documentation,
|
|
43
|
+
request: (input, options) => ({ query: `query CliDiscounts($scope: String!, $limit: Int!, $offset: Int!, $filter: ${filter}) { items: ${root}(${scope}: $scope, limit: $limit, offset: $offset, filter: $filter) { ${selection(resourceFields, options.fields)} } }`, variables: { scope: input[scope], limit: options.limit ?? 20, offset: options.offset ?? 0, filter: input.filter ?? {} } }),
|
|
44
|
+
})),
|
|
45
|
+
{ scalarListFields: ['productIds'], definition: { id: 'coupons.get', path: 'coupons get', effect: 'read', argument: 'id', description: 'Get a coupon by ID', schema: objectSchema({ id: couponId }, ['id']), options: [fieldOption, preview], example: 'pancake coupons get CPN_0000000000000000000001 --json' }, documentation,
|
|
46
|
+
request: (input, options) => ({ query: `query CliCoupon($id: String!) { item: coupon(id: $id) { ${selection(couponFields, options.fields)} } }`, variables: { id: input.id } }) },
|
|
47
|
+
];
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { previewFields } from "./action-previews.js";
|
|
2
|
+
function restrictionsPreview(input) {
|
|
3
|
+
return previewFields(input, ['perCustomerLimit', 'maxRedemptions', 'expiresAt', 'minimumAmount']);
|
|
4
|
+
}
|
|
5
|
+
function promotionPreview(input, visible) {
|
|
6
|
+
const result = previewFields(input, visible);
|
|
7
|
+
if (input.restrictions !== undefined)
|
|
8
|
+
result.restrictions = restrictionsPreview(input.restrictions);
|
|
9
|
+
return result;
|
|
10
|
+
}
|
|
11
|
+
export function couponPreview(input) {
|
|
12
|
+
const result = previewFields(input, ['id', 'storeId', 'discount', 'duration', 'durationInPeriods', 'productIds', 'maxRedemptions', 'redeemBy']);
|
|
13
|
+
if (Array.isArray(input.promotionCodes))
|
|
14
|
+
result.promotionCodes = input.promotionCodes.map(item => promotionPreview(item, []));
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
export const promotionCodePreview = (input) => promotionPreview(input, ['id', 'couponId', 'count', 'length']);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { objectSchema, storeId } from "./schemas.js";
|
|
2
|
+
import { positiveAmount, currency, productId } from "./action-values.js";
|
|
3
|
+
export const couponId = { type: 'string', pattern: '^CPN_[A-Za-z0-9]{22}$' };
|
|
4
|
+
const promotionId = { type: 'string', pattern: '^PMC_[A-Za-z0-9]{22}$' };
|
|
5
|
+
const name = { type: 'string', minLength: 1, maxLength: 64, pattern: '\\S' };
|
|
6
|
+
const code = { type: 'string', pattern: '^[A-Za-z0-9-]{3,32}$' };
|
|
7
|
+
const limit = { type: ['integer', 'null'], minimum: 1, maximum: 2147483647 };
|
|
8
|
+
const date = { type: ['string', 'null'], pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$' };
|
|
9
|
+
const amounts = { type: 'object', minProperties: 1, propertyNames: currency, additionalProperties: positiveAmount };
|
|
10
|
+
const restrictions = objectSchema({
|
|
11
|
+
customerEmails: { type: 'array', maxItems: 100, items: { type: 'string', pattern: '^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$' } },
|
|
12
|
+
perCustomerLimit: limit, maxRedemptions: limit, expiresAt: date,
|
|
13
|
+
minimumAmount: { anyOf: [amounts, { type: 'null' }] },
|
|
14
|
+
});
|
|
15
|
+
const promotion = { code, restrictions };
|
|
16
|
+
export const discountSchemas = {
|
|
17
|
+
'coupons.create': {
|
|
18
|
+
...objectSchema({ storeId, name, code,
|
|
19
|
+
discount: { oneOf: [objectSchema({ type: { const: 'percentage' }, percentOff: { type: 'number', exclusiveMinimum: 0, maximum: 100, multipleOf: 0.01 } }, ['type', 'percentOff']), objectSchema({ type: { const: 'fixed_amount' }, amountOff: amounts }, ['type', 'amountOff'])] },
|
|
20
|
+
duration: { enum: ['once', 'repeating', 'forever'] }, durationInPeriods: limit,
|
|
21
|
+
productIds: { type: 'array', maxItems: 100, items: productId }, maxRedemptions: limit, redeemBy: date,
|
|
22
|
+
promotionCodes: { type: 'array', maxItems: 20, items: objectSchema(promotion) },
|
|
23
|
+
}, ['storeId', 'name', 'discount']),
|
|
24
|
+
if: { required: ['duration'], properties: { duration: { const: 'repeating' } } },
|
|
25
|
+
then: { required: ['durationInPeriods'], properties: { durationInPeriods: { type: 'integer' } } },
|
|
26
|
+
else: { properties: { durationInPeriods: { type: 'null' } } },
|
|
27
|
+
},
|
|
28
|
+
'coupons.update': objectSchema({ id: couponId, name }, ['id', 'name']),
|
|
29
|
+
'coupons.deactivate': objectSchema({ id: couponId }, ['id']),
|
|
30
|
+
'promotion-codes.create': objectSchema({ couponId, ...promotion }, ['couponId']),
|
|
31
|
+
'promotion-codes.generate': objectSchema({ couponId, count: { type: 'integer', minimum: 1, maximum: 500 }, prefix: { type: 'string', pattern: '^[A-Za-z0-9-]{1,12}$' }, length: { type: 'integer', minimum: 8, maximum: 16 }, restrictions }, ['couponId', 'count']),
|
|
32
|
+
'promotion-codes.deactivate': objectSchema({ id: promotionId }, ['id']),
|
|
33
|
+
};
|
|
34
|
+
const string = { type: 'string' };
|
|
35
|
+
const stringFilter = objectSchema({ eq: string, ne: string, in: { type: 'array', items: string }, notIn: { type: 'array', items: string }, contains: string, startsWith: string, endsWith: string, isNull: { type: 'boolean' } });
|
|
36
|
+
const statusFilter = (values) => objectSchema({ eq: { enum: values }, ne: { enum: values }, in: { type: 'array', items: { enum: values } }, notIn: { type: 'array', items: { enum: values } } });
|
|
37
|
+
const createdAt = objectSchema({ ...Object.fromEntries(['eq', 'ne', 'gt', 'gte', 'lt', 'lte'].map(key => [key, string])), isNull: { type: 'boolean' } });
|
|
38
|
+
export const couponListSchema = objectSchema({ storeId, filter: objectSchema({ id: stringFilter, name: stringFilter, code: stringFilter, anyCode: objectSchema({ eq: string, in: { type: 'array', items: string }, startsWith: string, contains: string }), status: statusFilter(['active', 'inactive', 'failed']), isExhausted: { type: 'boolean' }, isExpired: { type: 'boolean' }, isRedeemable: { type: 'boolean' }, createdAt }) }, ['storeId']);
|
|
39
|
+
export const promotionListSchema = objectSchema({ couponId, filter: objectSchema({ id: stringFilter, code: stringFilter, batchId: stringFilter, status: statusFilter(['active', 'inactive']), createdAt }) }, ['couponId']);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { argumentError } from "../contracts/errors.js";
|
|
2
|
+
export function validateDiscountInput(id, input) {
|
|
3
|
+
if (!id.startsWith('coupons.') && !id.startsWith('promotion-codes.'))
|
|
4
|
+
return;
|
|
5
|
+
if (id === 'coupons.create') {
|
|
6
|
+
const codes = [input.code, ...(input.promotionCodes ?? []).map(item => item.code)].filter((value) => typeof value === 'string').map(value => value.toUpperCase());
|
|
7
|
+
if (new Set(codes).size !== codes.length)
|
|
8
|
+
throw argumentError('Coupon and promotion codes must be unique within the request (case-insensitive).');
|
|
9
|
+
}
|
|
10
|
+
const restrictions = [input.restrictions, ...(input.promotionCodes ?? []).map(item => item.restrictions)].filter((value) => !!value && typeof value === 'object');
|
|
11
|
+
for (const value of [input.redeemBy, ...restrictions.map(item => item.expiresAt)]) {
|
|
12
|
+
if (value === undefined || value === null)
|
|
13
|
+
continue;
|
|
14
|
+
if (typeof value !== 'string' || !Number.isFinite(Date.parse(value)) || Date.parse(value) <= Date.now() + 60_000)
|
|
15
|
+
throw argumentError('Discount expiry must be a valid ISO datetime more than 60 seconds in the future.');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { loopbackTarget } from "../contracts/loopback-target.js";
|
|
2
|
+
import { argumentError } from "../contracts/errors.js";
|
|
3
|
+
export function listenInput(options) {
|
|
4
|
+
if (!options.storeId || !/^STO_[A-Za-z0-9]+$/.test(options.storeId))
|
|
5
|
+
throw argumentError('Provide a valid --store-id.');
|
|
6
|
+
const url = loopbackTarget(options.forwardTo);
|
|
7
|
+
const events = options.events?.split(',');
|
|
8
|
+
if (events && (events.length > 100 || events.some(event => !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(event)) || new Set(events).size !== events.length)) {
|
|
9
|
+
throw argumentError('--events requires unique comma-separated event names.');
|
|
10
|
+
}
|
|
11
|
+
return { storeId: options.storeId, url, events, environment: options.live ? 'prod' : 'test' };
|
|
12
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const policies = {
|
|
2
|
+
'products.publish': 'test-to-prod', 'groups.publish': 'test-to-prod',
|
|
3
|
+
'stores.create': 'shared', 'stores.update': 'shared', 'stores.delete': 'shared',
|
|
4
|
+
'recipients.add': 'shared', 'recipients.update': 'shared', 'recipients.remove': 'shared',
|
|
5
|
+
'webhook.add': 'test-only', 'webhook.update': 'test-only', 'webhook.remove': 'test-only',
|
|
6
|
+
};
|
|
7
|
+
/** One command rule for discovery, offline previews and verified execution. */
|
|
8
|
+
export function operationImpact(command, environment) {
|
|
9
|
+
const impactPolicy = command.effect === 'write' ? policies[command.id] ?? 'selected-environment' : 'none';
|
|
10
|
+
const fixedImpacts = { none: null, 'test-only': 'test', shared: 'shared', 'test-to-prod': 'test-to-prod' };
|
|
11
|
+
const impact = impactPolicy === 'selected-environment' ? environment ?? null : fixedImpacts[impactPolicy];
|
|
12
|
+
const production = environment === undefined ? 'when-prod' : environment === 'prod';
|
|
13
|
+
const requiresProductionConfirmation = { none: false, 'test-only': false, shared: production, 'test-to-prod': true, 'selected-environment': production };
|
|
14
|
+
return { impact, impactPolicy, requiresProductionConfirmation: requiresProductionConfirmation[impactPolicy],
|
|
15
|
+
requiresSharedConfirmation: impactPolicy === 'shared' };
|
|
16
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { objectSchema, string } from "./schemas.js";
|
|
2
|
+
import { amount, currency, productId, positiveAmount, taxCategory } from "./action-values.js";
|
|
3
|
+
const priceSchema = (subscription) => ({
|
|
4
|
+
type: 'object', description: 'Replaces all existing prices. Omitted currencies are removed; include every currency and price setting to keep.', minProperties: 1, propertyNames: currency,
|
|
5
|
+
additionalProperties: objectSchema({
|
|
6
|
+
amount: positiveAmount, taxCategory,
|
|
7
|
+
...(subscription ? { trialAmount: amount } : {}),
|
|
8
|
+
}, ['amount', 'taxCategory']),
|
|
9
|
+
});
|
|
10
|
+
const updateFields = {
|
|
11
|
+
id: productId,
|
|
12
|
+
name: { ...string, maxLength: 64 },
|
|
13
|
+
description: { type: ['string', 'null'] },
|
|
14
|
+
media: { type: 'array', items: objectSchema({ type: { enum: ['image', 'video'] }, url: string, alt: { type: 'string' }, thumbnail: string }, ['type', 'url']) },
|
|
15
|
+
successUrl: { anyOf: [{ type: 'string', format: 'http-url', maxLength: 512 }, { const: '' }, { type: 'null' }] },
|
|
16
|
+
};
|
|
17
|
+
export const productUpdateSchema = { oneOf: [
|
|
18
|
+
objectSchema({ ...updateFields, type: { const: 'onetime' }, prices: priceSchema(false), metadata: { type: 'object', maxProperties: 50, additionalProperties: true } }, ['type', 'id']),
|
|
19
|
+
objectSchema({
|
|
20
|
+
...updateFields, type: { const: 'subscription' }, prices: priceSchema(true),
|
|
21
|
+
billingPeriod: { enum: ['weekly', 'monthly', 'quarterly', 'yearly'] },
|
|
22
|
+
metadata: { type: 'object', properties: { trialDays: { type: 'integer', minimum: 1, maximum: 365 } }, additionalProperties: true },
|
|
23
|
+
}, ['type', 'id']),
|
|
24
|
+
] };
|
|
25
|
+
export const productPublishSchema = objectSchema({ type: { enum: ['onetime', 'subscription'] }, id: productId }, ['type', 'id']);
|
|
26
|
+
export const productStatusSchema = objectSchema({ type: { enum: ['onetime', 'subscription'] }, id: productId, status: { enum: ['active', 'inactive'] } }, ['type', 'id', 'status']);
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export function productPreview(input) {
|
|
2
|
+
return { type: input.type, storeId: input.storeId, name: input.name, prices: input.prices, billingPeriod: input.billingPeriod,
|
|
3
|
+
metadata: input.metadata === undefined ? undefined : '[redacted]', description: input.description === undefined ? undefined : '[redacted]',
|
|
4
|
+
media: input.media === undefined ? undefined : '[redacted]', successUrl: input.successUrl === undefined ? undefined : '[redacted]' };
|
|
5
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { discountReadSpecs } from "./discount-definitions.js";
|
|
2
|
+
import { argumentError } from "../contracts/errors.js";
|
|
3
|
+
import { objectSchema, storeId, merchantId } from "./schemas.js";
|
|
4
|
+
import { orderListSchema, productId, productListSchema, querySchema, readFilters, readId } from "./read-schemas.js";
|
|
5
|
+
import { filterArgument, readOnlyRequest, selection } from "./read-query.js";
|
|
6
|
+
const docs = 'https://docs.waffo.ai/api-reference/endpoints/';
|
|
7
|
+
const productDocs = `${docs}graphql/stores-and-products`;
|
|
8
|
+
const orderDocs = `${docs}graphql/orders-and-payments`;
|
|
9
|
+
const previewOption = ['--dry-run', 'Validate and preview the query offline'];
|
|
10
|
+
const fieldOption = ['--fields <names>', 'Comma-separated documented top-level resource fields'];
|
|
11
|
+
const typeOption = ['--type <type>', 'onetime or subscription (required)'];
|
|
12
|
+
const listOptions = [['--limit <number>', 'Page size, 1–100 (default 20)'], ['--offset <number>', 'Zero-based offset (default 0)'], fieldOption, previewOption];
|
|
13
|
+
const fields = (...names) => Object.fromEntries(names.map(name => [name, name]));
|
|
14
|
+
const productFields = { ...fields('id', 'name', 'status', 'createdAt', 'updatedAt'), prices: 'prices { currency priceInfo { amount taxCategory } }' };
|
|
15
|
+
const subscriptionFields = { ...productFields, billingPeriod: 'billingPeriod', prices: 'prices { currency priceInfo { amount taxCategory trialAmount } }' };
|
|
16
|
+
const onetimeOrderFields = { ...fields('id', 'buyerEmail', 'currency', 'status', 'orderMerchantExternalId', 'createdAt'), priceSnapshot: 'priceSnapshot { currency subtotal taxAmount total taxCategory }' };
|
|
17
|
+
const subscriptionOrderFields = fields('id', 'buyerEmail', 'status', 'billingPeriod', 'orderMerchantExternalId', 'createdAt', 'currentPeriodStart', 'currentPeriodEnd', 'currentPeriodNumber');
|
|
18
|
+
const paymentFields = { ...fields('id', 'orderId', 'status', 'refundStatus', 'orderMerchantExternalId', 'periodNumber', 'createdAt'), snapshotAmountDetails: 'snapshotAmountDetails { subtotal taxAmount total currency }' };
|
|
19
|
+
const refundFields = { ...fields('id', 'paymentId', 'ticketId', 'status', 'orderMerchantExternalId', 'refundTicketMerchantExternalId', 'createdAt'), pspAmountDetails: 'pspAmountDetails { amount currency }' };
|
|
20
|
+
const refundTicketFields = { ...fields('id', 'status', 'refundTicketMerchantExternalId', 'reviewNote', 'rejectReason', 'executedAt', 'createdAt'), versionData: 'versionData { reason requestedAmount { amount currency } }' };
|
|
21
|
+
const storeFields = fields('id', 'name', 'status', 'slug', 'supportEmail', 'website', 'prodEnabled', 'createdAt', 'updatedAt');
|
|
22
|
+
function productType(options) {
|
|
23
|
+
if (options.type !== 'onetime' && options.type !== 'subscription')
|
|
24
|
+
throw argumentError('Provide --type onetime or --type subscription.');
|
|
25
|
+
return options.type;
|
|
26
|
+
}
|
|
27
|
+
function listRequest(root, resourceFields, input, options, storeArgument = false) {
|
|
28
|
+
const args = ['limit: $limit', 'offset: $offset', filterArgument((input.filter ?? {}))];
|
|
29
|
+
if (storeArgument)
|
|
30
|
+
args.push('storeId: $storeId');
|
|
31
|
+
return {
|
|
32
|
+
query: `query CliRead($limit: Int!, $offset: Int!${storeArgument ? ', $storeId: String!' : ''}) { items: ${root}(${args.filter(Boolean).join(', ')}) { ${selection(resourceFields, options.fields)} } }`,
|
|
33
|
+
variables: { limit: options.limit ?? 20, offset: options.offset ?? 0, ...(storeArgument ? { storeId: input.storeId } : {}) },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function listSpec(id, root, resourceFields, schema, documentation, storeArgument = false) {
|
|
37
|
+
return {
|
|
38
|
+
definition: { id: `${id}.list`, path: `${id} list`, description: `Read one page of ${id}`, effect: 'read', file: true, schema, options: listOptions, example: `pancake ${id} list${storeArgument ? ' --store-id STO_abc' : ''} --limit 20 --json` },
|
|
39
|
+
documentation: [documentation], request: (input, options) => listRequest(root, resourceFields, input, options, storeArgument),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function getSpec(id, root, resourceFields, idSchema, documentation, exampleId) {
|
|
43
|
+
return {
|
|
44
|
+
definition: { id: `${id}.get`, path: `${id} get`, argument: 'id', description: `Get a ${root} by ID`, effect: 'read', schema: objectSchema({ id: idSchema }, ['id']), options: [fieldOption, previewOption], example: `pancake ${id} get ${exampleId} --json` },
|
|
45
|
+
documentation: [documentation], request: (input, options) => ({ query: `query CliRead($id: String!) { item: ${root}(id: $id) { ${selection(resourceFields, options.fields)} } }`, variables: { id: input.id } }),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const ordersList = listSpec('orders', 'onetimeOrders', onetimeOrderFields, orderListSchema, orderDocs, true);
|
|
49
|
+
export const readSpecs = [
|
|
50
|
+
...discountReadSpecs,
|
|
51
|
+
getSpec('stores', 'store', storeFields, storeId, productDocs, 'STO_abc'),
|
|
52
|
+
{
|
|
53
|
+
definition: { id: 'products.list', path: 'products list', description: 'List products in the credential environment; JSON filter file is optional', effect: 'read', file: true, schema: productListSchema, options: [typeOption, ...listOptions], example: 'pancake products list --type onetime --store-id STO_abc --json' },
|
|
54
|
+
documentation: [productDocs, `${docs}graphql/overview`],
|
|
55
|
+
request(input, options) {
|
|
56
|
+
const type = productType(options);
|
|
57
|
+
return listRequest(`${type}Products`, type === 'onetime' ? productFields : subscriptionFields, input, options, input.storeId !== undefined);
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
definition: { id: 'products.versions', path: 'products versions', argument: 'id', description: 'Read product version history (no pagination)', effect: 'read', schema: objectSchema({ id: productId }, ['id']), options: [typeOption, fieldOption, previewOption], example: 'pancake products versions PROD_abc --type onetime --json' },
|
|
62
|
+
documentation: [productDocs],
|
|
63
|
+
request(input, options) {
|
|
64
|
+
const type = productType(options);
|
|
65
|
+
const versionFields = fields('id', 'versionNumber', 'name', 'createdAt');
|
|
66
|
+
if (type === 'subscription')
|
|
67
|
+
versionFields.billingPeriod = 'billingPeriod';
|
|
68
|
+
return { query: `query CliVersions($productId: String!) { items: ${type}ProductVersions(productId: $productId) { ${selection(versionFields, options.fields)} } }`, variables: { productId: input.id } };
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
...ordersList,
|
|
73
|
+
definition: { ...ordersList.definition, description: 'List onetime or subscription orders in a store', options: [typeOption, ...listOptions], example: 'pancake orders list --type onetime --store-id STO_abc --json' },
|
|
74
|
+
request: (input, options) => {
|
|
75
|
+
const type = productType(options);
|
|
76
|
+
return listRequest(`${type}Orders`, type === 'onetime' ? onetimeOrderFields : subscriptionOrderFields, input, options, true);
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
listSpec('subscriptions', 'subscriptionOrders', subscriptionOrderFields, orderListSchema, orderDocs, true),
|
|
80
|
+
listSpec('payments', 'payments', paymentFields, objectSchema({ filter: readFilters.payments }), orderDocs),
|
|
81
|
+
getSpec('payments', 'payment', paymentFields, readId, orderDocs, 'PAY_abc'),
|
|
82
|
+
listSpec('refunds', 'refunds', refundFields, objectSchema({ filter: readFilters.refunds }), orderDocs),
|
|
83
|
+
getSpec('refunds', 'refund', refundFields, readId, orderDocs, 'RFD_abc'),
|
|
84
|
+
listSpec('refund-tickets', 'refundTickets', refundTicketFields, objectSchema({ filter: readFilters.refundTickets }), orderDocs),
|
|
85
|
+
listSpec('recipients', 'storeNotificationRecipients', { ...fields('id', 'email', 'isPrimary', 'createdAt'), preferences: 'preferences { notifyNewOrders notifyNewSubscriptions notifySubscriptionCanceled notifySubscriptionRenewed notifySubscriptionEnded notifySubscriptionPastDue notifySubscriptionUncanceled notifySubscriptionPlanChanged notifyChargeback notifyRefundSucceeded }' }, objectSchema({ storeId }, ['storeId']), `${docs}notification-recipients/overview`, true),
|
|
86
|
+
listSpec('merchants', 'merchants', fields('id', 'email', 'status', 'createdAt'), objectSchema({}), productDocs),
|
|
87
|
+
getSpec('merchants', 'merchant', fields('id', 'email', 'status', 'createdAt', 'updatedAt'), merchantId, productDocs, 'MER_abc'),
|
|
88
|
+
...['graphql', 'analytics'].map(resource => ({
|
|
89
|
+
definition: { id: `${resource}.query`, path: `${resource} query`, description: resource === 'analytics' ? 'Run a custom read-only analytics GraphQL document with explicit nested selections' : 'Run exactly one read-only GraphQL operation; fragments and variables are supported', effect: 'read', file: true, schema: querySchema, options: [previewOption, ['--output <path>', 'Export response to a new private file; required for arbitrary GraphQL']], example: `pancake ${resource} query --file query.json --dry-run --json` },
|
|
90
|
+
sensitiveOutput: true, documentation: [`${docs}graphql/${resource === 'analytics' ? 'analytics' : 'overview'}`], request: (input) => readOnlyRequest(input),
|
|
91
|
+
})),
|
|
92
|
+
];
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Kind, getOperationAST, parse, print } from 'graphql';
|
|
2
|
+
import { argumentError } from "../contracts/errors.js";
|
|
3
|
+
export function graphqlValue(value) {
|
|
4
|
+
if (value === null)
|
|
5
|
+
return { kind: Kind.NULL };
|
|
6
|
+
if (typeof value === 'string')
|
|
7
|
+
return { kind: Kind.STRING, value };
|
|
8
|
+
if (typeof value === 'boolean')
|
|
9
|
+
return { kind: Kind.BOOLEAN, value };
|
|
10
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
11
|
+
return { kind: Number.isInteger(value) ? Kind.INT : Kind.FLOAT, value: String(value) };
|
|
12
|
+
if (Array.isArray(value))
|
|
13
|
+
return { kind: Kind.LIST, values: value.map(graphqlValue) };
|
|
14
|
+
if (typeof value === 'object' && value !== null) {
|
|
15
|
+
return { kind: Kind.OBJECT, fields: Object.entries(value).map(([key, field]) => {
|
|
16
|
+
if (!/^[_A-Za-z][_0-9A-Za-z]*$/.test(key))
|
|
17
|
+
throw argumentError('Filter keys must be GraphQL names.');
|
|
18
|
+
return { kind: Kind.OBJECT_FIELD, name: { kind: Kind.NAME, value: key }, value: graphqlValue(field) };
|
|
19
|
+
}) };
|
|
20
|
+
}
|
|
21
|
+
throw argumentError('Filters must contain JSON values.');
|
|
22
|
+
}
|
|
23
|
+
export function filterArgument(filter) {
|
|
24
|
+
return Object.keys(filter).length ? `filter: ${print(graphqlValue(filter))}` : '';
|
|
25
|
+
}
|
|
26
|
+
export function selection(fields, selected) {
|
|
27
|
+
const names = selected === undefined ? Object.keys(fields) : selected.split(',');
|
|
28
|
+
if (!names.length || names.some(name => !Object.hasOwn(fields, name)))
|
|
29
|
+
throw argumentError('Unknown field selection. Use the documented result field names.');
|
|
30
|
+
return [...new Set(names)].map(name => fields[name]).join(' ');
|
|
31
|
+
}
|
|
32
|
+
export function readOnlyRequest(input) {
|
|
33
|
+
if (typeof input.query !== 'string' || !input.query.trim())
|
|
34
|
+
throw argumentError('Provide a GraphQL query string in the JSON file.');
|
|
35
|
+
if (input.variables !== undefined && (typeof input.variables !== 'object' || input.variables === null || Array.isArray(input.variables)))
|
|
36
|
+
throw argumentError('GraphQL variables must be a JSON object.');
|
|
37
|
+
let document;
|
|
38
|
+
try {
|
|
39
|
+
document = parse(input.query);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw argumentError('The GraphQL document has invalid syntax.');
|
|
43
|
+
}
|
|
44
|
+
const operation = getOperationAST(document);
|
|
45
|
+
if (!operation || operation.operation !== 'query' || document.definitions.some(definition => definition.kind !== Kind.FRAGMENT_DEFINITION && (definition.kind !== Kind.OPERATION_DEFINITION || definition.operation !== 'query'))) {
|
|
46
|
+
throw argumentError('Provide exactly one query operation; mutations, subscriptions and schema definitions are not allowed.');
|
|
47
|
+
}
|
|
48
|
+
return { query: print(document), variables: (input.variables ?? {}) };
|
|
49
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { objectSchema, storeId } from "./schemas.js";
|
|
2
|
+
export const readId = { type: 'string', minLength: 1, maxLength: 128 };
|
|
3
|
+
export const productId = { type: 'string', pattern: '^PROD_[A-Za-z0-9]+$' };
|
|
4
|
+
const string = { type: 'string' };
|
|
5
|
+
const stringFilter = objectSchema({ eq: string, ne: string, in: { type: 'array', items: string }, contains: string });
|
|
6
|
+
const dateFilter = objectSchema({ eq: string, gt: string, lt: string, gte: string, lte: string });
|
|
7
|
+
const amountFilter = objectSchema(Object.fromEntries(['eq', 'ne', 'gt', 'gte', 'lt', 'lte'].map(key => [key, { type: 'string', pattern: '^\\d+(\\.\\d+)?$' }])));
|
|
8
|
+
export const readFilters = {
|
|
9
|
+
products: objectSchema({ status: stringFilter }),
|
|
10
|
+
orders: objectSchema({ status: stringFilter, createdAt: dateFilter, orderMerchantExternalId: stringFilter }),
|
|
11
|
+
payments: { ...objectSchema({ status: stringFilter, createdAt: dateFilter, orderMerchantExternalId: stringFilter, amount: amountFilter, currency: stringFilter }), if: { required: ['amount'] }, then: { required: ['currency'], properties: { currency: objectSchema({ eq: { type: 'string', pattern: '^[A-Za-z]{3}$' } }, ['eq']) } } },
|
|
12
|
+
refunds: objectSchema({ paymentId: stringFilter, refundTicketMerchantExternalId: stringFilter }),
|
|
13
|
+
refundTickets: objectSchema({ status: stringFilter, subjectId: stringFilter, refundTicketMerchantExternalId: stringFilter }),
|
|
14
|
+
};
|
|
15
|
+
export const productListSchema = objectSchema({ storeId, filter: readFilters.products });
|
|
16
|
+
export const orderListSchema = objectSchema({ storeId, filter: readFilters.orders }, ['storeId']);
|
|
17
|
+
export const querySchema = objectSchema({ query: { type: 'string', minLength: 1 }, variables: { type: 'object', additionalProperties: true } }, ['query']);
|